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;
74
75#[cfg(feature = "std")]
76/// Implementation [`RecursionCounter`] if std is available
77mod recursion {
78    use std::cell::Cell;
79    use std::rc::Rc;
80
81    use super::ParserError;
82
83    /// Tracks remaining recursion depth. This value is decremented on
84    /// each call to [`RecursionCounter::try_decrease()`], when it reaches 0 an error will
85    /// be returned.
86    ///
87    /// Note: Uses an [`std::rc::Rc`] and [`std::cell::Cell`] in order to satisfy the Rust
88    /// borrow checker so the automatic [`DepthGuard`] decrement a
89    /// reference to the counter.
90    ///
91    /// Note: when "recursive-protection" feature is enabled, this crate uses additional stack overflow protection
92    /// for some of its recursive methods. See [`recursive::recursive`] for more information.
93    pub(crate) struct RecursionCounter {
94        remaining_depth: Rc<Cell<usize>>,
95    }
96
97    impl RecursionCounter {
98        /// Creates a [`RecursionCounter`] with the specified maximum
99        /// depth
100        pub fn new(remaining_depth: usize) -> Self {
101            Self {
102                remaining_depth: Rc::new(remaining_depth.into()),
103            }
104        }
105
106        /// Decreases the remaining depth by 1.
107        ///
108        /// Returns [`Err`] if the remaining depth falls to 0.
109        ///
110        /// Returns a [`DepthGuard`] which will adds 1 to the
111        /// remaining depth upon drop;
112        pub fn try_decrease(&self) -> Result<DepthGuard, ParserError> {
113            let old_value = self.remaining_depth.get();
114            // ran out of space
115            if old_value == 0 {
116                Err(ParserError::RecursionLimitExceeded)
117            } else {
118                self.remaining_depth.set(old_value - 1);
119                Ok(DepthGuard::new(Rc::clone(&self.remaining_depth)))
120            }
121        }
122    }
123
124    /// Guard that increases the remaining depth by 1 on drop
125    pub struct DepthGuard {
126        remaining_depth: Rc<Cell<usize>>,
127    }
128
129    impl DepthGuard {
130        fn new(remaining_depth: Rc<Cell<usize>>) -> Self {
131            Self { remaining_depth }
132        }
133    }
134    impl Drop for DepthGuard {
135        fn drop(&mut self) {
136            let old_value = self.remaining_depth.get();
137            self.remaining_depth.set(old_value + 1);
138        }
139    }
140}
141
142#[cfg(not(feature = "std"))]
143mod recursion {
144    /// Implementation [`RecursionCounter`] if std is NOT available (and does not
145    /// guard against stack overflow).
146    ///
147    /// Has the same API as the std [`RecursionCounter`] implementation
148    /// but does not actually limit stack depth.
149    pub(crate) struct RecursionCounter {}
150
151    impl RecursionCounter {
152        pub fn new(_remaining_depth: usize) -> Self {
153            Self {}
154        }
155        pub fn try_decrease(&self) -> Result<DepthGuard, super::ParserError> {
156            Ok(DepthGuard {})
157        }
158    }
159
160    pub struct DepthGuard {}
161}
162
163#[derive(PartialEq, Eq)]
164/// Indicates whether a parser element is optional or mandatory.
165pub enum IsOptional {
166    /// The element is optional.
167    Optional,
168    /// The element is mandatory.
169    Mandatory,
170}
171
172/// Indicates if a table expression is lateral.
173pub enum IsLateral {
174    /// The expression is lateral.
175    Lateral,
176    /// The expression is not lateral.
177    NotLateral,
178}
179
180/// Represents a wildcard expression used in SELECT lists.
181pub enum WildcardExpr {
182    /// A specific expression used instead of a wildcard.
183    Expr(Expr),
184    /// A qualified wildcard like `table.*`.
185    QualifiedWildcard(ObjectName),
186    /// An unqualified `*` wildcard.
187    Wildcard,
188}
189
190impl From<TokenizerError> for ParserError {
191    fn from(e: TokenizerError) -> Self {
192        ParserError::TokenizerError(e.to_string())
193    }
194}
195
196impl fmt::Display for ParserError {
197    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
198        write!(
199            f,
200            "sql parser error: {}",
201            match self {
202                ParserError::TokenizerError(s) => s,
203                ParserError::ParserError(s) => s,
204                ParserError::RecursionLimitExceeded => "recursion limit exceeded",
205            }
206        )
207    }
208}
209
210impl core::error::Error for ParserError {}
211
212// By default, allow expressions up to this deep before erroring
213const DEFAULT_REMAINING_DEPTH: usize = 50;
214
215// A constant EOF token that can be referenced.
216const EOF_TOKEN: TokenWithSpan = TokenWithSpan {
217    token: Token::EOF,
218    span: Span {
219        start: Location { line: 0, column: 0 },
220        end: Location { line: 0, column: 0 },
221    },
222};
223
224/// Composite types declarations using angle brackets syntax can be arbitrary
225/// nested such that the following declaration is possible:
226///      `ARRAY<ARRAY<INT>>`
227/// But the tokenizer recognizes the `>>` as a ShiftRight token.
228/// We work around that limitation when parsing a data type by accepting
229/// either a `>` or `>>` token in such cases, remembering which variant we
230/// matched.
231/// In the latter case having matched a `>>`, the parent type will not look to
232/// match its closing `>` as a result since that will have taken place at the
233/// child type.
234///
235/// See [Parser::parse_data_type] for details
236struct MatchedTrailingBracket(bool);
237
238impl From<bool> for MatchedTrailingBracket {
239    fn from(value: bool) -> Self {
240        Self(value)
241    }
242}
243
244/// Options that control how the [`Parser`] parses SQL text
245#[derive(Debug, Clone, PartialEq, Eq)]
246pub struct ParserOptions {
247    /// Allow trailing commas in lists (e.g. `a, b,`).
248    pub trailing_commas: bool,
249    /// Controls how literal values are unescaped. See
250    /// [`Tokenizer::with_unescape`] for more details.
251    pub unescape: bool,
252    /// Controls if the parser expects a semi-colon token
253    /// between statements. Default is `true`.
254    pub require_semicolon_stmt_delimiter: bool,
255}
256
257impl Default for ParserOptions {
258    fn default() -> Self {
259        Self {
260            trailing_commas: false,
261            unescape: true,
262            require_semicolon_stmt_delimiter: true,
263        }
264    }
265}
266
267impl ParserOptions {
268    /// Create a new [`ParserOptions`]
269    pub fn new() -> Self {
270        Default::default()
271    }
272
273    /// Set if trailing commas are allowed.
274    ///
275    /// If this option is `false` (the default), the following SQL will
276    /// not parse. If the option is `true`, the SQL will parse.
277    ///
278    /// ```sql
279    ///  SELECT
280    ///   foo,
281    ///   bar,
282    ///  FROM baz
283    /// ```
284    pub fn with_trailing_commas(mut self, trailing_commas: bool) -> Self {
285        self.trailing_commas = trailing_commas;
286        self
287    }
288
289    /// Set if literal values are unescaped. Defaults to true. See
290    /// [`Tokenizer::with_unescape`] for more details.
291    pub fn with_unescape(mut self, unescape: bool) -> Self {
292        self.unescape = unescape;
293        self
294    }
295}
296
297#[derive(Copy, Clone)]
298enum ParserState {
299    /// The default state of the parser.
300    Normal,
301    /// The state when parsing a CONNECT BY expression. This allows parsing
302    /// PRIOR expressions while still allowing prior as an identifier name
303    /// in other contexts.
304    ConnectBy,
305    /// The state when parsing column definitions.  This state prohibits
306    /// NOT NULL as an alias for IS NOT NULL.  For example:
307    /// ```sql
308    /// CREATE TABLE foo (abc BIGINT NOT NULL);
309    /// ```
310    ColumnDefinition,
311}
312
313/// A SQL Parser
314///
315/// This struct is the main entry point for parsing SQL queries.
316///
317/// # Functionality:
318/// * Parsing SQL: see examples on [`Parser::new`] and [`Parser::parse_sql`]
319/// * Controlling recursion: See [`Parser::with_recursion_limit`]
320/// * Controlling parser options: See [`Parser::with_options`]
321/// * Providing your own tokens: See [`Parser::with_tokens`]
322///
323/// # Internals
324///
325/// The parser uses a [`Tokenizer`] to tokenize the input SQL string into a
326/// `Vec` of [`TokenWithSpan`]s and maintains an `index` to the current token
327/// being processed. The token vec may contain multiple SQL statements.
328///
329/// * The "current" token is the token at `index - 1`
330/// * The "next" token is the token at `index`
331/// * The "previous" token is the token at `index - 2`
332///
333/// If `index` is equal to the length of the token stream, the 'next' token is
334/// [`Token::EOF`].
335///
336/// For example, the SQL string "SELECT * FROM foo" will be tokenized into
337/// following tokens:
338/// ```text
339///  [
340///    "SELECT", // token index 0
341///    " ",      // whitespace
342///    "*",
343///    " ",
344///    "FROM",
345///    " ",
346///    "foo"
347///   ]
348/// ```
349///
350///
351pub struct Parser<'a> {
352    /// The tokens
353    tokens: Vec<TokenWithSpan>,
354    /// The index of the first unprocessed token in [`Parser::tokens`].
355    index: usize,
356    /// The current state of the parser.
357    state: ParserState,
358    /// The SQL dialect to use.
359    dialect: &'a dyn Dialect,
360    /// Additional options that allow you to mix & match behavior
361    /// otherwise constrained to certain dialects (e.g. trailing
362    /// commas) and/or format of parse (e.g. unescaping).
363    options: ParserOptions,
364    /// Ensures the stack does not overflow by limiting recursion depth.
365    recursion_counter: RecursionCounter,
366    /// Cached failures from `parse_prefix` calls that returned `Err`. See
367    /// [`Parser::parse_prefix`] for the 2^N patterns this guards.
368    failed_prefix_positions: BTreeMap<usize, ExprPrefixError>,
369    /// Cached failures from the speculative reserved-word prefix arm. See
370    /// [`Parser::parse_prefix`] for the 2^N patterns this guards.
371    failed_reserved_word_prefix_positions: BTreeMap<usize, ExprPrefixError>,
372    /// Cached failures from the speculative derived-table arm of
373    /// `parse_table_factor`. See [`Parser::parse_table_factor`] for the 2^N
374    /// pattern this guards.
375    failed_derived_table_factor_positions: BTreeSet<usize>,
376}
377
378/// Copy marker for a [`ParserError`] cached by the `parse_prefix` failure
379/// memoization, so the caches hold no strings.
380#[derive(Debug, Clone, Copy)]
381enum ExprPrefixError {
382    RecursionLimitExceeded,
383    Err,
384}
385
386impl From<&ParserError> for ExprPrefixError {
387    fn from(e: &ParserError) -> Self {
388        match e {
389            ParserError::RecursionLimitExceeded => Self::RecursionLimitExceeded,
390            _ => Self::Err,
391        }
392    }
393}
394
395impl<'a> Parser<'a> {
396    /// Create a parser for a [`Dialect`]
397    ///
398    /// See also [`Parser::parse_sql`]
399    ///
400    /// Example:
401    /// ```
402    /// # use sqlparser::{parser::{Parser, ParserError}, dialect::GenericDialect};
403    /// # fn main() -> Result<(), ParserError> {
404    /// let dialect = GenericDialect{};
405    /// let statements = Parser::new(&dialect)
406    ///   .try_with_sql("SELECT * FROM foo")?
407    ///   .parse_statements()?;
408    /// # Ok(())
409    /// # }
410    /// ```
411    pub fn new(dialect: &'a dyn Dialect) -> Self {
412        Self {
413            tokens: vec![],
414            index: 0,
415            state: ParserState::Normal,
416            dialect,
417            recursion_counter: RecursionCounter::new(DEFAULT_REMAINING_DEPTH),
418            options: ParserOptions::new().with_trailing_commas(dialect.supports_trailing_commas()),
419            failed_prefix_positions: BTreeMap::new(),
420            failed_reserved_word_prefix_positions: BTreeMap::new(),
421            failed_derived_table_factor_positions: BTreeSet::new(),
422        }
423    }
424
425    /// Specify the maximum recursion limit while parsing.
426    ///
427    /// [`Parser`] prevents stack overflows by returning
428    /// [`ParserError::RecursionLimitExceeded`] if the parser exceeds
429    /// this depth while processing the query.
430    ///
431    /// Example:
432    /// ```
433    /// # use sqlparser::{parser::{Parser, ParserError}, dialect::GenericDialect};
434    /// # fn main() -> Result<(), ParserError> {
435    /// let dialect = GenericDialect{};
436    /// let result = Parser::new(&dialect)
437    ///   .with_recursion_limit(1)
438    ///   .try_with_sql("SELECT * FROM foo WHERE (a OR (b OR (c OR d)))")?
439    ///   .parse_statements();
440    ///   assert_eq!(result, Err(ParserError::RecursionLimitExceeded));
441    /// # Ok(())
442    /// # }
443    /// ```
444    ///
445    /// Note: when "recursive-protection" feature is enabled, this crate uses additional stack overflow protection
446    //  for some of its recursive methods. See [`recursive::recursive`] for more information.
447    pub fn with_recursion_limit(mut self, recursion_limit: usize) -> Self {
448        self.recursion_counter = RecursionCounter::new(recursion_limit);
449        self
450    }
451
452    /// Specify additional parser options
453    ///
454    /// [`Parser`] supports additional options ([`ParserOptions`])
455    /// that allow you to mix & match behavior otherwise constrained
456    /// to certain dialects (e.g. trailing commas).
457    ///
458    /// Example:
459    /// ```
460    /// # use sqlparser::{parser::{Parser, ParserError, ParserOptions}, dialect::GenericDialect};
461    /// # fn main() -> Result<(), ParserError> {
462    /// let dialect = GenericDialect{};
463    /// let options = ParserOptions::new()
464    ///    .with_trailing_commas(true)
465    ///    .with_unescape(false);
466    /// let result = Parser::new(&dialect)
467    ///   .with_options(options)
468    ///   .try_with_sql("SELECT a, b, COUNT(*), FROM foo GROUP BY a, b,")?
469    ///   .parse_statements();
470    ///   assert!(matches!(result, Ok(_)));
471    /// # Ok(())
472    /// # }
473    /// ```
474    pub fn with_options(mut self, options: ParserOptions) -> Self {
475        self.options = options;
476        self
477    }
478
479    /// Reset this parser to parse the specified token stream
480    pub fn with_tokens_with_locations(mut self, tokens: Vec<TokenWithSpan>) -> Self {
481        self.tokens = tokens;
482        self.index = 0;
483        self.failed_prefix_positions.clear();
484        self.failed_reserved_word_prefix_positions.clear();
485        self.failed_derived_table_factor_positions.clear();
486        self
487    }
488
489    /// Reset this parser state to parse the specified tokens
490    pub fn with_tokens(self, tokens: Vec<Token>) -> Self {
491        // Put in dummy locations
492        let tokens_with_locations: Vec<TokenWithSpan> = tokens
493            .into_iter()
494            .map(|token| TokenWithSpan {
495                token,
496                span: Span::empty(),
497            })
498            .collect();
499        self.with_tokens_with_locations(tokens_with_locations)
500    }
501
502    /// Tokenize the sql string and sets this [`Parser`]'s state to
503    /// parse the resulting tokens
504    ///
505    /// Returns an error if there was an error tokenizing the SQL string.
506    ///
507    /// See example on [`Parser::new()`] for an example
508    pub fn try_with_sql(self, sql: &str) -> Result<Self, ParserError> {
509        debug!("Parsing sql '{sql}'...");
510        let tokens = Tokenizer::new(self.dialect, sql)
511            .with_unescape(self.options.unescape)
512            .tokenize_with_location()?;
513        Ok(self.with_tokens_with_locations(tokens))
514    }
515
516    /// Parse potentially multiple statements
517    ///
518    /// Example
519    /// ```
520    /// # use sqlparser::{parser::{Parser, ParserError}, dialect::GenericDialect};
521    /// # fn main() -> Result<(), ParserError> {
522    /// let dialect = GenericDialect{};
523    /// let statements = Parser::new(&dialect)
524    ///   // Parse a SQL string with 2 separate statements
525    ///   .try_with_sql("SELECT * FROM foo; SELECT * FROM bar;")?
526    ///   .parse_statements()?;
527    /// assert_eq!(statements.len(), 2);
528    /// # Ok(())
529    /// # }
530    /// ```
531    pub fn parse_statements(&mut self) -> Result<Vec<Statement>, ParserError> {
532        let mut stmts = Vec::new();
533        let mut expecting_statement_delimiter = false;
534        loop {
535            // ignore empty statements (between successive statement delimiters)
536            while self.consume_token(&Token::SemiColon) {
537                expecting_statement_delimiter = false;
538            }
539
540            if !self.options.require_semicolon_stmt_delimiter {
541                expecting_statement_delimiter = false;
542            }
543
544            match &self.peek_token_ref().token {
545                Token::EOF => break,
546
547                // end of statement
548                Token::Word(word)
549                    if expecting_statement_delimiter && word.keyword == Keyword::END =>
550                {
551                    break;
552                }
553                _ => {}
554            }
555
556            if expecting_statement_delimiter {
557                return self.expected_ref("end of statement", self.peek_token_ref());
558            }
559
560            let statement = self.parse_statement()?;
561            stmts.push(statement);
562            expecting_statement_delimiter = true;
563        }
564        Ok(stmts)
565    }
566
567    /// Convenience method to parse a string with one or more SQL
568    /// statements into produce an Abstract Syntax Tree (AST).
569    ///
570    /// Example
571    /// ```
572    /// # use sqlparser::{parser::{Parser, ParserError}, dialect::GenericDialect};
573    /// # fn main() -> Result<(), ParserError> {
574    /// let dialect = GenericDialect{};
575    /// let statements = Parser::parse_sql(
576    ///   &dialect, "SELECT * FROM foo"
577    /// )?;
578    /// assert_eq!(statements.len(), 1);
579    /// # Ok(())
580    /// # }
581    /// ```
582    pub fn parse_sql(dialect: &dyn Dialect, sql: &str) -> Result<Vec<Statement>, ParserError> {
583        Parser::new(dialect).try_with_sql(sql)?.parse_statements()
584    }
585
586    /// Parses the given `sql` into an Abstract Syntax Tree (AST), returning
587    /// also encountered source code comments.
588    ///
589    /// See [Parser::parse_sql].
590    pub fn parse_sql_with_comments(
591        dialect: &'a dyn Dialect,
592        sql: &str,
593    ) -> Result<(Vec<Statement>, comments::Comments), ParserError> {
594        let mut p = Parser::new(dialect).try_with_sql(sql)?;
595        p.parse_statements().map(|stmts| (stmts, p.into_comments()))
596    }
597
598    /// Consumes this parser returning comments from the parsed token stream.
599    pub fn into_comments(self) -> comments::Comments {
600        let mut comments = comments::Comments::default();
601        for t in self.tokens.into_iter() {
602            match t.token {
603                Token::Whitespace(Whitespace::SingleLineComment { comment, prefix }) => {
604                    comments.offer(comments::CommentWithSpan {
605                        comment: comments::Comment::SingleLine {
606                            content: comment,
607                            prefix,
608                        },
609                        span: t.span,
610                    });
611                }
612                Token::Whitespace(Whitespace::MultiLineComment(comment)) => {
613                    comments.offer(comments::CommentWithSpan {
614                        comment: comments::Comment::MultiLine(comment),
615                        span: t.span,
616                    });
617                }
618                _ => {}
619            }
620        }
621        comments
622    }
623
624    /// Parse a single top-level statement (such as SELECT, INSERT, CREATE, etc.),
625    /// stopping before the statement separator, if any.
626    pub fn parse_statement(&mut self) -> Result<Statement, ParserError> {
627        let _guard = self.recursion_counter.try_decrease()?;
628
629        // allow the dialect to override statement parsing
630        if let Some(statement) = self.dialect.parse_statement(self) {
631            return statement;
632        }
633
634        let next_token = self.next_token();
635        match &next_token.token {
636            Token::Word(w) => match w.keyword {
637                Keyword::KILL => self.parse_kill(),
638                Keyword::FLUSH => self.parse_flush(),
639                Keyword::DESC => self.parse_explain(DescribeAlias::Desc),
640                Keyword::DESCRIBE => self.parse_explain(DescribeAlias::Describe),
641                Keyword::EXPLAIN => self.parse_explain(DescribeAlias::Explain),
642                Keyword::ANALYZE => self.parse_analyze().map(Into::into),
643                Keyword::CASE => {
644                    self.prev_token();
645                    self.parse_case_stmt().map(Into::into)
646                }
647                Keyword::IF => {
648                    self.prev_token();
649                    self.parse_if_stmt().map(Into::into)
650                }
651                Keyword::WHILE => {
652                    self.prev_token();
653                    self.parse_while().map(Into::into)
654                }
655                Keyword::RAISE => {
656                    self.prev_token();
657                    self.parse_raise_stmt().map(Into::into)
658                }
659                Keyword::SELECT | Keyword::WITH | Keyword::VALUES | Keyword::FROM => {
660                    self.prev_token();
661                    self.parse_query().map(Into::into)
662                }
663                Keyword::TRUNCATE => self.parse_truncate().map(Into::into),
664                Keyword::ATTACH => {
665                    if dialect_of!(self is DuckDbDialect) {
666                        self.parse_attach_duckdb_database()
667                    } else {
668                        self.parse_attach_database()
669                    }
670                }
671                Keyword::DETACH if self.dialect.supports_detach() => {
672                    self.parse_detach_duckdb_database()
673                }
674                Keyword::MSCK => self.parse_msck().map(Into::into),
675                Keyword::CREATE => self.parse_create(),
676                Keyword::CACHE => self.parse_cache_table(),
677                Keyword::DROP => self.parse_drop(),
678                Keyword::DISCARD => self.parse_discard(),
679                Keyword::DECLARE => self.parse_declare(),
680                Keyword::FETCH => self.parse_fetch_statement(),
681                Keyword::DELETE => self.parse_delete(next_token),
682                Keyword::INSERT => self.parse_insert(next_token),
683                Keyword::REPLACE => self.parse_replace(next_token),
684                Keyword::UNCACHE => self.parse_uncache_table(),
685                Keyword::UPDATE => self.parse_update(next_token),
686                Keyword::ALTER => self.parse_alter(),
687                Keyword::CALL => self.parse_call(),
688                Keyword::COPY => self.parse_copy(),
689                Keyword::OPEN => {
690                    self.prev_token();
691                    self.parse_open()
692                }
693                Keyword::CLOSE => self.parse_close(),
694                Keyword::SET => self.parse_set(),
695                Keyword::SHOW => self.parse_show(),
696                Keyword::USE => self.parse_use(),
697                Keyword::GRANT => self.parse_grant().map(Into::into),
698                Keyword::DENY => {
699                    self.prev_token();
700                    self.parse_deny()
701                }
702                Keyword::REVOKE => self.parse_revoke().map(Into::into),
703                Keyword::START => self.parse_start_transaction(),
704                Keyword::BEGIN => self.parse_begin(),
705                Keyword::END => self.parse_end(),
706                Keyword::SAVEPOINT => self.parse_savepoint(),
707                Keyword::RELEASE => self.parse_release(),
708                Keyword::COMMIT => self.parse_commit(),
709                Keyword::RAISERROR => Ok(self.parse_raiserror()?),
710                Keyword::THROW => {
711                    self.prev_token();
712                    self.parse_throw().map(Into::into)
713                }
714                Keyword::ROLLBACK => self.parse_rollback(),
715                Keyword::ABORT => self.parse_abort(),
716                Keyword::ASSERT => self.parse_assert(),
717                // `PREPARE`, `EXECUTE` and `DEALLOCATE` are Postgres-specific
718                // syntaxes. They are used for Postgres prepared statement.
719                Keyword::DEALLOCATE => self.parse_deallocate(),
720                Keyword::EXECUTE | Keyword::EXEC => self.parse_execute(),
721                Keyword::PREPARE => self.parse_prepare(),
722                Keyword::MERGE => self.parse_merge(next_token).map(Into::into),
723                // `LISTEN`, `UNLISTEN` and `NOTIFY` are Postgres-specific
724                // syntaxes. They are used for Postgres statement.
725                Keyword::LISTEN if self.dialect.supports_listen_notify() => self.parse_listen(),
726                Keyword::UNLISTEN if self.dialect.supports_listen_notify() => self.parse_unlisten(),
727                Keyword::NOTIFY if self.dialect.supports_listen_notify() => self.parse_notify(),
728                // `PRAGMA` is sqlite specific https://www.sqlite.org/pragma.html
729                Keyword::PRAGMA => self.parse_pragma(),
730                Keyword::UNLOAD => {
731                    self.prev_token();
732                    self.parse_unload()
733                }
734                Keyword::RENAME => self.parse_rename(),
735                // `INSTALL` is duckdb specific https://duckdb.org/docs/extensions/overview
736                Keyword::INSTALL if self.dialect.supports_install() => self.parse_install(),
737                Keyword::LOAD => self.parse_load(),
738                Keyword::LOCK => {
739                    self.prev_token();
740                    self.parse_lock_statement().map(Into::into)
741                }
742                Keyword::OPTIMIZE if self.dialect.supports_optimize_table() => {
743                    self.parse_optimize_table()
744                }
745                // `COMMENT` is snowflake specific https://docs.snowflake.com/en/sql-reference/sql/comment
746                Keyword::COMMENT if self.dialect.supports_comment_on() => self.parse_comment(),
747                Keyword::PRINT => self.parse_print(),
748                // `WAITFOR` is MSSQL specific https://learn.microsoft.com/en-us/sql/t-sql/language-elements/waitfor-transact-sql
749                Keyword::WAITFOR => self.parse_waitfor(),
750                Keyword::RETURN => self.parse_return(),
751                Keyword::EXPORT => {
752                    self.prev_token();
753                    self.parse_export_data()
754                }
755                Keyword::VACUUM => {
756                    self.prev_token();
757                    self.parse_vacuum()
758                }
759                Keyword::RESET => self.parse_reset().map(Into::into),
760                _ => self.expected("an SQL statement", next_token),
761            },
762            Token::LParen => {
763                self.prev_token();
764                self.parse_query().map(Into::into)
765            }
766            _ => self.expected("an SQL statement", next_token),
767        }
768    }
769
770    /// Parse a `CASE` statement.
771    ///
772    /// See [Statement::Case]
773    pub fn parse_case_stmt(&mut self) -> Result<CaseStatement, ParserError> {
774        let case_token = self.expect_keyword(Keyword::CASE)?;
775
776        let match_expr = if self.peek_keyword(Keyword::WHEN) {
777            None
778        } else {
779            Some(self.parse_expr()?)
780        };
781
782        self.expect_keyword_is(Keyword::WHEN)?;
783        let when_blocks = self.parse_keyword_separated(Keyword::WHEN, |parser| {
784            parser.parse_conditional_statement_block(&[Keyword::WHEN, Keyword::ELSE, Keyword::END])
785        })?;
786
787        let else_block = if self.parse_keyword(Keyword::ELSE) {
788            Some(self.parse_conditional_statement_block(&[Keyword::END])?)
789        } else {
790            None
791        };
792
793        let mut end_case_token = self.expect_keyword(Keyword::END)?;
794        if self.peek_keyword(Keyword::CASE) {
795            end_case_token = self.expect_keyword(Keyword::CASE)?;
796        }
797
798        Ok(CaseStatement {
799            case_token: AttachedToken(case_token),
800            match_expr,
801            when_blocks,
802            else_block,
803            end_case_token: AttachedToken(end_case_token),
804        })
805    }
806
807    /// Parse an `IF` statement.
808    ///
809    /// See [Statement::If]
810    pub fn parse_if_stmt(&mut self) -> Result<IfStatement, ParserError> {
811        self.expect_keyword_is(Keyword::IF)?;
812        let if_block = self.parse_conditional_statement_block(&[
813            Keyword::ELSE,
814            Keyword::ELSEIF,
815            Keyword::END,
816        ])?;
817
818        let elseif_blocks = if self.parse_keyword(Keyword::ELSEIF) {
819            self.parse_keyword_separated(Keyword::ELSEIF, |parser| {
820                parser.parse_conditional_statement_block(&[
821                    Keyword::ELSEIF,
822                    Keyword::ELSE,
823                    Keyword::END,
824                ])
825            })?
826        } else {
827            vec![]
828        };
829
830        let else_block = if self.parse_keyword(Keyword::ELSE) {
831            Some(self.parse_conditional_statement_block(&[Keyword::END])?)
832        } else {
833            None
834        };
835
836        self.expect_keyword_is(Keyword::END)?;
837        let end_token = self.expect_keyword(Keyword::IF)?;
838
839        Ok(IfStatement {
840            if_block,
841            elseif_blocks,
842            else_block,
843            end_token: Some(AttachedToken(end_token)),
844        })
845    }
846
847    /// Parse a `WHILE` statement.
848    ///
849    /// See [Statement::While]
850    fn parse_while(&mut self) -> Result<WhileStatement, ParserError> {
851        self.expect_keyword_is(Keyword::WHILE)?;
852        let while_block = self.parse_conditional_statement_block(&[Keyword::END])?;
853
854        Ok(WhileStatement { while_block })
855    }
856
857    /// Parses an expression and associated list of statements
858    /// belonging to a conditional statement like `IF` or `WHEN` or `WHILE`.
859    ///
860    /// Example:
861    /// ```sql
862    /// IF condition THEN statement1; statement2;
863    /// ```
864    fn parse_conditional_statement_block(
865        &mut self,
866        terminal_keywords: &[Keyword],
867    ) -> Result<ConditionalStatementBlock, ParserError> {
868        let start_token = self.get_current_token().clone(); // self.expect_keyword(keyword)?;
869        let mut then_token = None;
870
871        let condition = match &start_token.token {
872            Token::Word(w) if w.keyword == Keyword::ELSE => None,
873            Token::Word(w) if w.keyword == Keyword::WHILE => {
874                let expr = self.parse_expr()?;
875                Some(expr)
876            }
877            _ => {
878                let expr = self.parse_expr()?;
879                then_token = Some(AttachedToken(self.expect_keyword(Keyword::THEN)?));
880                Some(expr)
881            }
882        };
883
884        let conditional_statements = self.parse_conditional_statements(terminal_keywords)?;
885
886        Ok(ConditionalStatementBlock {
887            start_token: AttachedToken(start_token),
888            condition,
889            then_token,
890            conditional_statements,
891        })
892    }
893
894    /// Parse a BEGIN/END block or a sequence of statements
895    /// This could be inside of a conditional (IF, CASE, WHILE etc.) or an object body defined optionally BEGIN/END and one or more statements.
896    pub(crate) fn parse_conditional_statements(
897        &mut self,
898        terminal_keywords: &[Keyword],
899    ) -> Result<ConditionalStatements, ParserError> {
900        let conditional_statements = if self.peek_keyword(Keyword::BEGIN) {
901            let begin_token = self.expect_keyword(Keyword::BEGIN)?;
902            let statements = self.parse_statement_list(terminal_keywords)?;
903            let end_token = self.expect_keyword(Keyword::END)?;
904
905            ConditionalStatements::BeginEnd(BeginEndStatements {
906                begin_token: AttachedToken(begin_token),
907                statements,
908                end_token: AttachedToken(end_token),
909            })
910        } else {
911            ConditionalStatements::Sequence {
912                statements: self.parse_statement_list(terminal_keywords)?,
913            }
914        };
915        Ok(conditional_statements)
916    }
917
918    /// Parse a `RAISE` statement.
919    ///
920    /// See [Statement::Raise]
921    pub fn parse_raise_stmt(&mut self) -> Result<RaiseStatement, ParserError> {
922        self.expect_keyword_is(Keyword::RAISE)?;
923
924        let value = if self.parse_keywords(&[Keyword::USING, Keyword::MESSAGE]) {
925            self.expect_token(&Token::Eq)?;
926            Some(RaiseStatementValue::UsingMessage(self.parse_expr()?))
927        } else {
928            self.maybe_parse(|parser| parser.parse_expr().map(RaiseStatementValue::Expr))?
929        };
930
931        Ok(RaiseStatement { value })
932    }
933    /// Parse a COMMENT statement.
934    ///
935    /// See [Statement::Comment]
936    pub fn parse_comment(&mut self) -> Result<Statement, ParserError> {
937        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
938
939        self.expect_keyword_is(Keyword::ON)?;
940        let token = self.next_token();
941
942        let (object_type, object_name) = match token.token {
943            Token::Word(w) if w.keyword == Keyword::COLLATION => {
944                (CommentObject::Collation, self.parse_object_name(false)?)
945            }
946            Token::Word(w) if w.keyword == Keyword::COLUMN => {
947                (CommentObject::Column, self.parse_object_name(false)?)
948            }
949            Token::Word(w) if w.keyword == Keyword::DATABASE => {
950                (CommentObject::Database, self.parse_object_name(false)?)
951            }
952            Token::Word(w) if w.keyword == Keyword::DOMAIN => {
953                (CommentObject::Domain, self.parse_object_name(false)?)
954            }
955            Token::Word(w) if w.keyword == Keyword::EXTENSION => {
956                (CommentObject::Extension, self.parse_object_name(false)?)
957            }
958            Token::Word(w) if w.keyword == Keyword::FUNCTION => {
959                (CommentObject::Function, self.parse_object_name(false)?)
960            }
961            Token::Word(w) if w.keyword == Keyword::INDEX => {
962                (CommentObject::Index, self.parse_object_name(false)?)
963            }
964            Token::Word(w) if w.keyword == Keyword::MATERIALIZED => {
965                self.expect_keyword_is(Keyword::VIEW)?;
966                (
967                    CommentObject::MaterializedView,
968                    self.parse_object_name(false)?,
969                )
970            }
971            Token::Word(w) if w.keyword == Keyword::PROCEDURE => {
972                (CommentObject::Procedure, self.parse_object_name(false)?)
973            }
974            Token::Word(w) if w.keyword == Keyword::ROLE => {
975                (CommentObject::Role, self.parse_object_name(false)?)
976            }
977            Token::Word(w) if w.keyword == Keyword::SCHEMA => {
978                (CommentObject::Schema, self.parse_object_name(false)?)
979            }
980            Token::Word(w) if w.keyword == Keyword::SEQUENCE => {
981                (CommentObject::Sequence, self.parse_object_name(false)?)
982            }
983            Token::Word(w) if w.keyword == Keyword::TABLE => {
984                (CommentObject::Table, self.parse_object_name(false)?)
985            }
986            Token::Word(w) if w.keyword == Keyword::TYPE => {
987                (CommentObject::Type, self.parse_object_name(false)?)
988            }
989            Token::Word(w) if w.keyword == Keyword::USER => {
990                (CommentObject::User, self.parse_object_name(false)?)
991            }
992            Token::Word(w) if w.keyword == Keyword::VIEW => {
993                (CommentObject::View, self.parse_object_name(false)?)
994            }
995            _ => self.expected("comment object_type", token)?,
996        };
997
998        self.expect_keyword_is(Keyword::IS)?;
999        let comment = if self.parse_keyword(Keyword::NULL) {
1000            None
1001        } else {
1002            Some(self.parse_literal_string()?)
1003        };
1004        Ok(Statement::Comment {
1005            object_type,
1006            object_name,
1007            comment,
1008            if_exists,
1009        })
1010    }
1011
1012    /// Parse `FLUSH` statement.
1013    pub fn parse_flush(&mut self) -> Result<Statement, ParserError> {
1014        let mut channel = None;
1015        let mut tables: Vec<ObjectName> = vec![];
1016        let mut read_lock = false;
1017        let mut export = false;
1018
1019        if !dialect_of!(self is MySqlDialect | GenericDialect) {
1020            return parser_err!(
1021                "Unsupported statement FLUSH",
1022                self.peek_token_ref().span.start
1023            );
1024        }
1025
1026        let location = if self.parse_keyword(Keyword::NO_WRITE_TO_BINLOG) {
1027            Some(FlushLocation::NoWriteToBinlog)
1028        } else if self.parse_keyword(Keyword::LOCAL) {
1029            Some(FlushLocation::Local)
1030        } else {
1031            None
1032        };
1033
1034        let object_type = if self.parse_keywords(&[Keyword::BINARY, Keyword::LOGS]) {
1035            FlushType::BinaryLogs
1036        } else if self.parse_keywords(&[Keyword::ENGINE, Keyword::LOGS]) {
1037            FlushType::EngineLogs
1038        } else if self.parse_keywords(&[Keyword::ERROR, Keyword::LOGS]) {
1039            FlushType::ErrorLogs
1040        } else if self.parse_keywords(&[Keyword::GENERAL, Keyword::LOGS]) {
1041            FlushType::GeneralLogs
1042        } else if self.parse_keywords(&[Keyword::HOSTS]) {
1043            FlushType::Hosts
1044        } else if self.parse_keyword(Keyword::PRIVILEGES) {
1045            FlushType::Privileges
1046        } else if self.parse_keyword(Keyword::OPTIMIZER_COSTS) {
1047            FlushType::OptimizerCosts
1048        } else if self.parse_keywords(&[Keyword::RELAY, Keyword::LOGS]) {
1049            if self.parse_keywords(&[Keyword::FOR, Keyword::CHANNEL]) {
1050                channel = Some(self.parse_object_name(false)?.to_string());
1051            }
1052            FlushType::RelayLogs
1053        } else if self.parse_keywords(&[Keyword::SLOW, Keyword::LOGS]) {
1054            FlushType::SlowLogs
1055        } else if self.parse_keyword(Keyword::STATUS) {
1056            FlushType::Status
1057        } else if self.parse_keyword(Keyword::USER_RESOURCES) {
1058            FlushType::UserResources
1059        } else if self.parse_keywords(&[Keyword::LOGS]) {
1060            FlushType::Logs
1061        } else if self.parse_keywords(&[Keyword::TABLES]) {
1062            loop {
1063                let next_token = self.next_token();
1064                match &next_token.token {
1065                    Token::Word(w) => match w.keyword {
1066                        Keyword::WITH => {
1067                            read_lock = self.parse_keywords(&[Keyword::READ, Keyword::LOCK]);
1068                        }
1069                        Keyword::FOR => {
1070                            export = self.parse_keyword(Keyword::EXPORT);
1071                        }
1072                        Keyword::NoKeyword => {
1073                            self.prev_token();
1074                            tables = self.parse_comma_separated(|p| p.parse_object_name(false))?;
1075                        }
1076                        _ => {}
1077                    },
1078                    _ => {
1079                        break;
1080                    }
1081                }
1082            }
1083
1084            FlushType::Tables
1085        } else {
1086            return self.expected_ref(
1087                "BINARY LOGS, ENGINE LOGS, ERROR LOGS, GENERAL LOGS, HOSTS, LOGS, PRIVILEGES, OPTIMIZER_COSTS,\
1088                 RELAY LOGS [FOR CHANNEL channel], SLOW LOGS, STATUS, USER_RESOURCES",
1089                self.peek_token_ref(),
1090            );
1091        };
1092
1093        Ok(Statement::Flush {
1094            object_type,
1095            location,
1096            channel,
1097            read_lock,
1098            export,
1099            tables,
1100        })
1101    }
1102
1103    /// Parse `MSCK` statement.
1104    pub fn parse_msck(&mut self) -> Result<Msck, ParserError> {
1105        let repair = self.parse_keyword(Keyword::REPAIR);
1106        self.expect_keyword_is(Keyword::TABLE)?;
1107        let table_name = self.parse_object_name(false)?;
1108        let partition_action = self
1109            .maybe_parse(|parser| {
1110                let pa = match parser.parse_one_of_keywords(&[
1111                    Keyword::ADD,
1112                    Keyword::DROP,
1113                    Keyword::SYNC,
1114                ]) {
1115                    Some(Keyword::ADD) => Some(AddDropSync::ADD),
1116                    Some(Keyword::DROP) => Some(AddDropSync::DROP),
1117                    Some(Keyword::SYNC) => Some(AddDropSync::SYNC),
1118                    _ => None,
1119                };
1120                parser.expect_keyword_is(Keyword::PARTITIONS)?;
1121                Ok(pa)
1122            })?
1123            .unwrap_or_default();
1124        Ok(Msck {
1125            repair,
1126            table_name,
1127            partition_action,
1128        })
1129    }
1130
1131    /// Parse `TRUNCATE` statement.
1132    pub fn parse_truncate(&mut self) -> Result<Truncate, ParserError> {
1133        let table = self.parse_keyword(Keyword::TABLE);
1134        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
1135
1136        let table_names = self.parse_comma_separated(|p| {
1137            let only = p.parse_keyword(Keyword::ONLY);
1138            let name = p.parse_object_name(false)?;
1139            let has_asterisk = p.consume_token(&Token::Mul);
1140            Ok(TruncateTableTarget {
1141                name,
1142                only,
1143                has_asterisk,
1144            })
1145        })?;
1146
1147        let mut partitions = None;
1148        if self.parse_keyword(Keyword::PARTITION) {
1149            self.expect_token(&Token::LParen)?;
1150            partitions = Some(self.parse_comma_separated(Parser::parse_expr)?);
1151            self.expect_token(&Token::RParen)?;
1152        }
1153
1154        let mut identity = None;
1155        let mut cascade = None;
1156
1157        if dialect_of!(self is PostgreSqlDialect | GenericDialect) {
1158            identity = if self.parse_keywords(&[Keyword::RESTART, Keyword::IDENTITY]) {
1159                Some(TruncateIdentityOption::Restart)
1160            } else if self.parse_keywords(&[Keyword::CONTINUE, Keyword::IDENTITY]) {
1161                Some(TruncateIdentityOption::Continue)
1162            } else {
1163                None
1164            };
1165
1166            cascade = self.parse_cascade_option();
1167        };
1168
1169        let on_cluster = self.parse_optional_on_cluster()?;
1170
1171        Ok(Truncate {
1172            table_names,
1173            partitions,
1174            table,
1175            if_exists,
1176            identity,
1177            cascade,
1178            on_cluster,
1179        })
1180    }
1181
1182    fn parse_cascade_option(&mut self) -> Option<CascadeOption> {
1183        if self.parse_keyword(Keyword::CASCADE) {
1184            Some(CascadeOption::Cascade)
1185        } else if self.parse_keyword(Keyword::RESTRICT) {
1186            Some(CascadeOption::Restrict)
1187        } else {
1188            None
1189        }
1190    }
1191
1192    /// Parse options for `ATTACH DUCKDB DATABASE` statement.
1193    pub fn parse_attach_duckdb_database_options(
1194        &mut self,
1195    ) -> Result<Vec<AttachDuckDBDatabaseOption>, ParserError> {
1196        if !self.consume_token(&Token::LParen) {
1197            return Ok(vec![]);
1198        }
1199
1200        let mut options = vec![];
1201        loop {
1202            if self.parse_keyword(Keyword::READ_ONLY) {
1203                let boolean = if self.parse_keyword(Keyword::TRUE) {
1204                    Some(true)
1205                } else if self.parse_keyword(Keyword::FALSE) {
1206                    Some(false)
1207                } else {
1208                    None
1209                };
1210                options.push(AttachDuckDBDatabaseOption::ReadOnly(boolean));
1211            } else if self.parse_keyword(Keyword::TYPE) {
1212                let ident = self.parse_identifier()?;
1213                options.push(AttachDuckDBDatabaseOption::Type(ident));
1214            } else {
1215                return self
1216                    .expected_ref("expected one of: ), READ_ONLY, TYPE", self.peek_token_ref());
1217            };
1218
1219            if self.consume_token(&Token::RParen) {
1220                return Ok(options);
1221            } else if self.consume_token(&Token::Comma) {
1222                continue;
1223            } else {
1224                return self.expected_ref("expected one of: ')', ','", self.peek_token_ref());
1225            }
1226        }
1227    }
1228
1229    /// Parse `ATTACH DUCKDB DATABASE` statement.
1230    pub fn parse_attach_duckdb_database(&mut self) -> Result<Statement, ParserError> {
1231        let database = self.parse_keyword(Keyword::DATABASE);
1232        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
1233        let database_path = self.parse_identifier()?;
1234        let database_alias = if self.parse_keyword(Keyword::AS) {
1235            Some(self.parse_identifier()?)
1236        } else {
1237            None
1238        };
1239
1240        let attach_options = self.parse_attach_duckdb_database_options()?;
1241        Ok(Statement::AttachDuckDBDatabase {
1242            if_not_exists,
1243            database,
1244            database_path,
1245            database_alias,
1246            attach_options,
1247        })
1248    }
1249
1250    /// Parse `DETACH DUCKDB DATABASE` statement.
1251    pub fn parse_detach_duckdb_database(&mut self) -> Result<Statement, ParserError> {
1252        let database = self.parse_keyword(Keyword::DATABASE);
1253        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
1254        let database_alias = self.parse_identifier()?;
1255        Ok(Statement::DetachDuckDBDatabase {
1256            if_exists,
1257            database,
1258            database_alias,
1259        })
1260    }
1261
1262    /// Parse `ATTACH DATABASE` statement.
1263    pub fn parse_attach_database(&mut self) -> Result<Statement, ParserError> {
1264        let database = self.parse_keyword(Keyword::DATABASE);
1265        let database_file_name = self.parse_expr()?;
1266        self.expect_keyword_is(Keyword::AS)?;
1267        let schema_name = self.parse_identifier()?;
1268        Ok(Statement::AttachDatabase {
1269            database,
1270            schema_name,
1271            database_file_name,
1272        })
1273    }
1274
1275    /// Parse `ANALYZE` statement.
1276    pub fn parse_analyze(&mut self) -> Result<Analyze, ParserError> {
1277        let has_table_keyword = self.parse_keyword(Keyword::TABLE);
1278        let table_name = self.maybe_parse(|parser| parser.parse_object_name(false))?;
1279        let mut for_columns = false;
1280        let mut cache_metadata = false;
1281        let mut noscan = false;
1282        let mut partitions = None;
1283        let mut compute_statistics = false;
1284        let mut columns = vec![];
1285
1286        // PostgreSQL syntax: ANALYZE t (col1, col2)
1287        if table_name.is_some() && self.consume_token(&Token::LParen) {
1288            columns = self.parse_comma_separated(|p| p.parse_identifier())?;
1289            self.expect_token(&Token::RParen)?;
1290        }
1291
1292        loop {
1293            match self.parse_one_of_keywords(&[
1294                Keyword::PARTITION,
1295                Keyword::FOR,
1296                Keyword::CACHE,
1297                Keyword::NOSCAN,
1298                Keyword::COMPUTE,
1299            ]) {
1300                Some(Keyword::PARTITION) => {
1301                    self.expect_token(&Token::LParen)?;
1302                    partitions = Some(self.parse_comma_separated(Parser::parse_expr)?);
1303                    self.expect_token(&Token::RParen)?;
1304                }
1305                Some(Keyword::NOSCAN) => noscan = true,
1306                Some(Keyword::FOR) => {
1307                    self.expect_keyword_is(Keyword::COLUMNS)?;
1308
1309                    columns = self
1310                        .maybe_parse(|parser| {
1311                            parser.parse_comma_separated(|p| p.parse_identifier())
1312                        })?
1313                        .unwrap_or_default();
1314                    for_columns = true
1315                }
1316                Some(Keyword::CACHE) => {
1317                    self.expect_keyword_is(Keyword::METADATA)?;
1318                    cache_metadata = true
1319                }
1320                Some(Keyword::COMPUTE) => {
1321                    self.expect_keyword_is(Keyword::STATISTICS)?;
1322                    compute_statistics = true
1323                }
1324                _ => break,
1325            }
1326        }
1327
1328        Ok(Analyze {
1329            has_table_keyword,
1330            table_name,
1331            for_columns,
1332            columns,
1333            partitions,
1334            cache_metadata,
1335            noscan,
1336            compute_statistics,
1337        })
1338    }
1339
1340    /// Parse a new expression including wildcard & qualified wildcard.
1341    pub fn parse_wildcard_expr(&mut self) -> Result<Expr, ParserError> {
1342        let index = self.index;
1343
1344        let next_token = self.next_token();
1345        match next_token.token {
1346            t @ (Token::Word(_) | Token::SingleQuotedString(_))
1347                if self.peek_token_ref().token == Token::Period =>
1348            {
1349                let mut id_parts: Vec<Ident> = vec![match t {
1350                    Token::Word(w) => w.into_ident(next_token.span),
1351                    Token::SingleQuotedString(s) => Ident::with_quote('\'', s),
1352                    _ => {
1353                        return Err(ParserError::ParserError(
1354                            "Internal parser error: unexpected token type".to_string(),
1355                        ))
1356                    }
1357                }];
1358
1359                while self.consume_token(&Token::Period) {
1360                    let next_token = self.next_token();
1361                    match next_token.token {
1362                        Token::Word(w) => id_parts.push(w.into_ident(next_token.span)),
1363                        Token::SingleQuotedString(s) => {
1364                            // SQLite has single-quoted identifiers
1365                            id_parts.push(Ident::with_quote('\'', s))
1366                        }
1367                        Token::Placeholder(s) => {
1368                            // Snowflake uses $1, $2, etc. for positional column references
1369                            // in staged data queries like: SELECT t.$1 FROM @stage t
1370                            id_parts.push(Ident::new(s))
1371                        }
1372                        Token::Mul => {
1373                            return Ok(Expr::QualifiedWildcard(
1374                                ObjectName::from(id_parts),
1375                                AttachedToken(next_token),
1376                            ));
1377                        }
1378                        _ => {
1379                            return self.expected("an identifier or a '*' after '.'", next_token);
1380                        }
1381                    }
1382                }
1383            }
1384            Token::Mul => {
1385                return Ok(Expr::Wildcard(AttachedToken(next_token)));
1386            }
1387            // Handle parenthesized wildcard: (*)
1388            Token::LParen => {
1389                let [maybe_mul, maybe_rparen] = self.peek_tokens_ref();
1390                if maybe_mul.token == Token::Mul && maybe_rparen.token == Token::RParen {
1391                    let mul_token = self.next_token(); // consume Mul
1392                    self.next_token(); // consume RParen
1393                    return Ok(Expr::Wildcard(AttachedToken(mul_token)));
1394                }
1395            }
1396            _ => (),
1397        };
1398
1399        self.index = index;
1400        self.parse_expr()
1401    }
1402
1403    /// Parse a new expression.
1404    pub fn parse_expr(&mut self) -> Result<Expr, ParserError> {
1405        self.parse_subexpr(self.dialect.prec_unknown())
1406    }
1407
1408    /// Parse expression with optional alias and order by.
1409    pub fn parse_expr_with_alias_and_order_by(
1410        &mut self,
1411    ) -> Result<ExprWithAliasAndOrderBy, ParserError> {
1412        let expr = self.parse_expr()?;
1413
1414        fn validator(explicit: bool, kw: &Keyword, _parser: &mut Parser) -> bool {
1415            explicit || !&[Keyword::ASC, Keyword::DESC, Keyword::GROUP].contains(kw)
1416        }
1417        let alias = self.parse_optional_alias_inner(None, validator)?;
1418        let order_by = OrderByOptions {
1419            sort: self.parse_optional_order_by_sort(),
1420            nulls_first: None,
1421        };
1422        Ok(ExprWithAliasAndOrderBy {
1423            expr: ExprWithAlias { expr, alias },
1424            order_by,
1425        })
1426    }
1427
1428    /// Parse tokens until the precedence changes.
1429    #[cfg_attr(feature = "recursive-protection", recursive::recursive)]
1430    pub fn parse_subexpr(&mut self, precedence: u8) -> Result<Expr, ParserError> {
1431        let _guard = self.recursion_counter.try_decrease()?;
1432        debug!("parsing expr");
1433        let mut expr = self.parse_prefix()?;
1434
1435        expr = self.parse_compound_expr(expr, vec![])?;
1436
1437        // Parse an optional collation cast operator following `expr`.
1438        //
1439        // For example (MSSQL): t1.a COLLATE Latin1_General_CI_AS
1440        if !self.in_column_definition_state() && self.parse_keyword(Keyword::COLLATE) {
1441            expr = Expr::Collate {
1442                expr: Box::new(expr),
1443                collation: self.parse_object_name(false)?,
1444            };
1445        }
1446
1447        debug!("prefix: {expr:?}");
1448        loop {
1449            let next_precedence = self.get_next_precedence()?;
1450            debug!("next precedence: {next_precedence:?}");
1451
1452            if precedence >= next_precedence {
1453                break;
1454            }
1455
1456            // The period operator is handled exclusively by the
1457            // compound field access parsing.
1458            if Token::Period == self.peek_token_ref().token {
1459                break;
1460            }
1461
1462            expr = self.parse_infix(expr, next_precedence)?;
1463        }
1464        Ok(expr)
1465    }
1466
1467    /// Parse `ASSERT` statement.
1468    pub fn parse_assert(&mut self) -> Result<Statement, ParserError> {
1469        let condition = self.parse_expr()?;
1470        let message = if self.parse_keyword(Keyword::AS) {
1471            Some(self.parse_expr()?)
1472        } else {
1473            None
1474        };
1475
1476        Ok(Statement::Assert { condition, message })
1477    }
1478
1479    /// Parse `SAVEPOINT` statement.
1480    pub fn parse_savepoint(&mut self) -> Result<Statement, ParserError> {
1481        let name = self.parse_identifier()?;
1482        Ok(Statement::Savepoint { name })
1483    }
1484
1485    /// Parse `RELEASE` statement.
1486    pub fn parse_release(&mut self) -> Result<Statement, ParserError> {
1487        let _ = self.parse_keyword(Keyword::SAVEPOINT);
1488        let name = self.parse_identifier()?;
1489
1490        Ok(Statement::ReleaseSavepoint { name })
1491    }
1492
1493    /// Parse `LISTEN` statement.
1494    pub fn parse_listen(&mut self) -> Result<Statement, ParserError> {
1495        let channel = self.parse_identifier()?;
1496        Ok(Statement::LISTEN { channel })
1497    }
1498
1499    /// Parse `UNLISTEN` statement.
1500    pub fn parse_unlisten(&mut self) -> Result<Statement, ParserError> {
1501        let channel = if self.consume_token(&Token::Mul) {
1502            Ident::new(Expr::Wildcard(AttachedToken::empty()).to_string())
1503        } else {
1504            match self.parse_identifier() {
1505                Ok(expr) => expr,
1506                _ => {
1507                    self.prev_token();
1508                    return self.expected_ref("wildcard or identifier", self.peek_token_ref());
1509                }
1510            }
1511        };
1512        Ok(Statement::UNLISTEN { channel })
1513    }
1514
1515    /// Parse `NOTIFY` statement.
1516    pub fn parse_notify(&mut self) -> Result<Statement, ParserError> {
1517        let channel = self.parse_identifier()?;
1518        let payload = if self.consume_token(&Token::Comma) {
1519            Some(self.parse_literal_string()?)
1520        } else {
1521            None
1522        };
1523        Ok(Statement::NOTIFY { channel, payload })
1524    }
1525
1526    /// Parses a `RENAME TABLE` statement. See [Statement::RenameTable]
1527    pub fn parse_rename(&mut self) -> Result<Statement, ParserError> {
1528        if self.peek_keyword(Keyword::TABLE) {
1529            self.expect_keyword(Keyword::TABLE)?;
1530            let rename_tables = self.parse_comma_separated(|parser| {
1531                let old_name = parser.parse_object_name(false)?;
1532                parser.expect_keyword(Keyword::TO)?;
1533                let new_name = parser.parse_object_name(false)?;
1534
1535                Ok(RenameTable { old_name, new_name })
1536            })?;
1537            Ok(rename_tables.into())
1538        } else {
1539            self.expected_ref("KEYWORD `TABLE` after RENAME", self.peek_token_ref())
1540        }
1541    }
1542
1543    /// Tries to parse an expression by matching the specified word to known keywords that have a special meaning in the dialect.
1544    /// Returns `None if no match is found.
1545    fn parse_expr_prefix_by_reserved_word(
1546        &mut self,
1547        w: &Word,
1548        w_span: Span,
1549    ) -> Result<Option<Expr>, ParserError> {
1550        match w.keyword {
1551            Keyword::TRUE | Keyword::FALSE if self.dialect.supports_boolean_literals() => {
1552                self.prev_token();
1553                Ok(Some(Expr::Value(self.parse_value()?)))
1554            }
1555            Keyword::NULL => {
1556                self.prev_token();
1557                Ok(Some(Expr::Value(self.parse_value()?)))
1558            }
1559            Keyword::CURRENT_CATALOG
1560            | Keyword::CURRENT_USER
1561            | Keyword::SESSION_USER
1562            | Keyword::USER
1563            if dialect_of!(self is PostgreSqlDialect | GenericDialect) =>
1564                {
1565                    Ok(Some(Expr::Function(Function {
1566                        name: ObjectName::from(vec![w.to_ident(w_span)]),
1567                        uses_odbc_syntax: false,
1568                        parameters: FunctionArguments::None,
1569                        args: FunctionArguments::None,
1570                        null_treatment: None,
1571                        filter: None,
1572                        over: None,
1573                        within_group: vec![],
1574                    })))
1575                }
1576            Keyword::CURRENT_TIMESTAMP
1577            | Keyword::CURRENT_TIME
1578            | Keyword::CURRENT_DATE
1579            | Keyword::LOCALTIME
1580            | Keyword::LOCALTIMESTAMP => {
1581                Ok(Some(self.parse_time_functions(ObjectName::from(vec![w.to_ident(w_span)]))?))
1582            }
1583            Keyword::CASE => Ok(Some(self.parse_case_expr()?)),
1584            Keyword::CONVERT => Ok(Some(self.parse_convert_expr(false)?)),
1585            Keyword::TRY_CONVERT if self.dialect.supports_try_convert() => Ok(Some(self.parse_convert_expr(true)?)),
1586            Keyword::CAST => Ok(Some(self.parse_cast_expr(CastKind::Cast)?)),
1587            Keyword::TRY_CAST => Ok(Some(self.parse_cast_expr(CastKind::TryCast)?)),
1588            Keyword::SAFE_CAST => Ok(Some(self.parse_cast_expr(CastKind::SafeCast)?)),
1589            Keyword::EXISTS
1590            // Support parsing Databricks has a function named `exists`.
1591            if !dialect_of!(self is DatabricksDialect)
1592                || matches!(
1593                        self.peek_nth_token_ref(1).token,
1594                        Token::Word(Word {
1595                            keyword: Keyword::SELECT | Keyword::WITH,
1596                            ..
1597                        })
1598                    ) =>
1599                {
1600                    Ok(Some(self.parse_exists_expr(false)?))
1601                }
1602            Keyword::EXTRACT => Ok(Some(self.parse_extract_expr()?)),
1603            Keyword::CEIL => Ok(Some(self.parse_ceil_floor_expr(true)?)),
1604            Keyword::FLOOR => Ok(Some(self.parse_ceil_floor_expr(false)?)),
1605            Keyword::POSITION if self.peek_token_ref().token == Token::LParen => {
1606                Ok(Some(self.parse_position_expr(w.to_ident(w_span))?))
1607            }
1608            Keyword::SUBSTR | Keyword::SUBSTRING => {
1609                self.prev_token();
1610                Ok(Some(self.parse_substring()?))
1611            }
1612            Keyword::OVERLAY => Ok(Some(self.parse_overlay_expr()?)),
1613            Keyword::TRIM => Ok(Some(self.parse_trim_expr()?)),
1614            Keyword::INTERVAL => Ok(Some(self.parse_interval()?)),
1615            // Treat ARRAY[1,2,3] as an array [1,2,3], otherwise try as subquery or a function call
1616            Keyword::ARRAY if *self.peek_token_ref() == Token::LBracket => {
1617                self.expect_token(&Token::LBracket)?;
1618                Ok(Some(self.parse_array_expr(true)?))
1619            }
1620            Keyword::ARRAY
1621            if self.peek_token_ref().token == Token::LParen
1622                && !dialect_of!(self is ClickHouseDialect | DatabricksDialect) =>
1623                {
1624                    self.expect_token(&Token::LParen)?;
1625                    let query = self.parse_query()?;
1626                    self.expect_token(&Token::RParen)?;
1627                    Ok(Some(Expr::Function(Function {
1628                        name: ObjectName::from(vec![w.to_ident(w_span)]),
1629                        uses_odbc_syntax: false,
1630                        parameters: FunctionArguments::None,
1631                        args: FunctionArguments::Subquery(query),
1632                        filter: None,
1633                        null_treatment: None,
1634                        over: None,
1635                        within_group: vec![],
1636                    })))
1637                }
1638            Keyword::NOT => Ok(Some(self.parse_not()?)),
1639            Keyword::MATCH if self.dialect.supports_match_against() => {
1640                Ok(Some(self.parse_match_against()?))
1641            }
1642            Keyword::STRUCT if self.dialect.supports_struct_literal() => {
1643                let struct_expr = self.parse_struct_literal()?;
1644                Ok(Some(struct_expr))
1645            }
1646            Keyword::PRIOR if matches!(self.state, ParserState::ConnectBy) => {
1647                let expr = self.parse_subexpr(self.dialect.prec_value(Precedence::PlusMinus))?;
1648                Ok(Some(Expr::Prior(Box::new(expr))))
1649            }
1650            Keyword::MAP if *self.peek_token_ref() == Token::LBrace && self.dialect.support_map_literal_syntax() => {
1651                Ok(Some(self.parse_duckdb_map_literal()?))
1652            }
1653            Keyword::LAMBDA if self.dialect.supports_lambda_functions() => {
1654                Ok(Some(self.parse_lambda_expr()?))
1655            }
1656            _ if self.dialect.supports_geometric_types() => match w.keyword {
1657                Keyword::CIRCLE => Ok(Some(self.parse_geometric_type(GeometricTypeKind::Circle)?)),
1658                Keyword::BOX => Ok(Some(self.parse_geometric_type(GeometricTypeKind::GeometricBox)?)),
1659                Keyword::PATH => Ok(Some(self.parse_geometric_type(GeometricTypeKind::GeometricPath)?)),
1660                Keyword::LINE => Ok(Some(self.parse_geometric_type(GeometricTypeKind::Line)?)),
1661                Keyword::LSEG => Ok(Some(self.parse_geometric_type(GeometricTypeKind::LineSegment)?)),
1662                Keyword::POINT => Ok(Some(self.parse_geometric_type(GeometricTypeKind::Point)?)),
1663                Keyword::POLYGON => Ok(Some(self.parse_geometric_type(GeometricTypeKind::Polygon)?)),
1664                _ => Ok(None),
1665            },
1666            _ => Ok(None),
1667        }
1668    }
1669
1670    /// Tries to parse an expression by a word that is not known to have a special meaning in the dialect.
1671    fn parse_expr_prefix_by_unreserved_word(
1672        &mut self,
1673        w: &Word,
1674        w_span: Span,
1675    ) -> Result<Expr, ParserError> {
1676        let is_outer_join = self.peek_outer_join_operator();
1677        match &self.peek_token_ref().token {
1678            Token::LParen if !is_outer_join => {
1679                let id_parts = vec![w.to_ident(w_span)];
1680                self.parse_function(ObjectName::from(id_parts))
1681            }
1682            // string introducer https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1683            Token::SingleQuotedString(_)
1684            | Token::DoubleQuotedString(_)
1685            | Token::HexStringLiteral(_)
1686                if w.value.starts_with('_') =>
1687            {
1688                Ok(Expr::Prefixed {
1689                    prefix: w.to_ident(w_span),
1690                    value: self.parse_introduced_string_expr()?.into(),
1691                })
1692            }
1693            // string introducer https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1694            Token::SingleQuotedString(_)
1695            | Token::DoubleQuotedString(_)
1696            | Token::HexStringLiteral(_)
1697                if w.value.starts_with('_') =>
1698            {
1699                Ok(Expr::Prefixed {
1700                    prefix: w.to_ident(w_span),
1701                    value: self.parse_introduced_string_expr()?.into(),
1702                })
1703            }
1704            // An unreserved word (likely an identifier) is followed by an arrow,
1705            // which indicates a lambda function with a single, untyped parameter.
1706            // For example: `a -> a * 2`.
1707            Token::Arrow if self.dialect.supports_lambda_functions() => {
1708                self.expect_token(&Token::Arrow)?;
1709                Ok(Expr::Lambda(LambdaFunction {
1710                    params: OneOrManyWithParens::One(LambdaFunctionParameter {
1711                        name: w.to_ident(w_span),
1712                        data_type: None,
1713                    }),
1714                    body: Box::new(self.parse_expr()?),
1715                    syntax: LambdaSyntax::Arrow,
1716                }))
1717            }
1718            // An unreserved word (likely an identifier) that is followed by another word (likley a data type)
1719            // which is then followed by an arrow, which indicates a lambda function with a single, typed parameter.
1720            // For example: `a INT -> a * 2`.
1721            Token::Word(_)
1722                if self.dialect.supports_lambda_functions()
1723                    && self.peek_nth_token_ref(1).token == Token::Arrow =>
1724            {
1725                let data_type = self.parse_data_type()?;
1726                self.expect_token(&Token::Arrow)?;
1727                Ok(Expr::Lambda(LambdaFunction {
1728                    params: OneOrManyWithParens::One(LambdaFunctionParameter {
1729                        name: w.to_ident(w_span),
1730                        data_type: Some(data_type),
1731                    }),
1732                    body: Box::new(self.parse_expr()?),
1733                    syntax: LambdaSyntax::Arrow,
1734                }))
1735            }
1736            _ => Ok(Expr::Identifier(w.to_ident(w_span))),
1737        }
1738    }
1739
1740    /// Returns true if the given [ObjectName] is a single unquoted
1741    /// identifier matching `expected` (case-insensitive).
1742    fn is_simple_unquoted_object_name(name: &ObjectName, expected: &str) -> bool {
1743        if let [ObjectNamePart::Identifier(ident)] = name.0.as_slice() {
1744            ident.quote_style.is_none() && ident.value.eq_ignore_ascii_case(expected)
1745        } else {
1746            false
1747        }
1748    }
1749
1750    /// Parse an expression prefix.
1751    pub fn parse_prefix(&mut self) -> Result<Expr, ParserError> {
1752        // allow the dialect to override prefix parsing
1753        if let Some(prefix) = self.dialect.parse_prefix(self) {
1754            return prefix;
1755        }
1756
1757        // Memoize parse_prefix failures to break 2^N speculation when both
1758        // prefix arms fail at every level (e.g. `IF(current_time(...x`).
1759        // The per-arm cache in `parse_prefix_inner` complements this for
1760        // chains where the reserved arm fails but the unreserved fallback
1761        // succeeds (e.g. `case-case-...c`).
1762        let start_index = self.index;
1763        if let Some(&cached) = self.failed_prefix_positions.get(&start_index) {
1764            return self.cached_prefix_error(cached, self.peek_token_ref());
1765        }
1766        let result = self.parse_prefix_inner();
1767        if let Err(ref e) = result {
1768            self.failed_prefix_positions.insert(start_index, e.into());
1769        }
1770        result
1771    }
1772
1773    /// Rebuild the error for a cached prefix failure at the `found` token.
1774    fn cached_prefix_error<T>(
1775        &self,
1776        cached: ExprPrefixError,
1777        found: &TokenWithSpan,
1778    ) -> Result<T, ParserError> {
1779        match cached {
1780            ExprPrefixError::RecursionLimitExceeded => Err(ParserError::RecursionLimitExceeded),
1781            ExprPrefixError::Err => self.expected_ref("an expression", found),
1782        }
1783    }
1784
1785    fn parse_prefix_inner(&mut self) -> Result<Expr, ParserError> {
1786        // PostgreSQL allows any string literal to be preceded by a type name, indicating that the
1787        // string literal represents a literal of that type. Some examples:
1788        //
1789        //      DATE '2020-05-20'
1790        //      TIMESTAMP WITH TIME ZONE '2020-05-20 7:43:54'
1791        //      BOOL 'true'
1792        //
1793        // The first two are standard SQL, while the latter is a PostgreSQL extension. Complicating
1794        // matters is the fact that INTERVAL string literals may optionally be followed by special
1795        // keywords, e.g.:
1796        //
1797        //      INTERVAL '7' DAY
1798        //
1799        // Note also that naively `SELECT date` looks like a syntax error because the `date` type
1800        // name is not followed by a string literal, but in fact in PostgreSQL it is a valid
1801        // expression that should parse as the column name "date".
1802        let loc = self.peek_token_ref().span.start;
1803        let opt_expr = self.maybe_parse(|parser| {
1804            match parser.parse_data_type()? {
1805                DataType::Interval { .. } => parser.parse_interval(),
1806                // PostgreSQL allows almost any identifier to be used as custom data type name,
1807                // and we support that in `parse_data_type()`. But unlike Postgres we don't
1808                // have a list of globally reserved keywords (since they vary across dialects),
1809                // so given `NOT 'a' LIKE 'b'`, we'd accept `NOT` as a possible custom data type
1810                // name, resulting in `NOT 'a'` being recognized as a `TypedString` instead of
1811                // an unary negation `NOT ('a' LIKE 'b')`. To solve this, we don't accept the
1812                // `type 'string'` syntax for the custom data types at all ...
1813                //
1814                // ... with the exception of `xml '...'` on dialects that support XML
1815                // expressions, which is a valid PostgreSQL typed string literal.
1816                DataType::Custom(ref name, ref modifiers)
1817                    if modifiers.is_empty()
1818                        && Self::is_simple_unquoted_object_name(name, "xml")
1819                        && parser.dialect.supports_xml_expressions() =>
1820                {
1821                    Ok(Expr::TypedString(TypedString {
1822                        data_type: DataType::Custom(name.clone(), modifiers.clone()),
1823                        value: parser.parse_value()?,
1824                        uses_odbc_syntax: false,
1825                    }))
1826                }
1827                DataType::Custom(..) => parser_err!("dummy", loc),
1828                // MySQL supports using the `BINARY` keyword as a cast to binary type.
1829                DataType::Binary(..) if self.dialect.supports_binary_kw_as_cast() => {
1830                    Ok(Expr::Cast {
1831                        kind: CastKind::Cast,
1832                        expr: Box::new(parser.parse_expr()?),
1833                        data_type: DataType::Binary(None),
1834                        array: false,
1835                        format: None,
1836                    })
1837                }
1838                data_type => Ok(Expr::TypedString(TypedString {
1839                    data_type,
1840                    value: parser.parse_value()?,
1841                    uses_odbc_syntax: false,
1842                })),
1843            }
1844        })?;
1845
1846        if let Some(expr) = opt_expr {
1847            return Ok(expr);
1848        }
1849
1850        // Cache some dialect properties to avoid lifetime issues with the
1851        // next_token reference.
1852
1853        let dialect = self.dialect;
1854
1855        self.advance_token();
1856        let next_token_index = self.get_current_index();
1857        let next_token = self.get_current_token();
1858        let span = next_token.span;
1859        let expr = match &next_token.token {
1860            Token::Word(w) => {
1861                // The word we consumed may fall into one of two cases: it has a special meaning, or not.
1862                // For example, in Snowflake, the word `interval` may have two meanings depending on the context:
1863                // `SELECT CURRENT_DATE() + INTERVAL '1 DAY', MAX(interval) FROM tbl;`
1864                //                          ^^^^^^^^^^^^^^^^      ^^^^^^^^
1865                //                         interval expression   identifier
1866                //
1867                // We first try to parse the word and following tokens as a special expression, and if that fails,
1868                // we rollback and try to parse it as an identifier.
1869                let w = w.clone();
1870                // Memoize failed speculative reserved-word parses. When
1871                // the reserved arm (CASE, CURRENT_TIME, etc.) does
1872                // exponential work but the unreserved fallback ultimately
1873                // succeeds, the overall `parse_prefix` returns `Ok` and the
1874                // outer cache never fires. Chains like `case-case-...c`
1875                // need this per-arm cache to break the doubling.
1876                let try_parse_result = if let Some(&cached) = self
1877                    .failed_reserved_word_prefix_positions
1878                    .get(&next_token_index)
1879                {
1880                    self.cached_prefix_error(cached, self.get_current_token())
1881                } else {
1882                    self.try_parse(|parser| parser.parse_expr_prefix_by_reserved_word(&w, span))
1883                };
1884                match try_parse_result {
1885                    // This word indicated an expression prefix and parsing was successful
1886                    Ok(Some(expr)) => Ok(expr),
1887
1888                    // No expression prefix associated with this word
1889                    Ok(None) => Ok(self.parse_expr_prefix_by_unreserved_word(&w, span)?),
1890
1891                    // If parsing of the word as a special expression failed, we are facing two options:
1892                    // 1. The statement is malformed, e.g. `SELECT INTERVAL '1 DAI` (`DAI` instead of `DAY`)
1893                    // 2. The word is used as an identifier, e.g. `SELECT MAX(interval) FROM tbl`
1894                    // We first try to parse the word as an identifier and if that fails
1895                    // we rollback and return the parsing error we got from trying to parse a
1896                    // special expression (to maintain backwards compatibility of parsing errors).
1897                    Err(e) => {
1898                        self.failed_reserved_word_prefix_positions
1899                            .insert(next_token_index, (&e).into());
1900                        if !self.dialect.is_reserved_for_identifier(w.keyword) {
1901                            if let Ok(Some(expr)) = self.maybe_parse(|parser| {
1902                                parser.parse_expr_prefix_by_unreserved_word(&w, span)
1903                            }) {
1904                                return Ok(expr);
1905                            }
1906                        }
1907                        return Err(e);
1908                    }
1909                }
1910            } // End of Token::Word
1911            // array `[1, 2, 3]`
1912            Token::LBracket => self.parse_array_expr(false),
1913            tok @ Token::Minus | tok @ Token::Plus => {
1914                let op = if *tok == Token::Plus {
1915                    UnaryOperator::Plus
1916                } else {
1917                    UnaryOperator::Minus
1918                };
1919                Ok(Expr::UnaryOp {
1920                    op,
1921                    expr: Box::new(
1922                        self.parse_subexpr(self.dialect.prec_value(Precedence::MulDivModOp))?,
1923                    ),
1924                })
1925            }
1926            Token::ExclamationMark if dialect.supports_bang_not_operator() => Ok(Expr::UnaryOp {
1927                op: UnaryOperator::BangNot,
1928                expr: Box::new(self.parse_subexpr(self.dialect.prec_value(Precedence::UnaryNot))?),
1929            }),
1930            tok @ Token::DoubleExclamationMark
1931            | tok @ Token::PGSquareRoot
1932            | tok @ Token::PGCubeRoot
1933            | tok @ Token::AtSign
1934                if dialect_is!(dialect is PostgreSqlDialect) =>
1935            {
1936                let op = match tok {
1937                    Token::DoubleExclamationMark => UnaryOperator::PGPrefixFactorial,
1938                    Token::PGSquareRoot => UnaryOperator::PGSquareRoot,
1939                    Token::PGCubeRoot => UnaryOperator::PGCubeRoot,
1940                    Token::AtSign => UnaryOperator::PGAbs,
1941                    _ => {
1942                        return Err(ParserError::ParserError(
1943                            "Internal parser error: unexpected unary operator token".to_string(),
1944                        ))
1945                    }
1946                };
1947                Ok(Expr::UnaryOp {
1948                    op,
1949                    expr: Box::new(
1950                        self.parse_subexpr(self.dialect.prec_value(Precedence::PlusMinus))?,
1951                    ),
1952                })
1953            }
1954            Token::Tilde => Ok(Expr::UnaryOp {
1955                op: UnaryOperator::BitwiseNot,
1956                expr: Box::new(self.parse_subexpr(self.dialect.prec_value(Precedence::PlusMinus))?),
1957            }),
1958            tok @ Token::Sharp
1959            | tok @ Token::AtDashAt
1960            | tok @ Token::AtAt
1961            | tok @ Token::QuestionMarkDash
1962            | tok @ Token::QuestionPipe
1963                if self.dialect.supports_geometric_types() =>
1964            {
1965                let op = match tok {
1966                    Token::Sharp => UnaryOperator::Hash,
1967                    Token::AtDashAt => UnaryOperator::AtDashAt,
1968                    Token::AtAt => UnaryOperator::DoubleAt,
1969                    Token::QuestionMarkDash => UnaryOperator::QuestionDash,
1970                    Token::QuestionPipe => UnaryOperator::QuestionPipe,
1971                    _ => {
1972                        return Err(ParserError::ParserError(format!(
1973                            "Unexpected token in unary operator parsing: {tok:?}"
1974                        )))
1975                    }
1976                };
1977                Ok(Expr::UnaryOp {
1978                    op,
1979                    expr: Box::new(
1980                        self.parse_subexpr(self.dialect.prec_value(Precedence::PlusMinus))?,
1981                    ),
1982                })
1983            }
1984            Token::EscapedStringLiteral(_) if dialect_is!(dialect is PostgreSqlDialect | GenericDialect) =>
1985            {
1986                self.prev_token();
1987                Ok(Expr::Value(self.parse_value()?))
1988            }
1989            Token::UnicodeStringLiteral(_) => {
1990                self.prev_token();
1991                Ok(Expr::Value(self.parse_value()?))
1992            }
1993            Token::Number(_, _)
1994            | Token::SingleQuotedString(_)
1995            | Token::DoubleQuotedString(_)
1996            | Token::TripleSingleQuotedString(_)
1997            | Token::TripleDoubleQuotedString(_)
1998            | Token::DollarQuotedString(_)
1999            | Token::SingleQuotedByteStringLiteral(_)
2000            | Token::DoubleQuotedByteStringLiteral(_)
2001            | Token::TripleSingleQuotedByteStringLiteral(_)
2002            | Token::TripleDoubleQuotedByteStringLiteral(_)
2003            | Token::SingleQuotedRawStringLiteral(_)
2004            | Token::DoubleQuotedRawStringLiteral(_)
2005            | Token::TripleSingleQuotedRawStringLiteral(_)
2006            | Token::TripleDoubleQuotedRawStringLiteral(_)
2007            | Token::NationalStringLiteral(_)
2008            | Token::QuoteDelimitedStringLiteral(_)
2009            | Token::NationalQuoteDelimitedStringLiteral(_)
2010            | Token::HexStringLiteral(_) => {
2011                self.prev_token();
2012                Ok(Expr::Value(self.parse_value()?))
2013            }
2014            Token::LParen => {
2015                let expr =
2016                    if let Some(expr) = self.try_parse_expr_sub_query()? {
2017                        expr
2018                    } else if let Some(lambda) = self.try_parse_lambda()? {
2019                        return Ok(lambda);
2020                    } else {
2021                        // Parentheses in expressions switch to "normal" parsing state.
2022                        // This matters for dialects (SQLite, DuckDB) where `NOT NULL` can
2023                        // be an alias for `IS NOT NULL`. In column definitions like:
2024                        //
2025                        //   CREATE TABLE t (c INT DEFAULT (42 NOT NULL) NOT NULL)
2026                        //
2027                        // The `(42 NOT NULL)` is an expression with parens, so it parses
2028                        // as `IsNotNull(42)`. The trailing `NOT NULL` is outside those
2029                        // expression parens (the outer parens are CREATE TABLE syntax),
2030                        // so it remains a column constraint.
2031                        let exprs = self.with_state(ParserState::Normal, |p| {
2032                            p.parse_comma_separated(Parser::parse_expr)
2033                        })?;
2034                        match exprs.len() {
2035                            0 => return Err(ParserError::ParserError(
2036                                "Internal parser error: parse_comma_separated returned empty list"
2037                                    .to_string(),
2038                            )),
2039                            1 => Expr::Nested(Box::new(exprs.into_iter().next().unwrap())),
2040                            _ => Expr::Tuple(exprs),
2041                        }
2042                    };
2043                self.expect_token(&Token::RParen)?;
2044                Ok(expr)
2045            }
2046            Token::Placeholder(_) | Token::Colon | Token::AtSign => {
2047                self.prev_token();
2048                Ok(Expr::Value(self.parse_value()?))
2049            }
2050            Token::LBrace => {
2051                self.prev_token();
2052                self.parse_lbrace_expr()
2053            }
2054            _ => self.expected_at("an expression", next_token_index),
2055        }?;
2056
2057        Ok(expr)
2058    }
2059
2060    fn parse_geometric_type(&mut self, kind: GeometricTypeKind) -> Result<Expr, ParserError> {
2061        Ok(Expr::TypedString(TypedString {
2062            data_type: DataType::GeometricType(kind),
2063            value: self.parse_value()?,
2064            uses_odbc_syntax: false,
2065        }))
2066    }
2067
2068    /// Try to parse an [Expr::CompoundFieldAccess] like `a.b.c` or `a.b[1].c`.
2069    /// If all the fields are `Expr::Identifier`s, return an [Expr::CompoundIdentifier] instead.
2070    /// If only the root exists, return the root.
2071    /// Parses compound expressions which may be delimited by period
2072    /// or bracket notation.
2073    /// For example: `a.b.c`, `a.b[1]`.
2074    pub fn parse_compound_expr(
2075        &mut self,
2076        root: Expr,
2077        mut chain: Vec<AccessExpr>,
2078    ) -> Result<Expr, ParserError> {
2079        let mut ending_wildcard: Option<TokenWithSpan> = None;
2080        loop {
2081            if self.consume_token(&Token::Period) {
2082                let next_token = self.peek_token_ref();
2083                match &next_token.token {
2084                    Token::Mul => {
2085                        // Postgres explicitly allows funcnm(tablenm.*) and the
2086                        // function array_agg traverses this control flow
2087                        if dialect_of!(self is PostgreSqlDialect) {
2088                            ending_wildcard = Some(self.next_token());
2089                        } else {
2090                            // Put back the consumed `.` tokens before exiting.
2091                            // If this expression is being parsed in the
2092                            // context of a projection, then the `.*` could imply
2093                            // a wildcard expansion. For example:
2094                            // `SELECT STRUCT('foo').* FROM T`
2095                            self.prev_token(); // .
2096                        }
2097
2098                        break;
2099                    }
2100                    Token::SingleQuotedString(s) => {
2101                        let expr =
2102                            Expr::Identifier(Ident::with_quote_and_span('\'', next_token.span, s));
2103                        chain.push(AccessExpr::Dot(expr));
2104                        self.advance_token(); // The consumed string
2105                    }
2106                    Token::Placeholder(s) => {
2107                        // Snowflake uses $1, $2, etc. for positional column references
2108                        // in staged data queries like: SELECT t.$1 FROM @stage t
2109                        let expr = Expr::Identifier(Ident::with_span(next_token.span, s));
2110                        chain.push(AccessExpr::Dot(expr));
2111                        self.advance_token(); // The consumed placeholder
2112                    }
2113                    // Parse a single field component, restricted to expression types valid
2114                    // after `.` (so e.g. `T.interval` is a compound identifier, not an
2115                    // interval expression). Using `parse_prefix` here rather than
2116                    // `parse_subexpr` avoids 2^N work on inputs like `IF a.b.c...x.#`:
2117                    // the outer loop already consumes successive `.field` segments, so a
2118                    // recursive `parse_subexpr` would re-walk the rest of the chain at
2119                    // every dot.
2120                    _ => {
2121                        // For a plain `Word` field (not followed by `(`), skip the
2122                        // speculative `parse_prefix`. The only result the validator
2123                        // below would accept is `Identifier`, which `parse_identifier`
2124                        // in the None branch produces directly. This avoids 2^N work
2125                        // on chains like `.not-b.not-b...` where `parse_prefix` would
2126                        // descend into `parse_not` and re-walk the remaining chain at
2127                        // every segment.
2128                        let word_field_no_lparen =
2129                            matches!(self.peek_token_ref().token, Token::Word(_))
2130                                && self.peek_nth_token_ref(1).token != Token::LParen;
2131
2132                        let expr = if word_field_no_lparen {
2133                            None
2134                        } else {
2135                            self.maybe_parse(|parser| {
2136                                let expr = parser.parse_prefix()?;
2137                                match &expr {
2138                                    Expr::CompoundFieldAccess { .. }
2139                                    | Expr::CompoundIdentifier(_)
2140                                    | Expr::Identifier(_)
2141                                    | Expr::Value(_)
2142                                    | Expr::Function(_) => Ok(expr),
2143                                    _ => parser.expected_ref(
2144                                        "an identifier or value",
2145                                        parser.peek_token_ref(),
2146                                    ),
2147                                }
2148                            })?
2149                        };
2150
2151                        match expr {
2152                            // If we get back a compound field access or identifier,
2153                            // we flatten the nested expression.
2154                            // For example if the current root is `foo`
2155                            // and we get back a compound identifier expression `bar.baz`
2156                            // The full expression should be `foo.bar.baz` (i.e.
2157                            // a root with an access chain with 2 entries) and not
2158                            // `foo.(bar.baz)` (i.e. a root with an access chain with
2159                            // 1 entry`).
2160                            Some(Expr::CompoundFieldAccess { root, access_chain }) => {
2161                                chain.push(AccessExpr::Dot(*root));
2162                                chain.extend(access_chain);
2163                            }
2164                            Some(Expr::CompoundIdentifier(parts)) => chain.extend(
2165                                parts.into_iter().map(Expr::Identifier).map(AccessExpr::Dot),
2166                            ),
2167                            Some(expr) => {
2168                                chain.push(AccessExpr::Dot(expr));
2169                            }
2170                            // If the expression is not a valid suffix, fall back to
2171                            // parsing as an identifier. This handles cases like `T.interval`
2172                            // where `interval` is a keyword but should be treated as an identifier.
2173                            None => {
2174                                chain.push(AccessExpr::Dot(Expr::Identifier(
2175                                    self.parse_identifier()?,
2176                                )));
2177                            }
2178                        }
2179                    }
2180                }
2181            } else if !self.dialect.supports_partiql()
2182                && self.peek_token_ref().token == Token::LBracket
2183            {
2184                self.parse_multi_dim_subscript(&mut chain)?;
2185            } else {
2186                break;
2187            }
2188        }
2189
2190        let tok_index = self.get_current_index();
2191        if let Some(wildcard_token) = ending_wildcard {
2192            if !Self::is_all_ident(&root, &chain) {
2193                return self
2194                    .expected_ref("an identifier or a '*' after '.'", self.peek_token_ref());
2195            };
2196            Ok(Expr::QualifiedWildcard(
2197                ObjectName::from(Self::exprs_to_idents(root, chain)?),
2198                AttachedToken(wildcard_token),
2199            ))
2200        } else if self.maybe_parse_outer_join_operator() {
2201            if !Self::is_all_ident(&root, &chain) {
2202                return self.expected_at("column identifier before (+)", tok_index);
2203            };
2204            let expr = if chain.is_empty() {
2205                root
2206            } else {
2207                Expr::CompoundIdentifier(Self::exprs_to_idents(root, chain)?)
2208            };
2209            Ok(Expr::OuterJoin(expr.into()))
2210        } else {
2211            Self::build_compound_expr(root, chain)
2212        }
2213    }
2214
2215    /// Combines a root expression and access chain to form
2216    /// a compound expression. Which may be a [Expr::CompoundFieldAccess]
2217    /// or other special cased expressions like [Expr::CompoundIdentifier],
2218    /// [Expr::OuterJoin].
2219    fn build_compound_expr(
2220        root: Expr,
2221        mut access_chain: Vec<AccessExpr>,
2222    ) -> Result<Expr, ParserError> {
2223        if access_chain.is_empty() {
2224            return Ok(root);
2225        }
2226
2227        if Self::is_all_ident(&root, &access_chain) {
2228            return Ok(Expr::CompoundIdentifier(Self::exprs_to_idents(
2229                root,
2230                access_chain,
2231            )?));
2232        }
2233
2234        // Flatten qualified function calls.
2235        // For example, the expression `a.b.c.foo(1,2,3)` should
2236        // represent a function called `a.b.c.foo`, rather than
2237        // a composite expression.
2238        if matches!(root, Expr::Identifier(_))
2239            && matches!(
2240                access_chain.last(),
2241                Some(AccessExpr::Dot(Expr::Function(_)))
2242            )
2243            && access_chain
2244                .iter()
2245                .rev()
2246                .skip(1) // All except the Function
2247                .all(|access| matches!(access, AccessExpr::Dot(Expr::Identifier(_))))
2248        {
2249            let Some(AccessExpr::Dot(Expr::Function(mut func))) = access_chain.pop() else {
2250                return parser_err!("expected function expression", root.span().start);
2251            };
2252
2253            let compound_func_name = [root]
2254                .into_iter()
2255                .chain(access_chain.into_iter().flat_map(|access| match access {
2256                    AccessExpr::Dot(expr) => Some(expr),
2257                    _ => None,
2258                }))
2259                .flat_map(|expr| match expr {
2260                    Expr::Identifier(ident) => Some(ident),
2261                    _ => None,
2262                })
2263                .map(ObjectNamePart::Identifier)
2264                .chain(func.name.0)
2265                .collect::<Vec<_>>();
2266            func.name = ObjectName(compound_func_name);
2267
2268            return Ok(Expr::Function(func));
2269        }
2270
2271        // Flatten qualified outer join expressions.
2272        // For example, the expression `T.foo(+)` should
2273        // represent an outer join on the column name `T.foo`
2274        // rather than a composite expression.
2275        if access_chain.len() == 1
2276            && matches!(
2277                access_chain.last(),
2278                Some(AccessExpr::Dot(Expr::OuterJoin(_)))
2279            )
2280        {
2281            let Some(AccessExpr::Dot(Expr::OuterJoin(inner_expr))) = access_chain.pop() else {
2282                return parser_err!("expected (+) expression", root.span().start);
2283            };
2284
2285            if !Self::is_all_ident(&root, &[]) {
2286                return parser_err!("column identifier before (+)", root.span().start);
2287            };
2288
2289            let token_start = root.span().start;
2290            let mut idents = Self::exprs_to_idents(root, vec![])?;
2291            match *inner_expr {
2292                Expr::CompoundIdentifier(suffix) => idents.extend(suffix),
2293                Expr::Identifier(suffix) => idents.push(suffix),
2294                _ => {
2295                    return parser_err!("column identifier before (+)", token_start);
2296                }
2297            }
2298
2299            return Ok(Expr::OuterJoin(Expr::CompoundIdentifier(idents).into()));
2300        }
2301
2302        Ok(Expr::CompoundFieldAccess {
2303            root: Box::new(root),
2304            access_chain,
2305        })
2306    }
2307
2308    fn keyword_to_modifier(k: Keyword) -> Option<ContextModifier> {
2309        match k {
2310            Keyword::LOCAL => Some(ContextModifier::Local),
2311            Keyword::GLOBAL => Some(ContextModifier::Global),
2312            Keyword::SESSION => Some(ContextModifier::Session),
2313            _ => None,
2314        }
2315    }
2316
2317    /// Check if the root is an identifier and all fields are identifiers.
2318    fn is_all_ident(root: &Expr, fields: &[AccessExpr]) -> bool {
2319        if !matches!(root, Expr::Identifier(_)) {
2320            return false;
2321        }
2322        fields
2323            .iter()
2324            .all(|x| matches!(x, AccessExpr::Dot(Expr::Identifier(_))))
2325    }
2326
2327    /// Convert a root and a list of fields to a list of identifiers.
2328    fn exprs_to_idents(root: Expr, fields: Vec<AccessExpr>) -> Result<Vec<Ident>, ParserError> {
2329        let mut idents = vec![];
2330        if let Expr::Identifier(root) = root {
2331            idents.push(root);
2332            for x in fields {
2333                if let AccessExpr::Dot(Expr::Identifier(ident)) = x {
2334                    idents.push(ident);
2335                } else {
2336                    return parser_err!(
2337                        format!("Expected identifier, found: {}", x),
2338                        x.span().start
2339                    );
2340                }
2341            }
2342            Ok(idents)
2343        } else {
2344            parser_err!(
2345                format!("Expected identifier, found: {}", root),
2346                root.span().start
2347            )
2348        }
2349    }
2350
2351    /// Returns true if the next tokens indicate the outer join operator `(+)`.
2352    fn peek_outer_join_operator(&mut self) -> bool {
2353        if !self.dialect.supports_outer_join_operator() {
2354            return false;
2355        }
2356
2357        let [maybe_lparen, maybe_plus, maybe_rparen] = self.peek_tokens_ref();
2358        Token::LParen == maybe_lparen.token
2359            && Token::Plus == maybe_plus.token
2360            && Token::RParen == maybe_rparen.token
2361    }
2362
2363    /// If the next tokens indicates the outer join operator `(+)`, consume
2364    /// the tokens and return true.
2365    fn maybe_parse_outer_join_operator(&mut self) -> bool {
2366        self.dialect.supports_outer_join_operator()
2367            && self.consume_tokens(&[Token::LParen, Token::Plus, Token::RParen])
2368    }
2369
2370    /// Parse utility options in the form of `(option1, option2 arg2, option3 arg3, ...)`
2371    pub fn parse_utility_options(&mut self) -> Result<Vec<UtilityOption>, ParserError> {
2372        self.expect_token(&Token::LParen)?;
2373        let options = self.parse_comma_separated(Self::parse_utility_option)?;
2374        self.expect_token(&Token::RParen)?;
2375
2376        Ok(options)
2377    }
2378
2379    fn parse_utility_option(&mut self) -> Result<UtilityOption, ParserError> {
2380        let name = self.parse_identifier()?;
2381
2382        let next_token = self.peek_token_ref();
2383        if next_token == &Token::Comma || next_token == &Token::RParen {
2384            return Ok(UtilityOption { name, arg: None });
2385        }
2386        let arg = self.parse_expr()?;
2387
2388        Ok(UtilityOption {
2389            name,
2390            arg: Some(arg),
2391        })
2392    }
2393
2394    fn try_parse_expr_sub_query(&mut self) -> Result<Option<Expr>, ParserError> {
2395        if !self.peek_sub_query() {
2396            return Ok(None);
2397        }
2398
2399        Ok(Some(Expr::Subquery(self.parse_query()?)))
2400    }
2401
2402    fn try_parse_lambda(&mut self) -> Result<Option<Expr>, ParserError> {
2403        if !self.dialect.supports_lambda_functions() {
2404            return Ok(None);
2405        }
2406        self.maybe_parse(|p| {
2407            let params = p.parse_comma_separated(|p| p.parse_lambda_function_parameter())?;
2408            p.expect_token(&Token::RParen)?;
2409            p.expect_token(&Token::Arrow)?;
2410            let expr = p.parse_expr()?;
2411            Ok(Expr::Lambda(LambdaFunction {
2412                params: OneOrManyWithParens::Many(params),
2413                body: Box::new(expr),
2414                syntax: LambdaSyntax::Arrow,
2415            }))
2416        })
2417    }
2418
2419    /// Parses a lambda expression following the `LAMBDA` keyword syntax.
2420    ///
2421    /// Syntax: `LAMBDA <params> : <expr>`
2422    ///
2423    /// Examples:
2424    /// - `LAMBDA x : x + 1`
2425    /// - `LAMBDA x, i : x > i`
2426    ///
2427    /// See <https://duckdb.org/docs/stable/sql/functions/lambda>
2428    fn parse_lambda_expr(&mut self) -> Result<Expr, ParserError> {
2429        // Parse the parameters: either a single identifier or comma-separated identifiers
2430        let params = self.parse_lambda_function_parameters()?;
2431        // Expect the colon separator
2432        self.expect_token(&Token::Colon)?;
2433        // Parse the body expression
2434        let body = self.parse_expr()?;
2435        Ok(Expr::Lambda(LambdaFunction {
2436            params,
2437            body: Box::new(body),
2438            syntax: LambdaSyntax::LambdaKeyword,
2439        }))
2440    }
2441
2442    /// Parses the parameters of a lambda function with optional typing.
2443    fn parse_lambda_function_parameters(
2444        &mut self,
2445    ) -> Result<OneOrManyWithParens<LambdaFunctionParameter>, ParserError> {
2446        // Parse the parameters: either a single identifier or comma-separated identifiers
2447        let params = if self.consume_token(&Token::LParen) {
2448            // Parenthesized parameters: (x, y)
2449            let params = self.parse_comma_separated(|p| p.parse_lambda_function_parameter())?;
2450            self.expect_token(&Token::RParen)?;
2451            OneOrManyWithParens::Many(params)
2452        } else {
2453            // Unparenthesized parameters: x or x, y
2454            let params = self.parse_comma_separated(|p| p.parse_lambda_function_parameter())?;
2455            if params.len() == 1 {
2456                OneOrManyWithParens::One(params.into_iter().next().unwrap())
2457            } else {
2458                OneOrManyWithParens::Many(params)
2459            }
2460        };
2461        Ok(params)
2462    }
2463
2464    /// Parses a single parameter of a lambda function, with optional typing.
2465    fn parse_lambda_function_parameter(&mut self) -> Result<LambdaFunctionParameter, ParserError> {
2466        let name = self.parse_identifier()?;
2467        let data_type = match &self.peek_token_ref().token {
2468            Token::Word(_) => self.maybe_parse(|p| p.parse_data_type())?,
2469            _ => None,
2470        };
2471        Ok(LambdaFunctionParameter { name, data_type })
2472    }
2473
2474    /// Tries to parse the body of an [ODBC escaping sequence]
2475    /// i.e. without the enclosing braces
2476    /// Currently implemented:
2477    /// Scalar Function Calls
2478    /// Date, Time, and Timestamp Literals
2479    /// See <https://learn.microsoft.com/en-us/sql/odbc/reference/develop-app/escape-sequences-in-odbc?view=sql-server-2017>
2480    fn maybe_parse_odbc_body(&mut self) -> Result<Option<Expr>, ParserError> {
2481        // Attempt 1: Try to parse it as a function.
2482        if let Some(expr) = self.maybe_parse_odbc_fn_body()? {
2483            return Ok(Some(expr));
2484        }
2485        // Attempt 2: Try to parse it as a Date, Time or Timestamp Literal
2486        self.maybe_parse_odbc_body_datetime()
2487    }
2488
2489    /// Tries to parse the body of an [ODBC Date, Time, and Timestamp Literals] call.
2490    ///
2491    /// ```sql
2492    /// {d '2025-07-17'}
2493    /// {t '14:12:01'}
2494    /// {ts '2025-07-17 14:12:01'}
2495    /// ```
2496    ///
2497    /// [ODBC Date, Time, and Timestamp Literals]:
2498    /// https://learn.microsoft.com/en-us/sql/odbc/reference/develop-app/date-time-and-timestamp-literals?view=sql-server-2017
2499    fn maybe_parse_odbc_body_datetime(&mut self) -> Result<Option<Expr>, ParserError> {
2500        self.maybe_parse(|p| {
2501            let token = p.next_token().clone();
2502            let word_string = token.token.to_string();
2503            let data_type = match word_string.as_str() {
2504                "t" => DataType::Time(None, TimezoneInfo::None),
2505                "d" => DataType::Date,
2506                "ts" => DataType::Timestamp(None, TimezoneInfo::None),
2507                _ => return p.expected("ODBC datetime keyword (t, d, or ts)", token),
2508            };
2509            let value = p.parse_value()?;
2510            Ok(Expr::TypedString(TypedString {
2511                data_type,
2512                value,
2513                uses_odbc_syntax: true,
2514            }))
2515        })
2516    }
2517
2518    /// Tries to parse the body of an [ODBC function] call.
2519    /// i.e. without the enclosing braces
2520    ///
2521    /// ```sql
2522    /// fn myfunc(1,2,3)
2523    /// ```
2524    ///
2525    /// [ODBC function]: https://learn.microsoft.com/en-us/sql/odbc/reference/develop-app/scalar-function-calls?view=sql-server-2017
2526    fn maybe_parse_odbc_fn_body(&mut self) -> Result<Option<Expr>, ParserError> {
2527        self.maybe_parse(|p| {
2528            p.expect_keyword(Keyword::FN)?;
2529            let fn_name = p.parse_object_name(false)?;
2530            let mut fn_call = p.parse_function_call(fn_name)?;
2531            fn_call.uses_odbc_syntax = true;
2532            Ok(Expr::Function(fn_call))
2533        })
2534    }
2535
2536    /// Parse a function call expression named by `name` and return it as an `Expr`.
2537    pub fn parse_function(&mut self, name: ObjectName) -> Result<Expr, ParserError> {
2538        self.parse_function_call(name).map(Expr::Function)
2539    }
2540
2541    fn parse_function_call(&mut self, name: ObjectName) -> Result<Function, ParserError> {
2542        self.expect_token(&Token::LParen)?;
2543
2544        // Snowflake permits a subquery to be passed as an argument without
2545        // an enclosing set of parens if it's the only argument.
2546        if self.dialect.supports_subquery_as_function_arg() && self.peek_sub_query() {
2547            let subquery = self.parse_query()?;
2548            self.expect_token(&Token::RParen)?;
2549            return Ok(Function {
2550                name,
2551                uses_odbc_syntax: false,
2552                parameters: FunctionArguments::None,
2553                args: FunctionArguments::Subquery(subquery),
2554                filter: None,
2555                null_treatment: None,
2556                over: None,
2557                within_group: vec![],
2558            });
2559        }
2560
2561        let mut args = self.parse_function_argument_list()?;
2562        let mut parameters = FunctionArguments::None;
2563        // ClickHouse aggregations support parametric functions like `HISTOGRAM(0.5, 0.6)(x, y)`
2564        // which (0.5, 0.6) is a parameter to the function.
2565        if dialect_of!(self is ClickHouseDialect | GenericDialect)
2566            && self.consume_token(&Token::LParen)
2567        {
2568            parameters = FunctionArguments::List(args);
2569            args = self.parse_function_argument_list()?;
2570        }
2571
2572        let within_group = if self.parse_keywords(&[Keyword::WITHIN, Keyword::GROUP]) {
2573            self.expect_token(&Token::LParen)?;
2574            self.expect_keywords(&[Keyword::ORDER, Keyword::BY])?;
2575            let order_by = self.parse_comma_separated(Parser::parse_order_by_expr)?;
2576            self.expect_token(&Token::RParen)?;
2577            order_by
2578        } else {
2579            vec![]
2580        };
2581
2582        let filter = if self.dialect.supports_filter_during_aggregation()
2583            && self.parse_keyword(Keyword::FILTER)
2584            && self.consume_token(&Token::LParen)
2585            && self.parse_keyword(Keyword::WHERE)
2586        {
2587            let filter = Some(Box::new(self.parse_expr()?));
2588            self.expect_token(&Token::RParen)?;
2589            filter
2590        } else {
2591            None
2592        };
2593
2594        // Syntax for null treatment shows up either in the args list
2595        // or after the function call, but not both.
2596        let null_treatment = if args
2597            .clauses
2598            .iter()
2599            .all(|clause| !matches!(clause, FunctionArgumentClause::IgnoreOrRespectNulls(_)))
2600        {
2601            self.parse_null_treatment()?
2602        } else {
2603            None
2604        };
2605
2606        let over = if self.parse_keyword(Keyword::OVER) {
2607            if self.consume_token(&Token::LParen) {
2608                let window_spec = self.parse_window_spec()?;
2609                Some(WindowType::WindowSpec(window_spec))
2610            } else {
2611                Some(WindowType::NamedWindow(self.parse_identifier()?))
2612            }
2613        } else {
2614            None
2615        };
2616
2617        Ok(Function {
2618            name,
2619            uses_odbc_syntax: false,
2620            parameters,
2621            args: FunctionArguments::List(args),
2622            null_treatment,
2623            filter,
2624            over,
2625            within_group,
2626        })
2627    }
2628
2629    /// Optionally parses a null treatment clause.
2630    fn parse_null_treatment(&mut self) -> Result<Option<NullTreatment>, ParserError> {
2631        match self.parse_one_of_keywords(&[Keyword::RESPECT, Keyword::IGNORE]) {
2632            Some(keyword) => {
2633                self.expect_keyword_is(Keyword::NULLS)?;
2634
2635                Ok(match keyword {
2636                    Keyword::RESPECT => Some(NullTreatment::RespectNulls),
2637                    Keyword::IGNORE => Some(NullTreatment::IgnoreNulls),
2638                    _ => None,
2639                })
2640            }
2641            None => Ok(None),
2642        }
2643    }
2644
2645    /// Parse time-related function `name` possibly followed by `(...)` arguments.
2646    pub fn parse_time_functions(&mut self, name: ObjectName) -> Result<Expr, ParserError> {
2647        let args = if self.consume_token(&Token::LParen) {
2648            FunctionArguments::List(self.parse_function_argument_list()?)
2649        } else {
2650            FunctionArguments::None
2651        };
2652        Ok(Expr::Function(Function {
2653            name,
2654            uses_odbc_syntax: false,
2655            parameters: FunctionArguments::None,
2656            args,
2657            filter: None,
2658            over: None,
2659            null_treatment: None,
2660            within_group: vec![],
2661        }))
2662    }
2663
2664    /// Parse window frame `UNITS` clause: `ROWS`, `RANGE`, or `GROUPS`.
2665    pub fn parse_window_frame_units(&mut self) -> Result<WindowFrameUnits, ParserError> {
2666        let next_token = self.next_token();
2667        match &next_token.token {
2668            Token::Word(w) => match w.keyword {
2669                Keyword::ROWS => Ok(WindowFrameUnits::Rows),
2670                Keyword::RANGE => Ok(WindowFrameUnits::Range),
2671                Keyword::GROUPS => Ok(WindowFrameUnits::Groups),
2672                _ => self.expected("ROWS, RANGE, GROUPS", next_token)?,
2673            },
2674            _ => self.expected("ROWS, RANGE, GROUPS", next_token),
2675        }
2676    }
2677
2678    /// Parse a `WINDOW` frame definition (units and bounds).
2679    pub fn parse_window_frame(&mut self) -> Result<WindowFrame, ParserError> {
2680        let units = self.parse_window_frame_units()?;
2681        let (start_bound, end_bound) = if self.parse_keyword(Keyword::BETWEEN) {
2682            let start_bound = self.parse_window_frame_bound()?;
2683            self.expect_keyword_is(Keyword::AND)?;
2684            let end_bound = Some(self.parse_window_frame_bound()?);
2685            (start_bound, end_bound)
2686        } else {
2687            (self.parse_window_frame_bound()?, None)
2688        };
2689        Ok(WindowFrame {
2690            units,
2691            start_bound,
2692            end_bound,
2693        })
2694    }
2695
2696    /// Parse a window frame bound: `CURRENT ROW` or `<n> PRECEDING|FOLLOWING`.
2697    pub fn parse_window_frame_bound(&mut self) -> Result<WindowFrameBound, ParserError> {
2698        if self.parse_keywords(&[Keyword::CURRENT, Keyword::ROW]) {
2699            Ok(WindowFrameBound::CurrentRow)
2700        } else {
2701            let rows = if self.parse_keyword(Keyword::UNBOUNDED) {
2702                None
2703            } else {
2704                Some(Box::new(match &self.peek_token_ref().token {
2705                    Token::SingleQuotedString(_) => self.parse_interval()?,
2706                    _ => self.parse_expr()?,
2707                }))
2708            };
2709            if self.parse_keyword(Keyword::PRECEDING) {
2710                Ok(WindowFrameBound::Preceding(rows))
2711            } else if self.parse_keyword(Keyword::FOLLOWING) {
2712                Ok(WindowFrameBound::Following(rows))
2713            } else {
2714                self.expected_ref("PRECEDING or FOLLOWING", self.peek_token_ref())
2715            }
2716        }
2717    }
2718
2719    /// Parse a group by expr. Group by expr can be one of group sets, roll up, cube, or simple expr.
2720    fn parse_group_by_expr(&mut self) -> Result<Expr, ParserError> {
2721        if self.dialect.supports_group_by_expr() {
2722            if self.parse_keywords(&[Keyword::GROUPING, Keyword::SETS]) {
2723                self.expect_token(&Token::LParen)?;
2724                let result = self.parse_comma_separated(|p| p.parse_tuple(true, true))?;
2725                self.expect_token(&Token::RParen)?;
2726                Ok(Expr::GroupingSets(result))
2727            } else if self.parse_keyword(Keyword::CUBE) {
2728                self.expect_token(&Token::LParen)?;
2729                let result = self.parse_comma_separated(|p| p.parse_tuple(true, true))?;
2730                self.expect_token(&Token::RParen)?;
2731                Ok(Expr::Cube(result))
2732            } else if self.parse_keyword(Keyword::ROLLUP) {
2733                self.expect_token(&Token::LParen)?;
2734                let result = self.parse_comma_separated(|p| p.parse_tuple(true, true))?;
2735                self.expect_token(&Token::RParen)?;
2736                Ok(Expr::Rollup(result))
2737            } else if self.consume_tokens(&[Token::LParen, Token::RParen]) {
2738                // PostgreSQL allow to use empty tuple as a group by expression,
2739                // e.g. `GROUP BY (), name`. Please refer to GROUP BY Clause section in
2740                // [PostgreSQL](https://www.postgresql.org/docs/16/sql-select.html)
2741                Ok(Expr::Tuple(vec![]))
2742            } else {
2743                self.parse_expr()
2744            }
2745        } else {
2746            // TODO parse rollup for other dialects
2747            self.parse_expr()
2748        }
2749    }
2750
2751    /// Parse a tuple with `(` and `)`.
2752    /// If `lift_singleton` is true, then a singleton tuple is lifted to a tuple of length 1, otherwise it will fail.
2753    /// If `allow_empty` is true, then an empty tuple is allowed.
2754    fn parse_tuple(
2755        &mut self,
2756        lift_singleton: bool,
2757        allow_empty: bool,
2758    ) -> Result<Vec<Expr>, ParserError> {
2759        if lift_singleton {
2760            if self.consume_token(&Token::LParen) {
2761                let result = if allow_empty && self.consume_token(&Token::RParen) {
2762                    vec![]
2763                } else {
2764                    let result = self.parse_comma_separated(Parser::parse_expr)?;
2765                    self.expect_token(&Token::RParen)?;
2766                    result
2767                };
2768                Ok(result)
2769            } else {
2770                Ok(vec![self.parse_expr()?])
2771            }
2772        } else {
2773            self.expect_token(&Token::LParen)?;
2774            let result = if allow_empty && self.consume_token(&Token::RParen) {
2775                vec![]
2776            } else {
2777                let result = self.parse_comma_separated(Parser::parse_expr)?;
2778                self.expect_token(&Token::RParen)?;
2779                result
2780            };
2781            Ok(result)
2782        }
2783    }
2784
2785    /// Parse a `CASE` expression and return an [`Expr::Case`].
2786    pub fn parse_case_expr(&mut self) -> Result<Expr, ParserError> {
2787        let case_token = AttachedToken(self.get_current_token().clone());
2788        let mut operand = None;
2789        if !self.parse_keyword(Keyword::WHEN) {
2790            operand = Some(Box::new(self.parse_expr()?));
2791            self.expect_keyword_is(Keyword::WHEN)?;
2792        }
2793        let mut conditions = vec![];
2794        loop {
2795            let condition = self.parse_expr()?;
2796            self.expect_keyword_is(Keyword::THEN)?;
2797            let result = self.parse_expr()?;
2798            conditions.push(CaseWhen { condition, result });
2799            if !self.parse_keyword(Keyword::WHEN) {
2800                break;
2801            }
2802        }
2803        let else_result = if self.parse_keyword(Keyword::ELSE) {
2804            Some(Box::new(self.parse_expr()?))
2805        } else {
2806            None
2807        };
2808        let end_token = AttachedToken(self.expect_keyword(Keyword::END)?);
2809        Ok(Expr::Case {
2810            case_token,
2811            end_token,
2812            operand,
2813            conditions,
2814            else_result,
2815        })
2816    }
2817
2818    /// Parse an optional `FORMAT` clause for `CAST` expressions.
2819    pub fn parse_optional_cast_format(&mut self) -> Result<Option<CastFormat>, ParserError> {
2820        if self.parse_keyword(Keyword::FORMAT) {
2821            let value = self.parse_value()?;
2822            match self.parse_optional_time_zone()? {
2823                Some(tz) => Ok(Some(CastFormat::ValueAtTimeZone(value, tz))),
2824                None => Ok(Some(CastFormat::Value(value))),
2825            }
2826        } else {
2827            Ok(None)
2828        }
2829    }
2830
2831    /// Parse an optional `AT TIME ZONE` clause.
2832    pub fn parse_optional_time_zone(&mut self) -> Result<Option<ValueWithSpan>, ParserError> {
2833        if self.parse_keywords(&[Keyword::AT, Keyword::TIME, Keyword::ZONE]) {
2834            self.parse_value().map(Some)
2835        } else {
2836            Ok(None)
2837        }
2838    }
2839
2840    /// mssql-like convert function
2841    fn parse_mssql_convert(&mut self, is_try: bool) -> Result<Expr, ParserError> {
2842        self.expect_token(&Token::LParen)?;
2843        let data_type = self.parse_data_type()?;
2844        self.expect_token(&Token::Comma)?;
2845        let expr = self.parse_expr()?;
2846        let styles = if self.consume_token(&Token::Comma) {
2847            self.parse_comma_separated(Parser::parse_expr)?
2848        } else {
2849            Default::default()
2850        };
2851        self.expect_token(&Token::RParen)?;
2852        Ok(Expr::Convert {
2853            is_try,
2854            expr: Box::new(expr),
2855            data_type: Some(data_type),
2856            charset: None,
2857            target_before_value: true,
2858            styles,
2859        })
2860    }
2861
2862    /// Parse a SQL CONVERT function:
2863    ///  - `CONVERT('héhé' USING utf8mb4)` (MySQL)
2864    ///  - `CONVERT('héhé', CHAR CHARACTER SET utf8mb4)` (MySQL)
2865    ///  - `CONVERT(DECIMAL(10, 5), 42)` (MSSQL) - the type comes first
2866    pub fn parse_convert_expr(&mut self, is_try: bool) -> Result<Expr, ParserError> {
2867        if self.dialect.convert_type_before_value() {
2868            return self.parse_mssql_convert(is_try);
2869        }
2870        self.expect_token(&Token::LParen)?;
2871        let expr = self.parse_expr()?;
2872        if self.parse_keyword(Keyword::USING) {
2873            let charset = self.parse_object_name(false)?;
2874            self.expect_token(&Token::RParen)?;
2875            return Ok(Expr::Convert {
2876                is_try,
2877                expr: Box::new(expr),
2878                data_type: None,
2879                charset: Some(charset),
2880                target_before_value: false,
2881                styles: vec![],
2882            });
2883        }
2884        self.expect_token(&Token::Comma)?;
2885        let data_type = self.parse_data_type()?;
2886        let charset = if self.parse_keywords(&[Keyword::CHARACTER, Keyword::SET]) {
2887            Some(self.parse_object_name(false)?)
2888        } else {
2889            None
2890        };
2891        self.expect_token(&Token::RParen)?;
2892        Ok(Expr::Convert {
2893            is_try,
2894            expr: Box::new(expr),
2895            data_type: Some(data_type),
2896            charset,
2897            target_before_value: false,
2898            styles: vec![],
2899        })
2900    }
2901
2902    /// Parse a SQL CAST function e.g. `CAST(expr AS FLOAT)`
2903    pub fn parse_cast_expr(&mut self, kind: CastKind) -> Result<Expr, ParserError> {
2904        self.expect_token(&Token::LParen)?;
2905        let expr = self.parse_expr()?;
2906        self.expect_keyword_is(Keyword::AS)?;
2907        let data_type = self.parse_data_type()?;
2908        let array = self.parse_keyword(Keyword::ARRAY);
2909        let format = self.parse_optional_cast_format()?;
2910        self.expect_token(&Token::RParen)?;
2911        Ok(Expr::Cast {
2912            kind,
2913            expr: Box::new(expr),
2914            data_type,
2915            array,
2916            format,
2917        })
2918    }
2919
2920    /// Parse a SQL EXISTS expression e.g. `WHERE EXISTS(SELECT ...)`.
2921    pub fn parse_exists_expr(&mut self, negated: bool) -> Result<Expr, ParserError> {
2922        self.expect_token(&Token::LParen)?;
2923        let exists_node = Expr::Exists {
2924            negated,
2925            subquery: self.parse_query()?,
2926        };
2927        self.expect_token(&Token::RParen)?;
2928        Ok(exists_node)
2929    }
2930
2931    /// Parse a SQL `EXTRACT` expression e.g. `EXTRACT(YEAR FROM date)`.
2932    pub fn parse_extract_expr(&mut self) -> Result<Expr, ParserError> {
2933        self.expect_token(&Token::LParen)?;
2934        let field = self.parse_date_time_field()?;
2935
2936        let syntax = if self.parse_keyword(Keyword::FROM) {
2937            ExtractSyntax::From
2938        } else if self.dialect.supports_extract_comma_syntax() && self.consume_token(&Token::Comma)
2939        {
2940            ExtractSyntax::Comma
2941        } else {
2942            return Err(ParserError::ParserError(
2943                "Expected 'FROM' or ','".to_string(),
2944            ));
2945        };
2946
2947        let expr = self.parse_expr()?;
2948        self.expect_token(&Token::RParen)?;
2949        Ok(Expr::Extract {
2950            field,
2951            expr: Box::new(expr),
2952            syntax,
2953        })
2954    }
2955
2956    /// Parse a `CEIL` or `FLOOR` expression.
2957    pub fn parse_ceil_floor_expr(&mut self, is_ceil: bool) -> Result<Expr, ParserError> {
2958        self.expect_token(&Token::LParen)?;
2959        let expr = self.parse_expr()?;
2960        // Parse `CEIL/FLOOR(expr)`
2961        let field = if self.parse_keyword(Keyword::TO) {
2962            // Parse `CEIL/FLOOR(expr TO DateTimeField)`
2963            CeilFloorKind::DateTimeField(self.parse_date_time_field()?)
2964        } else if self.consume_token(&Token::Comma) {
2965            // Parse `CEIL/FLOOR(expr, scale)`
2966            let v = self.parse_value()?;
2967            if matches!(v.value, Value::Number(_, _)) {
2968                CeilFloorKind::Scale(v)
2969            } else {
2970                return Err(ParserError::ParserError(
2971                    "Scale field can only be of number type".to_string(),
2972                ));
2973            }
2974        } else {
2975            CeilFloorKind::DateTimeField(DateTimeField::NoDateTime)
2976        };
2977        self.expect_token(&Token::RParen)?;
2978        if is_ceil {
2979            Ok(Expr::Ceil {
2980                expr: Box::new(expr),
2981                field,
2982            })
2983        } else {
2984            Ok(Expr::Floor {
2985                expr: Box::new(expr),
2986                field,
2987            })
2988        }
2989    }
2990
2991    /// Parse a `POSITION` expression.
2992    pub fn parse_position_expr(&mut self, ident: Ident) -> Result<Expr, ParserError> {
2993        let between_prec = self.dialect.prec_value(Precedence::Between);
2994        let position_expr = self.maybe_parse(|p| {
2995            // PARSE SELECT POSITION('@' in field)
2996            p.expect_token(&Token::LParen)?;
2997
2998            // Parse the subexpr till the IN keyword
2999            let expr = p.parse_subexpr(between_prec)?;
3000            p.expect_keyword_is(Keyword::IN)?;
3001            let from = p.parse_expr()?;
3002            p.expect_token(&Token::RParen)?;
3003            Ok(Expr::Position {
3004                expr: Box::new(expr),
3005                r#in: Box::new(from),
3006            })
3007        })?;
3008        match position_expr {
3009            Some(expr) => Ok(expr),
3010            // Snowflake supports `position` as an ordinary function call
3011            // without the special `IN` syntax.
3012            None => self.parse_function(ObjectName::from(vec![ident])),
3013        }
3014    }
3015
3016    /// Parse `SUBSTRING`/`SUBSTR` expressions: `SUBSTRING(expr FROM start FOR length)` or `SUBSTR(expr, start, length)`.
3017    pub fn parse_substring(&mut self) -> Result<Expr, ParserError> {
3018        let shorthand = match self.expect_one_of_keywords(&[Keyword::SUBSTR, Keyword::SUBSTRING])? {
3019            Keyword::SUBSTR => true,
3020            Keyword::SUBSTRING => false,
3021            _ => {
3022                self.prev_token();
3023                return self.expected_ref("SUBSTR or SUBSTRING", self.peek_token_ref());
3024            }
3025        };
3026        self.expect_token(&Token::LParen)?;
3027        let expr = self.parse_expr()?;
3028        let mut from_expr = None;
3029        let special = self.consume_token(&Token::Comma);
3030        if special || self.parse_keyword(Keyword::FROM) {
3031            from_expr = Some(self.parse_expr()?);
3032        }
3033
3034        let mut to_expr = None;
3035        if self.parse_keyword(Keyword::FOR) || self.consume_token(&Token::Comma) {
3036            to_expr = Some(self.parse_expr()?);
3037        }
3038        self.expect_token(&Token::RParen)?;
3039
3040        Ok(Expr::Substring {
3041            expr: Box::new(expr),
3042            substring_from: from_expr.map(Box::new),
3043            substring_for: to_expr.map(Box::new),
3044            special,
3045            shorthand,
3046        })
3047    }
3048
3049    /// Parse an OVERLAY expression.
3050    ///
3051    /// See [Expr::Overlay]
3052    pub fn parse_overlay_expr(&mut self) -> Result<Expr, ParserError> {
3053        // PARSE OVERLAY (EXPR PLACING EXPR FROM 1 [FOR 3])
3054        self.expect_token(&Token::LParen)?;
3055        let expr = self.parse_expr()?;
3056        self.expect_keyword_is(Keyword::PLACING)?;
3057        let what_expr = self.parse_expr()?;
3058        self.expect_keyword_is(Keyword::FROM)?;
3059        let from_expr = self.parse_expr()?;
3060        let mut for_expr = None;
3061        if self.parse_keyword(Keyword::FOR) {
3062            for_expr = Some(self.parse_expr()?);
3063        }
3064        self.expect_token(&Token::RParen)?;
3065
3066        Ok(Expr::Overlay {
3067            expr: Box::new(expr),
3068            overlay_what: Box::new(what_expr),
3069            overlay_from: Box::new(from_expr),
3070            overlay_for: for_expr.map(Box::new),
3071        })
3072    }
3073
3074    /// ```sql
3075    /// TRIM ([WHERE] ['text' FROM] 'text')
3076    /// TRIM ('text')
3077    /// TRIM(<expr>, [, characters]) -- PostgreSQL, DuckDB, Snowflake, BigQuery, Generic
3078    /// ```
3079    pub fn parse_trim_expr(&mut self) -> Result<Expr, ParserError> {
3080        self.expect_token(&Token::LParen)?;
3081        let mut trim_where = None;
3082        if let Token::Word(word) = &self.peek_token_ref().token {
3083            if [Keyword::BOTH, Keyword::LEADING, Keyword::TRAILING].contains(&word.keyword) {
3084                trim_where = Some(self.parse_trim_where()?);
3085            }
3086        }
3087        let expr = self.parse_expr()?;
3088        if self.parse_keyword(Keyword::FROM) {
3089            let trim_what = Box::new(expr);
3090            let expr = self.parse_expr()?;
3091            self.expect_token(&Token::RParen)?;
3092            Ok(Expr::Trim {
3093                expr: Box::new(expr),
3094                trim_where,
3095                trim_what: Some(trim_what),
3096                trim_characters: None,
3097            })
3098        } else if self.dialect.supports_comma_separated_trim() && self.consume_token(&Token::Comma)
3099        {
3100            let characters = self.parse_comma_separated(Parser::parse_expr)?;
3101            self.expect_token(&Token::RParen)?;
3102            Ok(Expr::Trim {
3103                expr: Box::new(expr),
3104                trim_where: None,
3105                trim_what: None,
3106                trim_characters: Some(characters),
3107            })
3108        } else {
3109            self.expect_token(&Token::RParen)?;
3110            Ok(Expr::Trim {
3111                expr: Box::new(expr),
3112                trim_where,
3113                trim_what: None,
3114                trim_characters: None,
3115            })
3116        }
3117    }
3118
3119    /// Parse the `WHERE` field for a `TRIM` expression.
3120    ///
3121    /// See [TrimWhereField]
3122    pub fn parse_trim_where(&mut self) -> Result<TrimWhereField, ParserError> {
3123        let next_token = self.next_token();
3124        match &next_token.token {
3125            Token::Word(w) => match w.keyword {
3126                Keyword::BOTH => Ok(TrimWhereField::Both),
3127                Keyword::LEADING => Ok(TrimWhereField::Leading),
3128                Keyword::TRAILING => Ok(TrimWhereField::Trailing),
3129                _ => self.expected("trim_where field", next_token)?,
3130            },
3131            _ => self.expected("trim_where field", next_token),
3132        }
3133    }
3134
3135    /// Parses an array expression `[ex1, ex2, ..]`
3136    /// if `named` is `true`, came from an expression like  `ARRAY[ex1, ex2]`
3137    pub fn parse_array_expr(&mut self, named: bool) -> Result<Expr, ParserError> {
3138        let exprs = self.parse_comma_separated0(Parser::parse_expr, Token::RBracket)?;
3139        self.expect_token(&Token::RBracket)?;
3140        Ok(Expr::Array(Array { elem: exprs, named }))
3141    }
3142
3143    /// Parse the `ON OVERFLOW` clause for `LISTAGG`.
3144    ///
3145    /// See [`ListAggOnOverflow`]
3146    pub fn parse_listagg_on_overflow(&mut self) -> Result<Option<ListAggOnOverflow>, ParserError> {
3147        if self.parse_keywords(&[Keyword::ON, Keyword::OVERFLOW]) {
3148            if self.parse_keyword(Keyword::ERROR) {
3149                Ok(Some(ListAggOnOverflow::Error))
3150            } else {
3151                self.expect_keyword_is(Keyword::TRUNCATE)?;
3152                let filler = match &self.peek_token_ref().token {
3153                    Token::Word(w)
3154                        if w.keyword == Keyword::WITH || w.keyword == Keyword::WITHOUT =>
3155                    {
3156                        None
3157                    }
3158                    Token::SingleQuotedString(_)
3159                    | Token::EscapedStringLiteral(_)
3160                    | Token::UnicodeStringLiteral(_)
3161                    | Token::NationalStringLiteral(_)
3162                    | Token::QuoteDelimitedStringLiteral(_)
3163                    | Token::NationalQuoteDelimitedStringLiteral(_)
3164                    | Token::HexStringLiteral(_) => Some(Box::new(self.parse_expr()?)),
3165                    _ => self.expected_ref(
3166                        "either filler, WITH, or WITHOUT in LISTAGG",
3167                        self.peek_token_ref(),
3168                    )?,
3169                };
3170                let with_count = self.parse_keyword(Keyword::WITH);
3171                if !with_count && !self.parse_keyword(Keyword::WITHOUT) {
3172                    self.expected_ref("either WITH or WITHOUT in LISTAGG", self.peek_token_ref())?;
3173                }
3174                self.expect_keyword_is(Keyword::COUNT)?;
3175                Ok(Some(ListAggOnOverflow::Truncate { filler, with_count }))
3176            }
3177        } else {
3178            Ok(None)
3179        }
3180    }
3181
3182    /// Parse a date/time field for `EXTRACT`, interval qualifiers, and ceil/floor operations.
3183    ///
3184    /// `EXTRACT` supports a wider set of date/time fields than interval qualifiers,
3185    /// so this function may need to be split in two.
3186    ///
3187    /// See [`DateTimeField`]
3188    pub fn parse_date_time_field(&mut self) -> Result<DateTimeField, ParserError> {
3189        let next_token = self.next_token();
3190        match &next_token.token {
3191            Token::Word(w) => match w.keyword {
3192                Keyword::YEAR => Ok(DateTimeField::Year),
3193                Keyword::YEARS => Ok(DateTimeField::Years),
3194                Keyword::MONTH => Ok(DateTimeField::Month),
3195                Keyword::MONTHS => Ok(DateTimeField::Months),
3196                Keyword::WEEK => {
3197                    let week_day = if dialect_of!(self is BigQueryDialect | GenericDialect)
3198                        && self.consume_token(&Token::LParen)
3199                    {
3200                        let week_day = self.parse_identifier()?;
3201                        self.expect_token(&Token::RParen)?;
3202                        Some(week_day)
3203                    } else {
3204                        None
3205                    };
3206                    Ok(DateTimeField::Week(week_day))
3207                }
3208                Keyword::WEEKS => Ok(DateTimeField::Weeks),
3209                Keyword::DAY => Ok(DateTimeField::Day),
3210                Keyword::DAYOFWEEK => Ok(DateTimeField::DayOfWeek),
3211                Keyword::DAYOFYEAR => Ok(DateTimeField::DayOfYear),
3212                Keyword::DAYS => Ok(DateTimeField::Days),
3213                Keyword::DATE => Ok(DateTimeField::Date),
3214                Keyword::DATETIME => Ok(DateTimeField::Datetime),
3215                Keyword::HOUR => Ok(DateTimeField::Hour),
3216                Keyword::HOURS => Ok(DateTimeField::Hours),
3217                Keyword::MINUTE => Ok(DateTimeField::Minute),
3218                Keyword::MINUTES => Ok(DateTimeField::Minutes),
3219                Keyword::SECOND => Ok(DateTimeField::Second),
3220                Keyword::SECONDS => Ok(DateTimeField::Seconds),
3221                Keyword::CENTURY => Ok(DateTimeField::Century),
3222                Keyword::DECADE => Ok(DateTimeField::Decade),
3223                Keyword::DOY => Ok(DateTimeField::Doy),
3224                Keyword::DOW => Ok(DateTimeField::Dow),
3225                Keyword::EPOCH => Ok(DateTimeField::Epoch),
3226                Keyword::ISODOW => Ok(DateTimeField::Isodow),
3227                Keyword::ISOYEAR => Ok(DateTimeField::Isoyear),
3228                Keyword::ISOWEEK => Ok(DateTimeField::IsoWeek),
3229                Keyword::JULIAN => Ok(DateTimeField::Julian),
3230                Keyword::MICROSECOND => Ok(DateTimeField::Microsecond),
3231                Keyword::MICROSECONDS => Ok(DateTimeField::Microseconds),
3232                Keyword::MILLENIUM => Ok(DateTimeField::Millenium),
3233                Keyword::MILLENNIUM => Ok(DateTimeField::Millennium),
3234                Keyword::MILLISECOND => Ok(DateTimeField::Millisecond),
3235                Keyword::MILLISECONDS => Ok(DateTimeField::Milliseconds),
3236                Keyword::NANOSECOND => Ok(DateTimeField::Nanosecond),
3237                Keyword::NANOSECONDS => Ok(DateTimeField::Nanoseconds),
3238                Keyword::QUARTER => Ok(DateTimeField::Quarter),
3239                Keyword::TIME => Ok(DateTimeField::Time),
3240                Keyword::TIMEZONE => Ok(DateTimeField::Timezone),
3241                Keyword::TIMEZONE_ABBR => Ok(DateTimeField::TimezoneAbbr),
3242                Keyword::TIMEZONE_HOUR => Ok(DateTimeField::TimezoneHour),
3243                Keyword::TIMEZONE_MINUTE => Ok(DateTimeField::TimezoneMinute),
3244                Keyword::TIMEZONE_REGION => Ok(DateTimeField::TimezoneRegion),
3245                _ if self.dialect.allow_extract_custom() => {
3246                    self.prev_token();
3247                    let custom = self.parse_identifier()?;
3248                    Ok(DateTimeField::Custom(custom))
3249                }
3250                _ => self.expected("date/time field", next_token),
3251            },
3252            Token::SingleQuotedString(_) if self.dialect.allow_extract_single_quotes() => {
3253                self.prev_token();
3254                let custom = self.parse_identifier()?;
3255                Ok(DateTimeField::Custom(custom))
3256            }
3257            _ => self.expected("date/time field", next_token),
3258        }
3259    }
3260
3261    /// Parse a `NOT` expression.
3262    ///
3263    /// Represented in the AST as `Expr::UnaryOp` with `UnaryOperator::Not`.
3264    pub fn parse_not(&mut self) -> Result<Expr, ParserError> {
3265        match &self.peek_token_ref().token {
3266            Token::Word(w) => match w.keyword {
3267                Keyword::EXISTS => {
3268                    let negated = true;
3269                    let _ = self.parse_keyword(Keyword::EXISTS);
3270                    self.parse_exists_expr(negated)
3271                }
3272                _ => Ok(Expr::UnaryOp {
3273                    op: UnaryOperator::Not,
3274                    expr: Box::new(
3275                        self.parse_subexpr(self.dialect.prec_value(Precedence::UnaryNot))?,
3276                    ),
3277                }),
3278            },
3279            _ => Ok(Expr::UnaryOp {
3280                op: UnaryOperator::Not,
3281                expr: Box::new(self.parse_subexpr(self.dialect.prec_value(Precedence::UnaryNot))?),
3282            }),
3283        }
3284    }
3285
3286    /// Parse expression types that start with a left brace '{'.
3287    /// Examples:
3288    /// ```sql
3289    /// -- Dictionary expr.
3290    /// {'key1': 'value1', 'key2': 'value2'}
3291    ///
3292    /// -- Function call using the ODBC syntax.
3293    /// { fn CONCAT('foo', 'bar') }
3294    /// ```
3295    fn parse_lbrace_expr(&mut self) -> Result<Expr, ParserError> {
3296        let token = self.expect_token(&Token::LBrace)?;
3297
3298        if let Some(fn_expr) = self.maybe_parse_odbc_body()? {
3299            self.expect_token(&Token::RBrace)?;
3300            return Ok(fn_expr);
3301        }
3302
3303        if self.dialect.supports_dictionary_syntax() {
3304            self.prev_token(); // Put back the '{'
3305            return self.parse_dictionary();
3306        }
3307
3308        self.expected("an expression", token)
3309    }
3310
3311    /// Parses fulltext expressions [`sqlparser::ast::Expr::MatchAgainst`]
3312    ///
3313    /// # Errors
3314    /// This method will raise an error if the column list is empty or with invalid identifiers,
3315    /// the match expression is not a literal string, or if the search modifier is not valid.
3316    pub fn parse_match_against(&mut self) -> Result<Expr, ParserError> {
3317        let columns = self.parse_parenthesized_qualified_column_list(Mandatory, false)?;
3318
3319        self.expect_keyword_is(Keyword::AGAINST)?;
3320
3321        self.expect_token(&Token::LParen)?;
3322
3323        // MySQL is too permissive about the value, IMO we can't validate it perfectly on syntax level.
3324        let match_value = self.parse_value()?;
3325
3326        let in_natural_language_mode_keywords = &[
3327            Keyword::IN,
3328            Keyword::NATURAL,
3329            Keyword::LANGUAGE,
3330            Keyword::MODE,
3331        ];
3332
3333        let with_query_expansion_keywords = &[Keyword::WITH, Keyword::QUERY, Keyword::EXPANSION];
3334
3335        let in_boolean_mode_keywords = &[Keyword::IN, Keyword::BOOLEAN, Keyword::MODE];
3336
3337        let opt_search_modifier = if self.parse_keywords(in_natural_language_mode_keywords) {
3338            if self.parse_keywords(with_query_expansion_keywords) {
3339                Some(SearchModifier::InNaturalLanguageModeWithQueryExpansion)
3340            } else {
3341                Some(SearchModifier::InNaturalLanguageMode)
3342            }
3343        } else if self.parse_keywords(in_boolean_mode_keywords) {
3344            Some(SearchModifier::InBooleanMode)
3345        } else if self.parse_keywords(with_query_expansion_keywords) {
3346            Some(SearchModifier::WithQueryExpansion)
3347        } else {
3348            None
3349        };
3350
3351        self.expect_token(&Token::RParen)?;
3352
3353        Ok(Expr::MatchAgainst {
3354            columns,
3355            match_value,
3356            opt_search_modifier,
3357        })
3358    }
3359
3360    /// Parse an `INTERVAL` expression.
3361    ///
3362    /// Some syntactically valid intervals:
3363    ///
3364    /// ```sql
3365    ///   1. INTERVAL '1' DAY
3366    ///   2. INTERVAL '1-1' YEAR TO MONTH
3367    ///   3. INTERVAL '1' SECOND
3368    ///   4. INTERVAL '1:1:1.1' HOUR (5) TO SECOND (5)
3369    ///   5. INTERVAL '1.1' SECOND (2, 2)
3370    ///   6. INTERVAL '1:1' HOUR (5) TO MINUTE (5)
3371    ///   7. (MySql & BigQuery only): INTERVAL 1 DAY
3372    /// ```
3373    ///
3374    /// Note that we do not currently attempt to parse the quoted value.
3375    pub fn parse_interval(&mut self) -> Result<Expr, ParserError> {
3376        // The SQL standard allows an optional sign before the value string, but
3377        // it is not clear if any implementations support that syntax, so we
3378        // don't currently try to parse it. (The sign can instead be included
3379        // inside the value string.)
3380
3381        // to match the different flavours of INTERVAL syntax, we only allow expressions
3382        // if the dialect requires an interval qualifier,
3383        // see https://github.com/sqlparser-rs/sqlparser-rs/pull/1398 for more details
3384        let value = if self.dialect.require_interval_qualifier() {
3385            // parse a whole expression so `INTERVAL 1 + 1 DAY` is valid
3386            self.parse_expr()?
3387        } else {
3388            // parse a prefix expression so `INTERVAL 1 DAY` is valid, but `INTERVAL 1 + 1 DAY` is not
3389            // this also means that `INTERVAL '5 days' > INTERVAL '1 day'` treated properly
3390            self.parse_prefix()?
3391        };
3392
3393        // Following the string literal is a qualifier which indicates the units
3394        // of the duration specified in the string literal.
3395        //
3396        // Note that PostgreSQL allows omitting the qualifier, so we provide
3397        // this more general implementation.
3398        let leading_field = if self.next_token_is_temporal_unit() {
3399            Some(self.parse_date_time_field()?)
3400        } else if self.dialect.require_interval_qualifier() {
3401            return parser_err!(
3402                "INTERVAL requires a unit after the literal value",
3403                self.peek_token_ref().span.start
3404            );
3405        } else {
3406            None
3407        };
3408
3409        let (leading_precision, last_field, fsec_precision) =
3410            if leading_field == Some(DateTimeField::Second) {
3411                // SQL mandates special syntax for `SECOND TO SECOND` literals.
3412                // Instead of
3413                //     `SECOND [(<leading precision>)] TO SECOND[(<fractional seconds precision>)]`
3414                // one must use the special format:
3415                //     `SECOND [( <leading precision> [ , <fractional seconds precision>] )]`
3416                let last_field = None;
3417                let (leading_precision, fsec_precision) = self.parse_optional_precision_scale()?;
3418                (leading_precision, last_field, fsec_precision)
3419            } else {
3420                let leading_precision = self.parse_optional_precision()?;
3421                if self.parse_keyword(Keyword::TO) {
3422                    let last_field = Some(self.parse_date_time_field()?);
3423                    let fsec_precision = if last_field == Some(DateTimeField::Second) {
3424                        self.parse_optional_precision()?
3425                    } else {
3426                        None
3427                    };
3428                    (leading_precision, last_field, fsec_precision)
3429                } else {
3430                    (leading_precision, None, None)
3431                }
3432            };
3433
3434        Ok(Expr::Interval(Interval {
3435            value: Box::new(value),
3436            leading_field,
3437            leading_precision,
3438            last_field,
3439            fractional_seconds_precision: fsec_precision,
3440        }))
3441    }
3442
3443    /// Peek at the next token and determine if it is a temporal unit
3444    /// like `second`.
3445    pub fn next_token_is_temporal_unit(&mut self) -> bool {
3446        if let Token::Word(word) = &self.peek_token_ref().token {
3447            matches!(
3448                word.keyword,
3449                Keyword::YEAR
3450                    | Keyword::YEARS
3451                    | Keyword::MONTH
3452                    | Keyword::MONTHS
3453                    | Keyword::WEEK
3454                    | Keyword::WEEKS
3455                    | Keyword::DAY
3456                    | Keyword::DAYS
3457                    | Keyword::HOUR
3458                    | Keyword::HOURS
3459                    | Keyword::MINUTE
3460                    | Keyword::MINUTES
3461                    | Keyword::SECOND
3462                    | Keyword::SECONDS
3463                    | Keyword::CENTURY
3464                    | Keyword::DECADE
3465                    | Keyword::DOW
3466                    | Keyword::DOY
3467                    | Keyword::EPOCH
3468                    | Keyword::ISODOW
3469                    | Keyword::ISOYEAR
3470                    | Keyword::JULIAN
3471                    | Keyword::MICROSECOND
3472                    | Keyword::MICROSECONDS
3473                    | Keyword::MILLENIUM
3474                    | Keyword::MILLENNIUM
3475                    | Keyword::MILLISECOND
3476                    | Keyword::MILLISECONDS
3477                    | Keyword::NANOSECOND
3478                    | Keyword::NANOSECONDS
3479                    | Keyword::QUARTER
3480                    | Keyword::TIMEZONE
3481                    | Keyword::TIMEZONE_HOUR
3482                    | Keyword::TIMEZONE_MINUTE
3483            )
3484        } else {
3485            false
3486        }
3487    }
3488
3489    /// Syntax
3490    /// ```sql
3491    /// -- typed
3492    /// STRUCT<[field_name] field_type, ...>( expr1 [, ... ])
3493    /// -- typeless
3494    /// STRUCT( expr1 [AS field_name] [, ... ])
3495    /// ```
3496    fn parse_struct_literal(&mut self) -> Result<Expr, ParserError> {
3497        // Parse the fields definition if exist `<[field_name] field_type, ...>`
3498        self.prev_token();
3499        let (fields, trailing_bracket) =
3500            self.parse_struct_type_def(Self::parse_struct_field_def)?;
3501        if trailing_bracket.0 {
3502            return parser_err!(
3503                "unmatched > in STRUCT literal",
3504                self.peek_token_ref().span.start
3505            );
3506        }
3507
3508        // Parse the struct values `(expr1 [, ... ])`
3509        self.expect_token(&Token::LParen)?;
3510        let values = self
3511            .parse_comma_separated(|parser| parser.parse_struct_field_expr(!fields.is_empty()))?;
3512        self.expect_token(&Token::RParen)?;
3513
3514        Ok(Expr::Struct { values, fields })
3515    }
3516
3517    /// Parse an expression value for a struct literal
3518    /// Syntax
3519    /// ```sql
3520    /// expr [AS name]
3521    /// ```
3522    ///
3523    /// For biquery [1], Parameter typed_syntax is set to true if the expression
3524    /// is to be parsed as a field expression declared using typed
3525    /// struct syntax [2], and false if using typeless struct syntax [3].
3526    ///
3527    /// [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#constructing_a_struct
3528    /// [2]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#typed_struct_syntax
3529    /// [3]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#typeless_struct_syntax
3530    fn parse_struct_field_expr(&mut self, typed_syntax: bool) -> Result<Expr, ParserError> {
3531        let expr = self.parse_expr()?;
3532        if self.parse_keyword(Keyword::AS) {
3533            if typed_syntax {
3534                return parser_err!("Typed syntax does not allow AS", {
3535                    self.prev_token();
3536                    self.peek_token_ref().span.start
3537                });
3538            }
3539            let field_name = self.parse_identifier()?;
3540            Ok(Expr::Named {
3541                expr: expr.into(),
3542                name: field_name,
3543            })
3544        } else {
3545            Ok(expr)
3546        }
3547    }
3548
3549    /// Parse a Struct type definition as a sequence of field-value pairs.
3550    /// The syntax of the Struct elem differs by dialect so it is customised
3551    /// by the `elem_parser` argument.
3552    ///
3553    /// Syntax
3554    /// ```sql
3555    /// Hive:
3556    /// STRUCT<field_name: field_type>
3557    ///
3558    /// BigQuery:
3559    /// STRUCT<[field_name] field_type>
3560    /// ```
3561    fn parse_struct_type_def<F>(
3562        &mut self,
3563        mut elem_parser: F,
3564    ) -> Result<(Vec<StructField>, MatchedTrailingBracket), ParserError>
3565    where
3566        F: FnMut(&mut Parser<'a>) -> Result<(StructField, MatchedTrailingBracket), ParserError>,
3567    {
3568        self.expect_keyword_is(Keyword::STRUCT)?;
3569
3570        // Nothing to do if we have no type information.
3571        if self.peek_token_ref().token != Token::Lt {
3572            return Ok((Default::default(), false.into()));
3573        }
3574        self.next_token();
3575
3576        let mut field_defs = vec![];
3577        let trailing_bracket = loop {
3578            let (def, trailing_bracket) = elem_parser(self)?;
3579            field_defs.push(def);
3580            // The struct field definition is finished if it occurs `>>` or comma.
3581            if trailing_bracket.0 || !self.consume_token(&Token::Comma) {
3582                break trailing_bracket;
3583            }
3584        };
3585
3586        Ok((
3587            field_defs,
3588            self.expect_closing_angle_bracket(trailing_bracket)?,
3589        ))
3590    }
3591
3592    /// Duckdb Struct Data Type <https://duckdb.org/docs/sql/data_types/struct.html#retrieving-from-structs>
3593    fn parse_duckdb_struct_type_def(&mut self) -> Result<Vec<StructField>, ParserError> {
3594        self.expect_keyword_is(Keyword::STRUCT)?;
3595        self.expect_token(&Token::LParen)?;
3596        let struct_body = self.parse_comma_separated(|parser| {
3597            let field_name = parser.parse_identifier()?;
3598            let field_type = parser.parse_data_type()?;
3599
3600            Ok(StructField {
3601                field_name: Some(field_name),
3602                field_type,
3603                options: None,
3604            })
3605        });
3606        self.expect_token(&Token::RParen)?;
3607        struct_body
3608    }
3609
3610    /// Parse a field definition in a [struct] or [tuple].
3611    /// Syntax:
3612    ///
3613    /// ```sql
3614    /// [field_name] field_type
3615    /// field_name: field_type
3616    /// ```
3617    ///
3618    /// [struct]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#declaring_a_struct_type
3619    /// [tuple]: https://clickhouse.com/docs/en/sql-reference/data-types/tuple
3620    /// [databricks]: https://docs.databricks.com/en/sql/language-manual/data-types/struct-type.html
3621    fn parse_struct_field_def(
3622        &mut self,
3623    ) -> Result<(StructField, MatchedTrailingBracket), ParserError> {
3624        // Look beyond the next item to infer whether both field name
3625        // and type are specified.
3626        let is_named_field = matches!(
3627            (self.peek_nth_token(0).token, self.peek_nth_token(1).token),
3628            (Token::Word(_), Token::Word(_)) | (Token::Word(_), Token::Colon)
3629        );
3630
3631        let field_name = if is_named_field {
3632            let name = self.parse_identifier()?;
3633            let _ = self.consume_token(&Token::Colon);
3634            Some(name)
3635        } else {
3636            None
3637        };
3638
3639        let (field_type, trailing_bracket) = self.parse_data_type_helper()?;
3640
3641        let options = self.maybe_parse_options(Keyword::OPTIONS)?;
3642        Ok((
3643            StructField {
3644                field_name,
3645                field_type,
3646                options,
3647            },
3648            trailing_bracket,
3649        ))
3650    }
3651
3652    /// DuckDB specific: Parse a Union type definition as a sequence of field-value pairs.
3653    ///
3654    /// Syntax:
3655    ///
3656    /// ```sql
3657    /// UNION(field_name field_type[,...])
3658    /// ```
3659    ///
3660    /// [1]: https://duckdb.org/docs/sql/data_types/union.html
3661    fn parse_union_type_def(&mut self) -> Result<Vec<UnionField>, ParserError> {
3662        self.expect_keyword_is(Keyword::UNION)?;
3663
3664        self.expect_token(&Token::LParen)?;
3665
3666        let fields = self.parse_comma_separated(|p| {
3667            Ok(UnionField {
3668                field_name: p.parse_identifier()?,
3669                field_type: p.parse_data_type()?,
3670            })
3671        })?;
3672
3673        self.expect_token(&Token::RParen)?;
3674
3675        Ok(fields)
3676    }
3677
3678    /// DuckDB and ClickHouse specific: Parse a duckdb [dictionary] or a clickhouse [map] setting
3679    ///
3680    /// Syntax:
3681    ///
3682    /// ```sql
3683    /// {'field_name': expr1[, ... ]}
3684    /// ```
3685    ///
3686    /// [dictionary]: https://duckdb.org/docs/sql/data_types/struct#creating-structs
3687    /// [map]: https://clickhouse.com/docs/operations/settings/settings#additional_table_filters
3688    fn parse_dictionary(&mut self) -> Result<Expr, ParserError> {
3689        self.expect_token(&Token::LBrace)?;
3690
3691        let fields = self.parse_comma_separated0(Self::parse_dictionary_field, Token::RBrace)?;
3692
3693        self.expect_token(&Token::RBrace)?;
3694
3695        Ok(Expr::Dictionary(fields))
3696    }
3697
3698    /// Parse a field for a duckdb [dictionary] or a clickhouse [map] setting
3699    ///
3700    /// Syntax
3701    ///
3702    /// ```sql
3703    /// 'name': expr
3704    /// ```
3705    ///
3706    /// [dictionary]: https://duckdb.org/docs/sql/data_types/struct#creating-structs
3707    /// [map]: https://clickhouse.com/docs/operations/settings/settings#additional_table_filters
3708    fn parse_dictionary_field(&mut self) -> Result<DictionaryField, ParserError> {
3709        let key = self.parse_identifier()?;
3710
3711        self.expect_token(&Token::Colon)?;
3712
3713        let expr = self.parse_expr()?;
3714
3715        Ok(DictionaryField {
3716            key,
3717            value: Box::new(expr),
3718        })
3719    }
3720
3721    /// DuckDB specific: Parse a duckdb [map]
3722    ///
3723    /// Syntax:
3724    ///
3725    /// ```sql
3726    /// Map {key1: value1[, ... ]}
3727    /// ```
3728    ///
3729    /// [map]: https://duckdb.org/docs/sql/data_types/map.html#creating-maps
3730    fn parse_duckdb_map_literal(&mut self) -> Result<Expr, ParserError> {
3731        self.expect_token(&Token::LBrace)?;
3732        let fields = self.parse_comma_separated0(Self::parse_duckdb_map_field, Token::RBrace)?;
3733        self.expect_token(&Token::RBrace)?;
3734        Ok(Expr::Map(Map { entries: fields }))
3735    }
3736
3737    /// Parse a field for a duckdb [map]
3738    ///
3739    /// Syntax
3740    ///
3741    /// ```sql
3742    /// key: value
3743    /// ```
3744    ///
3745    /// [map]: https://duckdb.org/docs/sql/data_types/map.html#creating-maps
3746    fn parse_duckdb_map_field(&mut self) -> Result<MapEntry, ParserError> {
3747        // Stop before `:` so it can act as a key/value separator
3748        let key = self.parse_subexpr(self.dialect.prec_value(Precedence::Colon))?;
3749
3750        self.expect_token(&Token::Colon)?;
3751
3752        let value = self.parse_expr()?;
3753
3754        Ok(MapEntry {
3755            key: Box::new(key),
3756            value: Box::new(value),
3757        })
3758    }
3759
3760    /// Parse clickhouse [map]
3761    ///
3762    /// Syntax
3763    ///
3764    /// ```sql
3765    /// Map(key_data_type, value_data_type)
3766    /// ```
3767    ///
3768    /// [map]: https://clickhouse.com/docs/en/sql-reference/data-types/map
3769    fn parse_click_house_map_def(&mut self) -> Result<(DataType, DataType), ParserError> {
3770        self.expect_keyword_is(Keyword::MAP)?;
3771        self.expect_token(&Token::LParen)?;
3772        let key_data_type = self.parse_data_type()?;
3773        self.expect_token(&Token::Comma)?;
3774        let value_data_type = self.parse_data_type()?;
3775        self.expect_token(&Token::RParen)?;
3776
3777        Ok((key_data_type, value_data_type))
3778    }
3779
3780    /// Parse clickhouse [tuple]
3781    ///
3782    /// Syntax
3783    ///
3784    /// ```sql
3785    /// Tuple([field_name] field_type, ...)
3786    /// ```
3787    ///
3788    /// [tuple]: https://clickhouse.com/docs/en/sql-reference/data-types/tuple
3789    fn parse_click_house_tuple_def(&mut self) -> Result<Vec<StructField>, ParserError> {
3790        self.expect_keyword_is(Keyword::TUPLE)?;
3791        self.expect_token(&Token::LParen)?;
3792        let mut field_defs = vec![];
3793        loop {
3794            let (def, _) = self.parse_struct_field_def()?;
3795            field_defs.push(def);
3796            if !self.consume_token(&Token::Comma) {
3797                break;
3798            }
3799        }
3800        self.expect_token(&Token::RParen)?;
3801
3802        Ok(field_defs)
3803    }
3804
3805    /// For nested types that use the angle bracket syntax, this matches either
3806    /// `>`, `>>` or nothing depending on which variant is expected (specified by the previously
3807    /// matched `trailing_bracket` argument). It returns whether there is a trailing
3808    /// left to be matched - (i.e. if '>>' was matched).
3809    fn expect_closing_angle_bracket(
3810        &mut self,
3811        trailing_bracket: MatchedTrailingBracket,
3812    ) -> Result<MatchedTrailingBracket, ParserError> {
3813        let trailing_bracket = if !trailing_bracket.0 {
3814            match &self.peek_token_ref().token {
3815                Token::Gt => {
3816                    self.next_token();
3817                    false.into()
3818                }
3819                Token::ShiftRight => {
3820                    self.next_token();
3821                    true.into()
3822                }
3823                _ => return self.expected_ref(">", self.peek_token_ref()),
3824            }
3825        } else {
3826            false.into()
3827        };
3828
3829        Ok(trailing_bracket)
3830    }
3831
3832    /// Parse an operator following an expression
3833    pub fn parse_infix(&mut self, expr: Expr, precedence: u8) -> Result<Expr, ParserError> {
3834        // allow the dialect to override infix parsing
3835        if let Some(infix) = self.dialect.parse_infix(self, &expr, precedence) {
3836            return infix;
3837        }
3838
3839        let dialect = self.dialect;
3840
3841        self.advance_token();
3842        let tok = self.get_current_token();
3843        debug!("infix: {tok:?}");
3844        let tok_index = self.get_current_index();
3845        let span = tok.span;
3846        let regular_binary_operator = match &tok.token {
3847            Token::Spaceship => Some(BinaryOperator::Spaceship),
3848            Token::DoubleEq => Some(BinaryOperator::Eq),
3849            Token::Assignment => Some(BinaryOperator::Assignment),
3850            Token::Eq => Some(BinaryOperator::Eq),
3851            Token::Neq => Some(BinaryOperator::NotEq),
3852            Token::Gt => Some(BinaryOperator::Gt),
3853            Token::GtEq => Some(BinaryOperator::GtEq),
3854            Token::Lt => Some(BinaryOperator::Lt),
3855            Token::LtEq => Some(BinaryOperator::LtEq),
3856            Token::Plus => Some(BinaryOperator::Plus),
3857            Token::Minus => Some(BinaryOperator::Minus),
3858            Token::Mul => Some(BinaryOperator::Multiply),
3859            Token::Mod => Some(BinaryOperator::Modulo),
3860            Token::StringConcat => Some(BinaryOperator::StringConcat),
3861            Token::Pipe => Some(BinaryOperator::BitwiseOr),
3862            Token::Caret => {
3863                // In PostgreSQL, ^ stands for the exponentiation operation,
3864                // and # stands for XOR. See https://www.postgresql.org/docs/current/functions-math.html
3865                if dialect_is!(dialect is PostgreSqlDialect) {
3866                    Some(BinaryOperator::PGExp)
3867                } else {
3868                    Some(BinaryOperator::BitwiseXor)
3869                }
3870            }
3871            Token::Ampersand => Some(BinaryOperator::BitwiseAnd),
3872            Token::Div => Some(BinaryOperator::Divide),
3873            Token::DuckIntDiv if dialect_is!(dialect is DuckDbDialect | GenericDialect) => {
3874                Some(BinaryOperator::DuckIntegerDivide)
3875            }
3876            Token::ShiftLeft if dialect.supports_bitwise_shift_operators() => {
3877                Some(BinaryOperator::PGBitwiseShiftLeft)
3878            }
3879            Token::ShiftRight if dialect.supports_bitwise_shift_operators() => {
3880                Some(BinaryOperator::PGBitwiseShiftRight)
3881            }
3882            Token::Sharp if dialect_is!(dialect is PostgreSqlDialect | RedshiftSqlDialect) => {
3883                Some(BinaryOperator::PGBitwiseXor)
3884            }
3885            Token::Overlap if dialect_is!(dialect is PostgreSqlDialect | RedshiftSqlDialect) => {
3886                Some(BinaryOperator::PGOverlap)
3887            }
3888            Token::Overlap if dialect_is!(dialect is PostgreSqlDialect | GenericDialect) => {
3889                Some(BinaryOperator::PGOverlap)
3890            }
3891            Token::Overlap if dialect.supports_double_ampersand_operator() => {
3892                Some(BinaryOperator::And)
3893            }
3894            Token::CaretAt if dialect_is!(dialect is PostgreSqlDialect | GenericDialect) => {
3895                Some(BinaryOperator::PGStartsWith)
3896            }
3897            Token::Tilde => Some(BinaryOperator::PGRegexMatch),
3898            Token::TildeAsterisk => Some(BinaryOperator::PGRegexIMatch),
3899            Token::ExclamationMarkTilde => Some(BinaryOperator::PGRegexNotMatch),
3900            Token::ExclamationMarkTildeAsterisk => Some(BinaryOperator::PGRegexNotIMatch),
3901            Token::DoubleTilde => Some(BinaryOperator::PGLikeMatch),
3902            Token::DoubleTildeAsterisk => Some(BinaryOperator::PGILikeMatch),
3903            Token::ExclamationMarkDoubleTilde => Some(BinaryOperator::PGNotLikeMatch),
3904            Token::ExclamationMarkDoubleTildeAsterisk => Some(BinaryOperator::PGNotILikeMatch),
3905            Token::Arrow => Some(BinaryOperator::Arrow),
3906            Token::LongArrow => Some(BinaryOperator::LongArrow),
3907            Token::HashArrow => Some(BinaryOperator::HashArrow),
3908            Token::HashLongArrow => Some(BinaryOperator::HashLongArrow),
3909            Token::AtArrow => Some(BinaryOperator::AtArrow),
3910            Token::ArrowAt => Some(BinaryOperator::ArrowAt),
3911            Token::HashMinus => Some(BinaryOperator::HashMinus),
3912            Token::AtQuestion => Some(BinaryOperator::AtQuestion),
3913            Token::AtAt => Some(BinaryOperator::AtAt),
3914            Token::Question => Some(BinaryOperator::Question),
3915            Token::QuestionAnd => Some(BinaryOperator::QuestionAnd),
3916            Token::QuestionPipe => Some(BinaryOperator::QuestionPipe),
3917            Token::CustomBinaryOperator(s) => Some(BinaryOperator::Custom(s.clone())),
3918            Token::DoubleSharp if self.dialect.supports_geometric_types() => {
3919                Some(BinaryOperator::DoubleHash)
3920            }
3921
3922            Token::AmpersandLeftAngleBracket if self.dialect.supports_geometric_types() => {
3923                Some(BinaryOperator::AndLt)
3924            }
3925            Token::AmpersandRightAngleBracket if self.dialect.supports_geometric_types() => {
3926                Some(BinaryOperator::AndGt)
3927            }
3928            Token::QuestionMarkDash if self.dialect.supports_geometric_types() => {
3929                Some(BinaryOperator::QuestionDash)
3930            }
3931            Token::AmpersandLeftAngleBracketVerticalBar
3932                if self.dialect.supports_geometric_types() =>
3933            {
3934                Some(BinaryOperator::AndLtPipe)
3935            }
3936            Token::VerticalBarAmpersandRightAngleBracket
3937                if self.dialect.supports_geometric_types() =>
3938            {
3939                Some(BinaryOperator::PipeAndGt)
3940            }
3941            Token::TwoWayArrow if self.dialect.supports_geometric_types() => {
3942                Some(BinaryOperator::LtDashGt)
3943            }
3944            Token::LeftAngleBracketCaret if self.dialect.supports_geometric_types() => {
3945                Some(BinaryOperator::LtCaret)
3946            }
3947            Token::RightAngleBracketCaret if self.dialect.supports_geometric_types() => {
3948                Some(BinaryOperator::GtCaret)
3949            }
3950            Token::QuestionMarkSharp if self.dialect.supports_geometric_types() => {
3951                Some(BinaryOperator::QuestionHash)
3952            }
3953            Token::QuestionMarkDoubleVerticalBar if self.dialect.supports_geometric_types() => {
3954                Some(BinaryOperator::QuestionDoublePipe)
3955            }
3956            Token::QuestionMarkDashVerticalBar if self.dialect.supports_geometric_types() => {
3957                Some(BinaryOperator::QuestionDashPipe)
3958            }
3959            Token::TildeEqual if self.dialect.supports_geometric_types() => {
3960                Some(BinaryOperator::TildeEq)
3961            }
3962            Token::ShiftLeftVerticalBar if self.dialect.supports_geometric_types() => {
3963                Some(BinaryOperator::LtLtPipe)
3964            }
3965            Token::VerticalBarShiftRight if self.dialect.supports_geometric_types() => {
3966                Some(BinaryOperator::PipeGtGt)
3967            }
3968            Token::AtSign if self.dialect.supports_geometric_types() => Some(BinaryOperator::At),
3969
3970            Token::Word(w) => match w.keyword {
3971                Keyword::AND => Some(BinaryOperator::And),
3972                Keyword::OR => Some(BinaryOperator::Or),
3973                Keyword::XOR => Some(BinaryOperator::Xor),
3974                Keyword::OVERLAPS => Some(BinaryOperator::Overlaps),
3975                Keyword::OPERATOR if dialect_is!(dialect is PostgreSqlDialect | GenericDialect) => {
3976                    // there are special rules for operator names in
3977                    // postgres so we can not use 'parse_object'
3978                    // or similar.
3979                    // See https://www.postgresql.org/docs/current/sql-createoperator.html
3980                    Some(BinaryOperator::PGCustomBinaryOperator(
3981                        self.parse_pg_operator_ident_parts()?,
3982                    ))
3983                }
3984                _ => None,
3985            },
3986            _ => None,
3987        };
3988
3989        let tok = self.token_at(tok_index);
3990        if let Some(op) = regular_binary_operator {
3991            if let Some(keyword) =
3992                self.parse_one_of_keywords(&[Keyword::ANY, Keyword::ALL, Keyword::SOME])
3993            {
3994                self.expect_token(&Token::LParen)?;
3995                let right = if self.peek_sub_query() {
3996                    // We have a subquery ahead (SELECT\WITH ...) need to rewind and
3997                    // use the parenthesis for parsing the subquery as an expression.
3998                    self.prev_token(); // LParen
3999                    self.parse_subexpr(precedence)?
4000                } else {
4001                    // Non-subquery expression
4002                    let right = self.parse_subexpr(precedence)?;
4003                    self.expect_token(&Token::RParen)?;
4004                    right
4005                };
4006
4007                if !matches!(
4008                    op,
4009                    BinaryOperator::Gt
4010                        | BinaryOperator::Lt
4011                        | BinaryOperator::GtEq
4012                        | BinaryOperator::LtEq
4013                        | BinaryOperator::Eq
4014                        | BinaryOperator::NotEq
4015                        | BinaryOperator::PGRegexMatch
4016                        | BinaryOperator::PGRegexIMatch
4017                        | BinaryOperator::PGRegexNotMatch
4018                        | BinaryOperator::PGRegexNotIMatch
4019                        | BinaryOperator::PGLikeMatch
4020                        | BinaryOperator::PGILikeMatch
4021                        | BinaryOperator::PGNotLikeMatch
4022                        | BinaryOperator::PGNotILikeMatch
4023                ) {
4024                    return parser_err!(
4025                        format!(
4026                        "Expected one of [=, >, <, =>, =<, !=, ~, ~*, !~, !~*, ~~, ~~*, !~~, !~~*] as comparison operator, found: {op}"
4027                    ),
4028                        span.start
4029                    );
4030                };
4031
4032                Ok(match keyword {
4033                    Keyword::ALL => Expr::AllOp {
4034                        left: Box::new(expr),
4035                        compare_op: op,
4036                        right: Box::new(right),
4037                    },
4038                    Keyword::ANY | Keyword::SOME => Expr::AnyOp {
4039                        left: Box::new(expr),
4040                        compare_op: op,
4041                        right: Box::new(right),
4042                        is_some: keyword == Keyword::SOME,
4043                    },
4044                    unexpected_keyword => return Err(ParserError::ParserError(
4045                        format!("Internal parser error: expected any of {{ALL, ANY, SOME}}, got {unexpected_keyword:?}"),
4046                    )),
4047                })
4048            } else {
4049                Ok(Expr::BinaryOp {
4050                    left: Box::new(expr),
4051                    op,
4052                    right: Box::new(self.parse_subexpr(precedence)?),
4053                })
4054            }
4055        } else if let Token::Word(w) = &tok.token {
4056            match w.keyword {
4057                Keyword::IS => {
4058                    if self.parse_keyword(Keyword::NULL) {
4059                        Ok(Expr::IsNull(Box::new(expr)))
4060                    } else if self.parse_keywords(&[Keyword::NOT, Keyword::NULL]) {
4061                        Ok(Expr::IsNotNull(Box::new(expr)))
4062                    } else if self.parse_keywords(&[Keyword::TRUE]) {
4063                        Ok(Expr::IsTrue(Box::new(expr)))
4064                    } else if self.parse_keywords(&[Keyword::NOT, Keyword::TRUE]) {
4065                        Ok(Expr::IsNotTrue(Box::new(expr)))
4066                    } else if self.parse_keywords(&[Keyword::FALSE]) {
4067                        Ok(Expr::IsFalse(Box::new(expr)))
4068                    } else if self.parse_keywords(&[Keyword::NOT, Keyword::FALSE]) {
4069                        Ok(Expr::IsNotFalse(Box::new(expr)))
4070                    } else if self.parse_keywords(&[Keyword::UNKNOWN]) {
4071                        Ok(Expr::IsUnknown(Box::new(expr)))
4072                    } else if self.parse_keywords(&[Keyword::NOT, Keyword::UNKNOWN]) {
4073                        Ok(Expr::IsNotUnknown(Box::new(expr)))
4074                    } else if self.parse_keywords(&[Keyword::DISTINCT, Keyword::FROM]) {
4075                        let expr2 = self.parse_expr()?;
4076                        Ok(Expr::IsDistinctFrom(Box::new(expr), Box::new(expr2)))
4077                    } else if self.parse_keywords(&[Keyword::NOT, Keyword::DISTINCT, Keyword::FROM])
4078                    {
4079                        let expr2 = self.parse_expr()?;
4080                        Ok(Expr::IsNotDistinctFrom(Box::new(expr), Box::new(expr2)))
4081                    } else if let Ok(is_normalized) = self.parse_unicode_is_normalized(expr) {
4082                        Ok(is_normalized)
4083                    } else {
4084                        self.expected_ref(
4085                            "[NOT] NULL | TRUE | FALSE | DISTINCT | [form] NORMALIZED FROM after IS",
4086                            self.peek_token_ref(),
4087                        )
4088                    }
4089                }
4090                Keyword::AT => {
4091                    self.expect_keywords(&[Keyword::TIME, Keyword::ZONE])?;
4092                    Ok(Expr::AtTimeZone {
4093                        timestamp: Box::new(expr),
4094                        time_zone: Box::new(self.parse_subexpr(precedence)?),
4095                    })
4096                }
4097                Keyword::NOT
4098                | Keyword::IN
4099                | Keyword::BETWEEN
4100                | Keyword::LIKE
4101                | Keyword::ILIKE
4102                | Keyword::SIMILAR
4103                | Keyword::REGEXP
4104                | Keyword::RLIKE => {
4105                    self.prev_token();
4106                    let negated = self.parse_keyword(Keyword::NOT);
4107                    let regexp = self.parse_keyword(Keyword::REGEXP);
4108                    let rlike = self.parse_keyword(Keyword::RLIKE);
4109                    let null = if !self.in_column_definition_state() {
4110                        self.parse_keyword(Keyword::NULL)
4111                    } else {
4112                        false
4113                    };
4114                    if regexp || rlike {
4115                        Ok(Expr::RLike {
4116                            negated,
4117                            expr: Box::new(expr),
4118                            pattern: Box::new(
4119                                self.parse_subexpr(self.dialect.prec_value(Precedence::Like))?,
4120                            ),
4121                            regexp,
4122                        })
4123                    } else if negated && null {
4124                        Ok(Expr::IsNotNull(Box::new(expr)))
4125                    } else if self.parse_keyword(Keyword::IN) {
4126                        self.parse_in(expr, negated)
4127                    } else if self.parse_keyword(Keyword::BETWEEN) {
4128                        self.parse_between(expr, negated)
4129                    } else if self.parse_keyword(Keyword::LIKE) {
4130                        Ok(Expr::Like {
4131                            negated,
4132                            any: self.parse_keyword(Keyword::ANY),
4133                            expr: Box::new(expr),
4134                            pattern: Box::new(
4135                                self.parse_subexpr(self.dialect.prec_value(Precedence::Like))?,
4136                            ),
4137                            escape_char: self.parse_escape_char()?,
4138                        })
4139                    } else if self.parse_keyword(Keyword::ILIKE) {
4140                        Ok(Expr::ILike {
4141                            negated,
4142                            any: self.parse_keyword(Keyword::ANY),
4143                            expr: Box::new(expr),
4144                            pattern: Box::new(
4145                                self.parse_subexpr(self.dialect.prec_value(Precedence::Like))?,
4146                            ),
4147                            escape_char: self.parse_escape_char()?,
4148                        })
4149                    } else if self.parse_keywords(&[Keyword::SIMILAR, Keyword::TO]) {
4150                        Ok(Expr::SimilarTo {
4151                            negated,
4152                            expr: Box::new(expr),
4153                            pattern: Box::new(
4154                                self.parse_subexpr(self.dialect.prec_value(Precedence::Like))?,
4155                            ),
4156                            escape_char: self.parse_escape_char()?,
4157                        })
4158                    } else {
4159                        self.expected_ref("IN or BETWEEN after NOT", self.peek_token_ref())
4160                    }
4161                }
4162                Keyword::NOTNULL if dialect.supports_notnull_operator() => {
4163                    Ok(Expr::IsNotNull(Box::new(expr)))
4164                }
4165                Keyword::MEMBER => {
4166                    if self.parse_keyword(Keyword::OF) {
4167                        self.expect_token(&Token::LParen)?;
4168                        let array = self.parse_expr()?;
4169                        self.expect_token(&Token::RParen)?;
4170                        Ok(Expr::MemberOf(MemberOf {
4171                            value: Box::new(expr),
4172                            array: Box::new(array),
4173                        }))
4174                    } else {
4175                        self.expected_ref("OF after MEMBER", self.peek_token_ref())
4176                    }
4177                }
4178                // Can only happen if `get_next_precedence` got out of sync with this function
4179                _ => parser_err!(
4180                    format!("No infix parser for token {:?}", tok.token),
4181                    tok.span.start
4182                ),
4183            }
4184        } else if Token::DoubleColon == *tok {
4185            Ok(Expr::Cast {
4186                kind: CastKind::DoubleColon,
4187                expr: Box::new(expr),
4188                data_type: self.parse_data_type()?,
4189                array: false,
4190                format: None,
4191            })
4192        } else if Token::ExclamationMark == *tok && self.dialect.supports_factorial_operator() {
4193            Ok(Expr::UnaryOp {
4194                op: UnaryOperator::PGPostfixFactorial,
4195                expr: Box::new(expr),
4196            })
4197        } else if Token::LBracket == *tok && self.dialect.supports_partiql()
4198            || (Token::Colon == *tok)
4199        {
4200            self.prev_token();
4201            self.parse_json_access(expr)
4202        } else {
4203            // Can only happen if `get_next_precedence` got out of sync with this function
4204            parser_err!(
4205                format!("No infix parser for token {:?}", tok.token),
4206                tok.span.start
4207            )
4208        }
4209    }
4210
4211    /// Parse the `ESCAPE CHAR` portion of `LIKE`, `ILIKE`, and `SIMILAR TO`
4212    pub fn parse_escape_char(&mut self) -> Result<Option<ValueWithSpan>, ParserError> {
4213        if self.parse_keyword(Keyword::ESCAPE) {
4214            Ok(Some(self.parse_value()?))
4215        } else {
4216            Ok(None)
4217        }
4218    }
4219
4220    /// Parses an array subscript like
4221    /// * `[:]`
4222    /// * `[l]`
4223    /// * `[l:]`
4224    /// * `[:u]`
4225    /// * `[l:u]`
4226    /// * `[l:u:s]`
4227    ///
4228    /// Parser is right after `[`
4229    fn parse_subscript_inner(&mut self) -> Result<Subscript, ParserError> {
4230        // at either `<lower>:(rest)` or `:(rest)]`
4231        let lower_bound = if self.consume_token(&Token::Colon) {
4232            None
4233        } else {
4234            // parse expr until we hit a colon (or any token with lower precedence)
4235            Some(self.parse_subexpr(self.dialect.prec_value(Precedence::Colon))?)
4236        };
4237
4238        // check for end
4239        if self.consume_token(&Token::RBracket) {
4240            if let Some(lower_bound) = lower_bound {
4241                return Ok(Subscript::Index { index: lower_bound });
4242            };
4243            return Ok(Subscript::Slice {
4244                lower_bound,
4245                upper_bound: None,
4246                stride: None,
4247            });
4248        }
4249
4250        // consume the `:`
4251        if lower_bound.is_some() {
4252            self.expect_token(&Token::Colon)?;
4253        }
4254
4255        // we are now at either `]`, `<upper>(rest)]`
4256        let upper_bound = if self.consume_token(&Token::RBracket) {
4257            return Ok(Subscript::Slice {
4258                lower_bound,
4259                upper_bound: None,
4260                stride: None,
4261            });
4262        } else {
4263            // parse expr until we hit a colon (or any token with lower precedence)
4264            Some(self.parse_subexpr(self.dialect.prec_value(Precedence::Colon))?)
4265        };
4266
4267        // check for end
4268        if self.consume_token(&Token::RBracket) {
4269            return Ok(Subscript::Slice {
4270                lower_bound,
4271                upper_bound,
4272                stride: None,
4273            });
4274        }
4275
4276        // we are now at `:]` or `:stride]`
4277        self.expect_token(&Token::Colon)?;
4278        let stride = if self.consume_token(&Token::RBracket) {
4279            None
4280        } else {
4281            Some(self.parse_expr()?)
4282        };
4283
4284        if stride.is_some() {
4285            self.expect_token(&Token::RBracket)?;
4286        }
4287
4288        Ok(Subscript::Slice {
4289            lower_bound,
4290            upper_bound,
4291            stride,
4292        })
4293    }
4294
4295    /// Parse a multi-dimension array accessing like `[1:3][1][1]`
4296    pub fn parse_multi_dim_subscript(
4297        &mut self,
4298        chain: &mut Vec<AccessExpr>,
4299    ) -> Result<(), ParserError> {
4300        while self.consume_token(&Token::LBracket) {
4301            self.parse_subscript(chain)?;
4302        }
4303        Ok(())
4304    }
4305
4306    /// Parses an array subscript like `[1:3]`
4307    ///
4308    /// Parser is right after `[`
4309    fn parse_subscript(&mut self, chain: &mut Vec<AccessExpr>) -> Result<(), ParserError> {
4310        let subscript = self.parse_subscript_inner()?;
4311        chain.push(AccessExpr::Subscript(subscript));
4312        Ok(())
4313    }
4314
4315    fn parse_json_path_object_key(&mut self) -> Result<JsonPathElem, ParserError> {
4316        let token = self.next_token();
4317        match token.token {
4318            Token::Word(Word {
4319                value,
4320                // path segments in SF dot notation can be unquoted or double-quoted;
4321                // Databricks also supports backtick-quoted identifiers
4322                quote_style: quote_style @ (Some('"') | Some('`') | None),
4323                // some experimentation suggests that snowflake permits
4324                // any keyword here unquoted.
4325                keyword: _,
4326            }) => Ok(JsonPathElem::Dot {
4327                key: value,
4328                quoted: quote_style.is_some(),
4329            }),
4330
4331            // This token should never be generated on snowflake or generic
4332            // dialects, but we handle it just in case this is used on future
4333            // dialects.
4334            Token::DoubleQuotedString(key) => Ok(JsonPathElem::Dot { key, quoted: true }),
4335
4336            _ => self.expected("variant object key name", token),
4337        }
4338    }
4339
4340    fn parse_json_access(&mut self, expr: Expr) -> Result<Expr, ParserError> {
4341        let path = self.parse_json_path()?;
4342        Ok(Expr::JsonAccess {
4343            value: Box::new(expr),
4344            path,
4345        })
4346    }
4347
4348    fn parse_json_path(&mut self) -> Result<JsonPath, ParserError> {
4349        let mut path = Vec::new();
4350        loop {
4351            match self.next_token().token {
4352                Token::Colon if path.is_empty() && self.peek_token_ref() == &Token::LBracket => {
4353                    self.next_token();
4354                    let key = self.parse_wildcard_expr()?;
4355                    self.expect_token(&Token::RBracket)?;
4356                    path.push(JsonPathElem::ColonBracket { key });
4357                }
4358                Token::Colon if path.is_empty() => {
4359                    path.push(self.parse_json_path_object_key()?);
4360                }
4361                Token::Period if !path.is_empty() => {
4362                    path.push(self.parse_json_path_object_key()?);
4363                }
4364                Token::LBracket => {
4365                    let key = self.parse_wildcard_expr()?;
4366                    self.expect_token(&Token::RBracket)?;
4367
4368                    path.push(JsonPathElem::Bracket { key });
4369                }
4370                _ => {
4371                    self.prev_token();
4372                    break;
4373                }
4374            };
4375        }
4376
4377        debug_assert!(!path.is_empty());
4378        Ok(JsonPath { path })
4379    }
4380
4381    /// Parses the parens following the `[ NOT ] IN` operator.
4382    pub fn parse_in(&mut self, expr: Expr, negated: bool) -> Result<Expr, ParserError> {
4383        // BigQuery allows `IN UNNEST(array_expression)`
4384        // https://cloud.google.com/bigquery/docs/reference/standard-sql/operators#in_operators
4385        if self.parse_keyword(Keyword::UNNEST) {
4386            self.expect_token(&Token::LParen)?;
4387            let array_expr = self.parse_expr()?;
4388            self.expect_token(&Token::RParen)?;
4389            return Ok(Expr::InUnnest {
4390                expr: Box::new(expr),
4391                array_expr: Box::new(array_expr),
4392                negated,
4393            });
4394        }
4395        if self.dialect.supports_in_unparenthesized_expr()
4396            && self.peek_token_ref().token != Token::LParen
4397        {
4398            return Ok(Expr::InList {
4399                expr: Box::new(expr),
4400                list: vec![self.parse_expr()?],
4401                negated,
4402            });
4403        }
4404        self.expect_token(&Token::LParen)?;
4405        let in_op = match self.maybe_parse(|p| p.parse_query())? {
4406            Some(subquery) => Expr::InSubquery {
4407                expr: Box::new(expr),
4408                subquery,
4409                negated,
4410            },
4411            None => Expr::InList {
4412                expr: Box::new(expr),
4413                list: if self.dialect.supports_in_empty_list() {
4414                    self.parse_comma_separated0(Parser::parse_expr, Token::RParen)?
4415                } else {
4416                    self.parse_comma_separated(Parser::parse_expr)?
4417                },
4418                negated,
4419            },
4420        };
4421        self.expect_token(&Token::RParen)?;
4422        Ok(in_op)
4423    }
4424
4425    /// Parses `BETWEEN <low> AND <high>`, assuming the `BETWEEN` keyword was already consumed.
4426    pub fn parse_between(&mut self, expr: Expr, negated: bool) -> Result<Expr, ParserError> {
4427        // Stop parsing subexpressions for <low> and <high> on tokens with
4428        // precedence lower than that of `BETWEEN`, such as `AND`, `IS`, etc.
4429        let low = self.parse_subexpr(self.dialect.prec_value(Precedence::Between))?;
4430        self.expect_keyword_is(Keyword::AND)?;
4431        let high = self.parse_subexpr(self.dialect.prec_value(Precedence::Between))?;
4432        Ok(Expr::Between {
4433            expr: Box::new(expr),
4434            negated,
4435            low: Box::new(low),
4436            high: Box::new(high),
4437        })
4438    }
4439
4440    /// Parse a PostgreSQL casting style which is in the form of `expr::datatype`.
4441    pub fn parse_pg_cast(&mut self, expr: Expr) -> Result<Expr, ParserError> {
4442        Ok(Expr::Cast {
4443            kind: CastKind::DoubleColon,
4444            expr: Box::new(expr),
4445            data_type: self.parse_data_type()?,
4446            array: false,
4447            format: None,
4448        })
4449    }
4450
4451    /// Get the precedence of the next token
4452    pub fn get_next_precedence(&self) -> Result<u8, ParserError> {
4453        self.dialect.get_next_precedence_default(self)
4454    }
4455
4456    /// Return the token at the given location, or EOF if the index is beyond
4457    /// the length of the current set of tokens.
4458    pub fn token_at(&self, index: usize) -> &TokenWithSpan {
4459        self.tokens.get(index).unwrap_or(&EOF_TOKEN)
4460    }
4461
4462    /// Return the first non-whitespace token that has not yet been processed
4463    /// or Token::EOF
4464    ///
4465    /// See [`Self::peek_token_ref`] to avoid the copy.
4466    pub fn peek_token(&self) -> TokenWithSpan {
4467        self.peek_nth_token(0)
4468    }
4469
4470    /// Return a reference to the first non-whitespace token that has not yet
4471    /// been processed or Token::EOF
4472    pub fn peek_token_ref(&self) -> &TokenWithSpan {
4473        self.peek_nth_token_ref(0)
4474    }
4475
4476    /// Returns the `N` next non-whitespace tokens that have not yet been
4477    /// processed.
4478    ///
4479    /// Example:
4480    /// ```rust
4481    /// # use sqlparser::dialect::GenericDialect;
4482    /// # use sqlparser::parser::Parser;
4483    /// # use sqlparser::keywords::Keyword;
4484    /// # use sqlparser::tokenizer::{Token, Word};
4485    /// let dialect = GenericDialect {};
4486    /// let mut parser = Parser::new(&dialect).try_with_sql("ORDER BY foo, bar").unwrap();
4487    ///
4488    /// // Note that Rust infers the number of tokens to peek based on the
4489    /// // length of the slice pattern!
4490    /// assert!(matches!(
4491    ///     parser.peek_tokens(),
4492    ///     [
4493    ///         Token::Word(Word { keyword: Keyword::ORDER, .. }),
4494    ///         Token::Word(Word { keyword: Keyword::BY, .. }),
4495    ///     ]
4496    /// ));
4497    /// ```
4498    pub fn peek_tokens<const N: usize>(&self) -> [Token; N] {
4499        self.peek_tokens_with_location()
4500            .map(|with_loc| with_loc.token)
4501    }
4502
4503    /// Returns the `N` next non-whitespace tokens with locations that have not
4504    /// yet been processed.
4505    ///
4506    /// See [`Self::peek_token`] for an example.
4507    pub fn peek_tokens_with_location<const N: usize>(&self) -> [TokenWithSpan; N] {
4508        let mut index = self.index;
4509        core::array::from_fn(|_| loop {
4510            let token = self.tokens.get(index);
4511            index += 1;
4512            if let Some(TokenWithSpan {
4513                token: Token::Whitespace(_),
4514                span: _,
4515            }) = token
4516            {
4517                continue;
4518            }
4519            break token.cloned().unwrap_or(TokenWithSpan {
4520                token: Token::EOF,
4521                span: Span::empty(),
4522            });
4523        })
4524    }
4525
4526    /// Returns references to the `N` next non-whitespace tokens
4527    /// that have not yet been processed.
4528    ///
4529    /// See [`Self::peek_tokens`] for an example.
4530    pub fn peek_tokens_ref<const N: usize>(&self) -> [&TokenWithSpan; N] {
4531        let mut index = self.index;
4532        core::array::from_fn(|_| loop {
4533            let token = self.tokens.get(index);
4534            index += 1;
4535            if let Some(TokenWithSpan {
4536                token: Token::Whitespace(_),
4537                span: _,
4538            }) = token
4539            {
4540                continue;
4541            }
4542            break token.unwrap_or(&EOF_TOKEN);
4543        })
4544    }
4545
4546    /// Return nth non-whitespace token that has not yet been processed
4547    pub fn peek_nth_token(&self, n: usize) -> TokenWithSpan {
4548        self.peek_nth_token_ref(n).clone()
4549    }
4550
4551    /// Return nth non-whitespace token that has not yet been processed
4552    pub fn peek_nth_token_ref(&self, mut n: usize) -> &TokenWithSpan {
4553        let mut index = self.index;
4554        loop {
4555            index += 1;
4556            match self.tokens.get(index - 1) {
4557                Some(TokenWithSpan {
4558                    token: Token::Whitespace(_),
4559                    span: _,
4560                }) => continue,
4561                non_whitespace => {
4562                    if n == 0 {
4563                        return non_whitespace.unwrap_or(&EOF_TOKEN);
4564                    }
4565                    n -= 1;
4566                }
4567            }
4568        }
4569    }
4570
4571    /// Return the first token, possibly whitespace, that has not yet been processed
4572    /// (or None if reached end-of-file).
4573    pub fn peek_token_no_skip(&self) -> TokenWithSpan {
4574        self.peek_nth_token_no_skip(0)
4575    }
4576
4577    /// Return nth token, possibly whitespace, that has not yet been processed.
4578    pub fn peek_nth_token_no_skip(&self, n: usize) -> TokenWithSpan {
4579        self.tokens
4580            .get(self.index + n)
4581            .cloned()
4582            .unwrap_or(TokenWithSpan {
4583                token: Token::EOF,
4584                span: Span::empty(),
4585            })
4586    }
4587
4588    /// Return nth token, possibly whitespace, that has not yet been processed.
4589    fn peek_nth_token_no_skip_ref(&self, n: usize) -> &TokenWithSpan {
4590        self.tokens.get(self.index + n).unwrap_or(&EOF_TOKEN)
4591    }
4592
4593    /// Return true if the next tokens exactly `expected`
4594    ///
4595    /// Does not advance the current token.
4596    fn peek_keywords(&mut self, expected: &[Keyword]) -> bool {
4597        let index = self.index;
4598        let matched = self.parse_keywords(expected);
4599        self.index = index;
4600        matched
4601    }
4602
4603    /// Advances to the next non-whitespace token and returns a copy.
4604    ///
4605    /// Please use [`Self::advance_token`] and [`Self::get_current_token`] to
4606    /// avoid the copy.
4607    pub fn next_token(&mut self) -> TokenWithSpan {
4608        self.advance_token();
4609        self.get_current_token().clone()
4610    }
4611
4612    /// Returns the index of the current token
4613    ///
4614    /// This can be used with APIs that expect an index, such as
4615    /// [`Self::token_at`]
4616    pub fn get_current_index(&self) -> usize {
4617        self.index.saturating_sub(1)
4618    }
4619
4620    /// Return the next unprocessed token, possibly whitespace.
4621    pub fn next_token_no_skip(&mut self) -> Option<&TokenWithSpan> {
4622        self.index += 1;
4623        self.tokens.get(self.index - 1)
4624    }
4625
4626    /// Advances the current token to the next non-whitespace token
4627    ///
4628    /// See [`Self::get_current_token`] to get the current token after advancing
4629    pub fn advance_token(&mut self) {
4630        loop {
4631            self.index += 1;
4632            match self.tokens.get(self.index - 1) {
4633                Some(TokenWithSpan {
4634                    token: Token::Whitespace(_),
4635                    span: _,
4636                }) => continue,
4637                _ => break,
4638            }
4639        }
4640    }
4641
4642    /// Returns a reference to the current token
4643    ///
4644    /// Does not advance the current token.
4645    pub fn get_current_token(&self) -> &TokenWithSpan {
4646        self.token_at(self.index.saturating_sub(1))
4647    }
4648
4649    /// Returns a reference to the previous token
4650    ///
4651    /// Does not advance the current token.
4652    pub fn get_previous_token(&self) -> &TokenWithSpan {
4653        self.token_at(self.index.saturating_sub(2))
4654    }
4655
4656    /// Returns a reference to the next token
4657    ///
4658    /// Does not advance the current token.
4659    pub fn get_next_token(&self) -> &TokenWithSpan {
4660        self.token_at(self.index)
4661    }
4662
4663    /// Seek back the last one non-whitespace token.
4664    ///
4665    /// Must be called after `next_token()`, otherwise might panic. OK to call
4666    /// after `next_token()` indicates an EOF.
4667    ///
4668    // TODO rename to backup_token and deprecate prev_token?
4669    pub fn prev_token(&mut self) {
4670        loop {
4671            assert!(self.index > 0);
4672            self.index -= 1;
4673            if let Some(TokenWithSpan {
4674                token: Token::Whitespace(_),
4675                span: _,
4676            }) = self.tokens.get(self.index)
4677            {
4678                continue;
4679            }
4680            return;
4681        }
4682    }
4683
4684    /// Report `found` was encountered instead of `expected`
4685    pub fn expected<T>(&self, expected: &str, found: TokenWithSpan) -> Result<T, ParserError> {
4686        parser_err!(
4687            format!("Expected: {expected}, found: {found}"),
4688            found.span.start
4689        )
4690    }
4691
4692    /// report `found` was encountered instead of `expected`
4693    pub fn expected_ref<T>(&self, expected: &str, found: &TokenWithSpan) -> Result<T, ParserError> {
4694        parser_err!(
4695            format!("Expected: {expected}, found: {found}"),
4696            found.span.start
4697        )
4698    }
4699
4700    /// Report that the token at `index` was found instead of `expected`.
4701    pub fn expected_at<T>(&self, expected: &str, index: usize) -> Result<T, ParserError> {
4702        let found = self.tokens.get(index).unwrap_or(&EOF_TOKEN);
4703        parser_err!(
4704            format!("Expected: {expected}, found: {found}"),
4705            found.span.start
4706        )
4707    }
4708
4709    /// If the current token is the `expected` keyword, consume it and returns
4710    /// true. Otherwise, no tokens are consumed and returns false.
4711    #[must_use]
4712    pub fn parse_keyword(&mut self, expected: Keyword) -> bool {
4713        if self.peek_keyword(expected) {
4714            self.advance_token();
4715            true
4716        } else {
4717            false
4718        }
4719    }
4720
4721    #[must_use]
4722    /// Check if the current token is the expected keyword without consuming it.
4723    ///
4724    /// Returns true if the current token matches the expected keyword.
4725    pub fn peek_keyword(&self, expected: Keyword) -> bool {
4726        matches!(&self.peek_token_ref().token, Token::Word(w) if expected == w.keyword)
4727    }
4728
4729    /// If the current token is the `expected` keyword followed by
4730    /// specified tokens, consume them and returns true.
4731    /// Otherwise, no tokens are consumed and returns false.
4732    ///
4733    /// Note that if the length of `tokens` is too long, this function will
4734    /// not be efficient as it does a loop on the tokens with `peek_nth_token`
4735    /// each time.
4736    pub fn parse_keyword_with_tokens(&mut self, expected: Keyword, tokens: &[Token]) -> bool {
4737        self.keyword_with_tokens(expected, tokens, true)
4738    }
4739
4740    /// Peeks to see if the current token is the `expected` keyword followed by specified tokens
4741    /// without consuming them.
4742    ///
4743    /// See [Self::parse_keyword_with_tokens] for details.
4744    pub(crate) fn peek_keyword_with_tokens(&mut self, expected: Keyword, tokens: &[Token]) -> bool {
4745        self.keyword_with_tokens(expected, tokens, false)
4746    }
4747
4748    fn keyword_with_tokens(&mut self, expected: Keyword, tokens: &[Token], consume: bool) -> bool {
4749        match &self.peek_token_ref().token {
4750            Token::Word(w) if expected == w.keyword => {
4751                for (idx, token) in tokens.iter().enumerate() {
4752                    if self.peek_nth_token_ref(idx + 1).token != *token {
4753                        return false;
4754                    }
4755                }
4756
4757                if consume {
4758                    for _ in 0..(tokens.len() + 1) {
4759                        self.advance_token();
4760                    }
4761                }
4762
4763                true
4764            }
4765            _ => false,
4766        }
4767    }
4768
4769    /// If the current and subsequent tokens exactly match the `keywords`
4770    /// sequence, consume them and returns true. Otherwise, no tokens are
4771    /// consumed and returns false
4772    #[must_use]
4773    pub fn parse_keywords(&mut self, keywords: &[Keyword]) -> bool {
4774        self.parse_keywords_indexed(keywords).is_some()
4775    }
4776
4777    /// Just like [Self::parse_keywords], but - upon success - returns the
4778    /// token index of the first keyword.
4779    #[must_use]
4780    fn parse_keywords_indexed(&mut self, keywords: &[Keyword]) -> Option<usize> {
4781        let start_index = self.index;
4782        let mut first_keyword_index = None;
4783        for &keyword in keywords {
4784            if !self.parse_keyword(keyword) {
4785                self.index = start_index;
4786                return None;
4787            }
4788            if first_keyword_index.is_none() {
4789                first_keyword_index = Some(self.index.saturating_sub(1));
4790            }
4791        }
4792        first_keyword_index
4793    }
4794
4795    /// If the current token is one of the given `keywords`, returns the keyword
4796    /// that matches, without consuming the token. Otherwise, returns [`None`].
4797    #[must_use]
4798    pub fn peek_one_of_keywords(&self, keywords: &[Keyword]) -> Option<Keyword> {
4799        for keyword in keywords {
4800            if self.peek_keyword(*keyword) {
4801                return Some(*keyword);
4802            }
4803        }
4804        None
4805    }
4806
4807    /// If the current token is one of the given `keywords`, consume the token
4808    /// and return the keyword that matches. Otherwise, no tokens are consumed
4809    /// and returns [`None`].
4810    #[must_use]
4811    pub fn parse_one_of_keywords(&mut self, keywords: &[Keyword]) -> Option<Keyword> {
4812        match &self.peek_token_ref().token {
4813            Token::Word(w) => {
4814                keywords
4815                    .iter()
4816                    .find(|keyword| **keyword == w.keyword)
4817                    .map(|keyword| {
4818                        self.advance_token();
4819                        *keyword
4820                    })
4821            }
4822            _ => None,
4823        }
4824    }
4825
4826    /// If the current token is one of the expected keywords, consume the token
4827    /// and return the keyword that matches. Otherwise, return an error.
4828    pub fn expect_one_of_keywords(&mut self, keywords: &[Keyword]) -> Result<Keyword, ParserError> {
4829        if let Some(keyword) = self.parse_one_of_keywords(keywords) {
4830            Ok(keyword)
4831        } else {
4832            let keywords: Vec<String> = keywords.iter().map(|x| format!("{x:?}")).collect();
4833            self.expected_ref(
4834                &format!("one of {}", keywords.join(" or ")),
4835                self.peek_token_ref(),
4836            )
4837        }
4838    }
4839
4840    /// If the current token is the `expected` keyword, consume the token.
4841    /// Otherwise, return an error.
4842    ///
4843    // todo deprecate in favor of expected_keyword_is
4844    pub fn expect_keyword(&mut self, expected: Keyword) -> Result<TokenWithSpan, ParserError> {
4845        if self.parse_keyword(expected) {
4846            Ok(self.get_current_token().clone())
4847        } else {
4848            self.expected_ref(format!("{:?}", &expected).as_str(), self.peek_token_ref())
4849        }
4850    }
4851
4852    /// If the current token is the `expected` keyword, consume the token.
4853    /// Otherwise, return an error.
4854    ///
4855    /// This differs from expect_keyword only in that the matched keyword
4856    /// token is not returned.
4857    pub fn expect_keyword_is(&mut self, expected: Keyword) -> Result<(), ParserError> {
4858        if self.parse_keyword(expected) {
4859            Ok(())
4860        } else {
4861            self.expected_ref(format!("{:?}", &expected).as_str(), self.peek_token_ref())
4862        }
4863    }
4864
4865    /// If the current and subsequent tokens exactly match the `keywords`
4866    /// sequence, consume them and returns Ok. Otherwise, return an Error.
4867    pub fn expect_keywords(&mut self, expected: &[Keyword]) -> Result<(), ParserError> {
4868        for &kw in expected {
4869            self.expect_keyword_is(kw)?;
4870        }
4871        Ok(())
4872    }
4873
4874    /// Consume the next token if it matches the expected token, otherwise return false
4875    ///
4876    /// See [Self::advance_token] to consume the token unconditionally
4877    #[must_use]
4878    pub fn consume_token(&mut self, expected: &Token) -> bool {
4879        if self.peek_token_ref() == expected {
4880            self.advance_token();
4881            true
4882        } else {
4883            false
4884        }
4885    }
4886
4887    /// If the current and subsequent tokens exactly match the `tokens`
4888    /// sequence, consume them and returns true. Otherwise, no tokens are
4889    /// consumed and returns false
4890    #[must_use]
4891    pub fn consume_tokens(&mut self, tokens: &[Token]) -> bool {
4892        let index = self.index;
4893        for token in tokens {
4894            if !self.consume_token(token) {
4895                self.index = index;
4896                return false;
4897            }
4898        }
4899        true
4900    }
4901
4902    /// Bail out if the current token is not an expected keyword, or consume it if it is
4903    pub fn expect_token(&mut self, expected: &Token) -> Result<TokenWithSpan, ParserError> {
4904        if self.peek_token_ref() == expected {
4905            Ok(self.next_token())
4906        } else {
4907            self.expected_ref(&expected.to_string(), self.peek_token_ref())
4908        }
4909    }
4910
4911    fn parse<T: FromStr>(s: String, loc: Location) -> Result<T, ParserError>
4912    where
4913        <T as FromStr>::Err: Display,
4914    {
4915        s.parse::<T>().map_err(|e| {
4916            ParserError::ParserError(format!(
4917                "Could not parse '{s}' as {}: {e}{loc}",
4918                core::any::type_name::<T>()
4919            ))
4920        })
4921    }
4922
4923    /// Parse a comma-separated list of 1+ SelectItem
4924    pub fn parse_projection(&mut self) -> Result<Vec<SelectItem>, ParserError> {
4925        // BigQuery and Snowflake allow trailing commas, but only in project lists
4926        // e.g. `SELECT 1, 2, FROM t`
4927        // https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#trailing_commas
4928        // https://docs.snowflake.com/en/release-notes/2024/8_11#select-supports-trailing-commas
4929
4930        let trailing_commas =
4931            self.options.trailing_commas | self.dialect.supports_projection_trailing_commas();
4932
4933        self.parse_comma_separated_with_trailing_commas(
4934            |p| p.parse_select_item(),
4935            trailing_commas,
4936            Self::is_reserved_for_column_alias,
4937        )
4938    }
4939
4940    /// Parse a list of actions for `GRANT` statements.
4941    pub fn parse_actions_list(&mut self) -> Result<Vec<Action>, ParserError> {
4942        let mut values = vec![];
4943        loop {
4944            values.push(self.parse_grant_permission()?);
4945            if !self.consume_token(&Token::Comma) {
4946                break;
4947            } else if self.options.trailing_commas {
4948                match &self.peek_token_ref().token {
4949                    Token::Word(kw) if kw.keyword == Keyword::ON => {
4950                        break;
4951                    }
4952                    Token::RParen
4953                    | Token::SemiColon
4954                    | Token::EOF
4955                    | Token::RBracket
4956                    | Token::RBrace => break,
4957                    _ => continue,
4958                }
4959            }
4960        }
4961        Ok(values)
4962    }
4963
4964    /// Parse a list of [TableWithJoins]
4965    fn parse_table_with_joins(&mut self) -> Result<Vec<TableWithJoins>, ParserError> {
4966        let trailing_commas = self.dialect.supports_from_trailing_commas();
4967
4968        self.parse_comma_separated_with_trailing_commas(
4969            Parser::parse_table_and_joins,
4970            trailing_commas,
4971            |kw, parser| !self.dialect.is_table_factor(kw, parser),
4972        )
4973    }
4974
4975    /// Parse the comma of a comma-separated syntax element.
4976    /// `R` is a predicate that should return true if the next
4977    /// keyword is a reserved keyword.
4978    /// Allows for control over trailing commas
4979    ///
4980    /// Returns true if there is a next element
4981    fn is_parse_comma_separated_end_with_trailing_commas<R>(
4982        &mut self,
4983        trailing_commas: bool,
4984        is_reserved_keyword: &R,
4985    ) -> bool
4986    where
4987        R: Fn(&Keyword, &mut Parser) -> bool,
4988    {
4989        if !self.consume_token(&Token::Comma) {
4990            true
4991        } else if trailing_commas {
4992            let token = self.next_token().token;
4993            let is_end = match token {
4994                Token::Word(ref kw) if is_reserved_keyword(&kw.keyword, self) => true,
4995                Token::RParen | Token::SemiColon | Token::EOF | Token::RBracket | Token::RBrace => {
4996                    true
4997                }
4998                _ => false,
4999            };
5000            self.prev_token();
5001
5002            is_end
5003        } else {
5004            false
5005        }
5006    }
5007
5008    /// Parse the comma of a comma-separated syntax element.
5009    /// Returns true if there is a next element
5010    fn is_parse_comma_separated_end(&mut self) -> bool {
5011        self.is_parse_comma_separated_end_with_trailing_commas(
5012            self.options.trailing_commas,
5013            &Self::is_reserved_for_column_alias,
5014        )
5015    }
5016
5017    /// Parse a comma-separated list of 1+ items accepted by `F`
5018    pub fn parse_comma_separated<T, F>(&mut self, f: F) -> Result<Vec<T>, ParserError>
5019    where
5020        F: FnMut(&mut Parser<'a>) -> Result<T, ParserError>,
5021    {
5022        self.parse_comma_separated_with_trailing_commas(
5023            f,
5024            self.options.trailing_commas,
5025            Self::is_reserved_for_column_alias,
5026        )
5027    }
5028
5029    /// Parse a comma-separated list of 1+ items accepted by `F`.
5030    /// `R` is a predicate that should return true if the next
5031    /// keyword is a reserved keyword.
5032    /// Allows for control over trailing commas.
5033    fn parse_comma_separated_with_trailing_commas<T, F, R>(
5034        &mut self,
5035        mut f: F,
5036        trailing_commas: bool,
5037        is_reserved_keyword: R,
5038    ) -> Result<Vec<T>, ParserError>
5039    where
5040        F: FnMut(&mut Parser<'a>) -> Result<T, ParserError>,
5041        R: Fn(&Keyword, &mut Parser) -> bool,
5042    {
5043        let mut values = vec![];
5044        loop {
5045            values.push(f(self)?);
5046            if self.is_parse_comma_separated_end_with_trailing_commas(
5047                trailing_commas,
5048                &is_reserved_keyword,
5049            ) {
5050                break;
5051            }
5052        }
5053        Ok(values)
5054    }
5055
5056    /// Parse a period-separated list of 1+ items accepted by `F`
5057    fn parse_period_separated<T, F>(&mut self, mut f: F) -> Result<Vec<T>, ParserError>
5058    where
5059        F: FnMut(&mut Parser<'a>) -> Result<T, ParserError>,
5060    {
5061        let mut values = vec![];
5062        loop {
5063            values.push(f(self)?);
5064            if !self.consume_token(&Token::Period) {
5065                break;
5066            }
5067        }
5068        Ok(values)
5069    }
5070
5071    /// Parse a keyword-separated list of 1+ items accepted by `F`
5072    pub fn parse_keyword_separated<T, F>(
5073        &mut self,
5074        keyword: Keyword,
5075        mut f: F,
5076    ) -> Result<Vec<T>, ParserError>
5077    where
5078        F: FnMut(&mut Parser<'a>) -> Result<T, ParserError>,
5079    {
5080        let mut values = vec![];
5081        loop {
5082            values.push(f(self)?);
5083            if !self.parse_keyword(keyword) {
5084                break;
5085            }
5086        }
5087        Ok(values)
5088    }
5089
5090    /// Parse an expression enclosed in parentheses.
5091    pub fn parse_parenthesized<T, F>(&mut self, mut f: F) -> Result<T, ParserError>
5092    where
5093        F: FnMut(&mut Parser<'a>) -> Result<T, ParserError>,
5094    {
5095        self.expect_token(&Token::LParen)?;
5096        let res = f(self)?;
5097        self.expect_token(&Token::RParen)?;
5098        Ok(res)
5099    }
5100
5101    /// Parse a comma-separated list of 0+ items accepted by `F`
5102    /// * `end_token` - expected end token for the closure (e.g. [Token::RParen], [Token::RBrace] ...)
5103    pub fn parse_comma_separated0<T, F>(
5104        &mut self,
5105        f: F,
5106        end_token: Token,
5107    ) -> Result<Vec<T>, ParserError>
5108    where
5109        F: FnMut(&mut Parser<'a>) -> Result<T, ParserError>,
5110    {
5111        if self.peek_token_ref().token == end_token {
5112            return Ok(vec![]);
5113        }
5114
5115        if self.options.trailing_commas && self.peek_tokens() == [Token::Comma, end_token] {
5116            let _ = self.consume_token(&Token::Comma);
5117            return Ok(vec![]);
5118        }
5119
5120        self.parse_comma_separated(f)
5121    }
5122
5123    /// Parses 0 or more statements, each followed by a semicolon.
5124    /// If the next token is any of `terminal_keywords` then no more
5125    /// statements will be parsed.
5126    pub(crate) fn parse_statement_list(
5127        &mut self,
5128        terminal_keywords: &[Keyword],
5129    ) -> Result<Vec<Statement>, ParserError> {
5130        let mut values = vec![];
5131        loop {
5132            match &self.peek_nth_token_ref(0).token {
5133                Token::EOF => break,
5134                Token::Word(w)
5135                    if w.quote_style.is_none() && terminal_keywords.contains(&w.keyword) =>
5136                {
5137                    break;
5138                }
5139                _ => {}
5140            }
5141
5142            values.push(self.parse_statement()?);
5143            self.expect_token(&Token::SemiColon)?;
5144        }
5145        Ok(values)
5146    }
5147
5148    /// Default implementation of a predicate that returns true if
5149    /// the specified keyword is reserved for column alias.
5150    /// See [Dialect::is_column_alias]
5151    fn is_reserved_for_column_alias(kw: &Keyword, parser: &mut Parser) -> bool {
5152        !parser.dialect.is_column_alias(kw, parser)
5153    }
5154
5155    /// Run a parser method `f`, reverting back to the current position if unsuccessful.
5156    /// Returns `ParserError::RecursionLimitExceeded` if `f` returns a `RecursionLimitExceeded`.
5157    /// Returns `Ok(None)` if `f` returns any other error.
5158    pub fn maybe_parse<T, F>(&mut self, f: F) -> Result<Option<T>, ParserError>
5159    where
5160        F: FnMut(&mut Parser) -> Result<T, ParserError>,
5161    {
5162        match self.try_parse(f) {
5163            Ok(t) => Ok(Some(t)),
5164            Err(ParserError::RecursionLimitExceeded) => Err(ParserError::RecursionLimitExceeded),
5165            _ => Ok(None),
5166        }
5167    }
5168
5169    /// Run a parser method `f`, reverting back to the current position if unsuccessful.
5170    pub fn try_parse<T, F>(&mut self, mut f: F) -> Result<T, ParserError>
5171    where
5172        F: FnMut(&mut Parser) -> Result<T, ParserError>,
5173    {
5174        let index = self.index;
5175        match f(self) {
5176            Ok(t) => Ok(t),
5177            Err(e) => {
5178                // Unwind stack if limit exceeded
5179                self.index = index;
5180                Err(e)
5181            }
5182        }
5183    }
5184
5185    /// Parse either `ALL`, `DISTINCT` or `DISTINCT ON (...)`. Returns [`None`] if `ALL` is parsed
5186    /// and results in a [`ParserError`] if both `ALL` and `DISTINCT` are found.
5187    pub fn parse_all_or_distinct(&mut self) -> Result<Option<Distinct>, ParserError> {
5188        let loc = self.peek_token_ref().span.start;
5189        let distinct = match self.parse_one_of_keywords(&[Keyword::ALL, Keyword::DISTINCT]) {
5190            Some(Keyword::ALL) => {
5191                if self.peek_keyword(Keyword::DISTINCT) {
5192                    return parser_err!("Cannot specify ALL then DISTINCT".to_string(), loc);
5193                }
5194                Some(Distinct::All)
5195            }
5196            Some(Keyword::DISTINCT) => {
5197                if self.peek_keyword(Keyword::ALL) {
5198                    return parser_err!("Cannot specify DISTINCT then ALL".to_string(), loc);
5199                }
5200                Some(Distinct::Distinct)
5201            }
5202            None => return Ok(None),
5203            _ => return parser_err!("ALL or DISTINCT", loc),
5204        };
5205
5206        let Some(Distinct::Distinct) = distinct else {
5207            return Ok(distinct);
5208        };
5209        if !self.parse_keyword(Keyword::ON) {
5210            return Ok(Some(Distinct::Distinct));
5211        }
5212
5213        self.expect_token(&Token::LParen)?;
5214        let col_names = if self.consume_token(&Token::RParen) {
5215            self.prev_token();
5216            Vec::new()
5217        } else {
5218            self.parse_comma_separated(Parser::parse_expr)?
5219        };
5220        self.expect_token(&Token::RParen)?;
5221        Ok(Some(Distinct::On(col_names)))
5222    }
5223
5224    /// Parse a SQL CREATE statement
5225    pub fn parse_create(&mut self) -> Result<Statement, ParserError> {
5226        let or_replace = self.parse_keywords(&[Keyword::OR, Keyword::REPLACE]);
5227        let or_alter = self.parse_keywords(&[Keyword::OR, Keyword::ALTER]);
5228        let multiset = self.maybe_parse_multiset();
5229        let local = self.parse_one_of_keywords(&[Keyword::LOCAL]).is_some();
5230        let global = self.parse_one_of_keywords(&[Keyword::GLOBAL]).is_some();
5231        let transient = self.parse_one_of_keywords(&[Keyword::TRANSIENT]).is_some();
5232        let global: Option<bool> = if global {
5233            Some(true)
5234        } else if local {
5235            Some(false)
5236        } else {
5237            None
5238        };
5239        let temporary = self
5240            .parse_one_of_keywords(&[Keyword::TEMP, Keyword::TEMPORARY])
5241            .is_some();
5242        let volatile = self.parse_keyword(Keyword::VOLATILE);
5243        let unlogged = self.peek_keywords(&[Keyword::UNLOGGED, Keyword::TABLE]);
5244        if unlogged {
5245            self.expect_keyword(Keyword::UNLOGGED)?;
5246        }
5247        let persistent = dialect_of!(self is DuckDbDialect)
5248            && self.parse_one_of_keywords(&[Keyword::PERSISTENT]).is_some();
5249        let create_view_params = self.parse_create_view_params()?;
5250        if self.peek_keywords(&[Keyword::SNAPSHOT, Keyword::TABLE]) {
5251            self.parse_create_snapshot_table().map(Into::into)
5252        } else if self.peek_keywords(&[Keyword::TEXT, Keyword::SEARCH]) {
5253            self.parse_create_text_search().map(Into::into)
5254        } else if self.parse_keyword(Keyword::TABLE) {
5255            self.parse_create_table(
5256                or_replace, temporary, unlogged, global, transient, volatile, multiset,
5257            )
5258            .map(Into::into)
5259        } else if self.peek_keyword(Keyword::MATERIALIZED)
5260            || self.peek_keyword(Keyword::VIEW)
5261            || self.peek_keywords(&[Keyword::SECURE, Keyword::MATERIALIZED, Keyword::VIEW])
5262            || self.peek_keywords(&[Keyword::SECURE, Keyword::VIEW])
5263        {
5264            self.parse_create_view(or_alter, or_replace, temporary, create_view_params)
5265                .map(Into::into)
5266        } else if self.parse_keyword(Keyword::POLICY) {
5267            self.parse_create_policy().map(Into::into)
5268        } else if self.parse_keyword(Keyword::EXTERNAL) {
5269            self.parse_create_external_table(or_replace).map(Into::into)
5270        } else if self.parse_keyword(Keyword::FUNCTION) {
5271            self.parse_create_function(or_alter, or_replace, temporary)
5272        } else if self.parse_keyword(Keyword::DOMAIN) {
5273            self.parse_create_domain().map(Into::into)
5274        } else if self.parse_keyword(Keyword::TRIGGER) {
5275            self.parse_create_trigger(temporary, or_alter, or_replace, false)
5276                .map(Into::into)
5277        } else if self.parse_keywords(&[Keyword::CONSTRAINT, Keyword::TRIGGER]) {
5278            self.parse_create_trigger(temporary, or_alter, or_replace, true)
5279                .map(Into::into)
5280        } else if self.parse_keyword(Keyword::MACRO) {
5281            self.parse_create_macro(or_replace, temporary)
5282        } else if self.parse_keyword(Keyword::SECRET) {
5283            self.parse_create_secret(or_replace, temporary, persistent)
5284        } else if self.parse_keyword(Keyword::USER) {
5285            self.parse_create_user(or_replace).map(Into::into)
5286        } else if or_replace {
5287            self.expected_ref(
5288                "[EXTERNAL] TABLE or [MATERIALIZED] VIEW or FUNCTION after CREATE OR REPLACE",
5289                self.peek_token_ref(),
5290            )
5291        } else if self.parse_keyword(Keyword::EXTENSION) {
5292            self.parse_create_extension().map(Into::into)
5293        } else if self.parse_keyword(Keyword::INDEX) {
5294            self.parse_create_index(false).map(Into::into)
5295        } else if self.parse_keywords(&[Keyword::UNIQUE, Keyword::INDEX]) {
5296            self.parse_create_index(true).map(Into::into)
5297        } else if dialect_of!(self is GenericDialect | MySqlDialect)
5298            && self.parse_keywords(&[Keyword::FULLTEXT, Keyword::INDEX])
5299        {
5300            self.parse_create_fulltext_or_spatial_index(FullTextOrSpatialKind::Fulltext)
5301                .map(Into::into)
5302        } else if dialect_of!(self is GenericDialect | MySqlDialect)
5303            && self.parse_keywords(&[Keyword::SPATIAL, Keyword::INDEX])
5304        {
5305            self.parse_create_fulltext_or_spatial_index(FullTextOrSpatialKind::Spatial)
5306                .map(Into::into)
5307        } else if self.parse_keyword(Keyword::VIRTUAL) {
5308            self.parse_create_virtual_table()
5309        } else if self.parse_keyword(Keyword::SCHEMA) {
5310            self.parse_create_schema()
5311        } else if self.parse_keyword(Keyword::DATABASE) {
5312            self.parse_create_database()
5313        } else if self.parse_keyword(Keyword::ROLE) {
5314            self.parse_create_role().map(Into::into)
5315        } else if self.parse_keyword(Keyword::SEQUENCE) {
5316            self.parse_create_sequence(temporary)
5317        } else if self.parse_keyword(Keyword::COLLATION) {
5318            self.parse_create_collation().map(Into::into)
5319        } else if self.parse_keyword(Keyword::TYPE) {
5320            self.parse_create_type()
5321        } else if self.parse_keyword(Keyword::PROCEDURE) {
5322            self.parse_create_procedure(or_alter)
5323        } else if self.parse_keyword(Keyword::CONNECTOR) {
5324            self.parse_create_connector().map(Into::into)
5325        } else if self.parse_keyword(Keyword::OPERATOR) {
5326            // Check if this is CREATE OPERATOR FAMILY or CREATE OPERATOR CLASS
5327            if self.parse_keyword(Keyword::FAMILY) {
5328                self.parse_create_operator_family().map(Into::into)
5329            } else if self.parse_keyword(Keyword::CLASS) {
5330                self.parse_create_operator_class().map(Into::into)
5331            } else {
5332                self.parse_create_operator().map(Into::into)
5333            }
5334        } else if self.parse_keyword(Keyword::SERVER) {
5335            self.parse_pg_create_server()
5336        } else {
5337            self.expected_ref("an object type after CREATE", self.peek_token_ref())
5338        }
5339    }
5340
5341    fn parse_text_search_object_type(&mut self) -> Result<TextSearchObjectType, ParserError> {
5342        match self.expect_one_of_keywords(&[
5343            Keyword::DICTIONARY,
5344            Keyword::CONFIGURATION,
5345            Keyword::TEMPLATE,
5346            Keyword::PARSER,
5347        ])? {
5348            Keyword::DICTIONARY => Ok(TextSearchObjectType::Dictionary),
5349            Keyword::CONFIGURATION => Ok(TextSearchObjectType::Configuration),
5350            Keyword::TEMPLATE => Ok(TextSearchObjectType::Template),
5351            Keyword::PARSER => Ok(TextSearchObjectType::Parser),
5352            unexpected_keyword => Err(ParserError::ParserError(format!(
5353                "Internal parser error: expected any of {{DICTIONARY, CONFIGURATION, TEMPLATE, PARSER}}, got {unexpected_keyword:?}"
5354            ))),
5355        }
5356    }
5357
5358    /// Parse a `CREATE TEXT SEARCH ...` statement.
5359    pub fn parse_create_text_search(&mut self) -> Result<CreateTextSearch, ParserError> {
5360        self.expect_keywords(&[Keyword::TEXT, Keyword::SEARCH])?;
5361        let object_type = self.parse_text_search_object_type()?;
5362        let name = self.parse_object_name(false)?;
5363        self.expect_token(&Token::LParen)?;
5364        let options = self.parse_comma_separated(Parser::parse_sql_option)?;
5365        self.expect_token(&Token::RParen)?;
5366        Ok(CreateTextSearch {
5367            object_type,
5368            name,
5369            options,
5370        })
5371    }
5372
5373    fn parse_alter_text_search_option(&mut self) -> Result<AlterTextSearchOption, ParserError> {
5374        let key = self.parse_identifier()?;
5375        let value = if self.consume_token(&Token::Eq) {
5376            Some(self.parse_expr()?)
5377        } else {
5378            None
5379        };
5380        Ok(AlterTextSearchOption { key, value })
5381    }
5382
5383    /// Parse an `ALTER TEXT SEARCH ...` statement.
5384    pub fn parse_alter_text_search(&mut self) -> Result<AlterTextSearch, ParserError> {
5385        self.expect_keywords(&[Keyword::TEXT, Keyword::SEARCH])?;
5386        let object_type = self.parse_text_search_object_type()?;
5387        let name = self.parse_object_name(false)?;
5388
5389        let operation = if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
5390            AlterTextSearchOperation::RenameTo {
5391                new_name: self.parse_identifier()?,
5392            }
5393        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
5394            AlterTextSearchOperation::OwnerTo(self.parse_owner()?)
5395        } else if self.parse_keywords(&[Keyword::SET, Keyword::SCHEMA]) {
5396            AlterTextSearchOperation::SetSchema {
5397                schema_name: self.parse_object_name(false)?,
5398            }
5399        } else if self.consume_token(&Token::LParen) {
5400            let options = self.parse_comma_separated(Parser::parse_alter_text_search_option)?;
5401            self.expect_token(&Token::RParen)?;
5402            AlterTextSearchOperation::SetOptions { options }
5403        } else {
5404            let expected = "RENAME TO, OWNER TO, SET SCHEMA, or (...) after ALTER TEXT SEARCH";
5405            return self.expected_ref(expected, self.peek_token_ref());
5406        };
5407
5408        Ok(AlterTextSearch {
5409            object_type,
5410            name,
5411            operation,
5412        })
5413    }
5414
5415    fn parse_create_user(&mut self, or_replace: bool) -> Result<CreateUser, ParserError> {
5416        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
5417        let name = self.parse_identifier()?;
5418        let options = self
5419            .parse_key_value_options(false, &[Keyword::WITH, Keyword::TAG])?
5420            .options;
5421        let with_tags = self.parse_keyword(Keyword::WITH);
5422        let tags = if self.parse_keyword(Keyword::TAG) {
5423            self.parse_key_value_options(true, &[])?.options
5424        } else {
5425            vec![]
5426        };
5427        Ok(CreateUser {
5428            or_replace,
5429            if_not_exists,
5430            name,
5431            options: KeyValueOptions {
5432                options,
5433                delimiter: KeyValueOptionsDelimiter::Space,
5434            },
5435            with_tags,
5436            tags: KeyValueOptions {
5437                options: tags,
5438                delimiter: KeyValueOptionsDelimiter::Comma,
5439            },
5440        })
5441    }
5442
5443    /// See [DuckDB Docs](https://duckdb.org/docs/sql/statements/create_secret.html) for more details.
5444    pub fn parse_create_secret(
5445        &mut self,
5446        or_replace: bool,
5447        temporary: bool,
5448        persistent: bool,
5449    ) -> Result<Statement, ParserError> {
5450        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
5451
5452        let mut storage_specifier = None;
5453        let mut name = None;
5454        if self.peek_token_ref().token != Token::LParen {
5455            if self.parse_keyword(Keyword::IN) {
5456                storage_specifier = self.parse_identifier().ok()
5457            } else {
5458                name = self.parse_identifier().ok();
5459            }
5460
5461            // Storage specifier may follow the name
5462            if storage_specifier.is_none()
5463                && self.peek_token_ref().token != Token::LParen
5464                && self.parse_keyword(Keyword::IN)
5465            {
5466                storage_specifier = self.parse_identifier().ok();
5467            }
5468        }
5469
5470        self.expect_token(&Token::LParen)?;
5471        self.expect_keyword_is(Keyword::TYPE)?;
5472        let secret_type = self.parse_identifier()?;
5473
5474        let mut options = Vec::new();
5475        if self.consume_token(&Token::Comma) {
5476            options.append(&mut self.parse_comma_separated(|p| {
5477                let key = p.parse_identifier()?;
5478                let value = p.parse_identifier()?;
5479                Ok(SecretOption { key, value })
5480            })?);
5481        }
5482        self.expect_token(&Token::RParen)?;
5483
5484        let temp = match (temporary, persistent) {
5485            (true, false) => Some(true),
5486            (false, true) => Some(false),
5487            (false, false) => None,
5488            _ => self.expected_ref("TEMPORARY or PERSISTENT", self.peek_token_ref())?,
5489        };
5490
5491        Ok(Statement::CreateSecret {
5492            or_replace,
5493            temporary: temp,
5494            if_not_exists,
5495            name,
5496            storage_specifier,
5497            secret_type,
5498            options,
5499        })
5500    }
5501
5502    /// Parse a CACHE TABLE statement
5503    pub fn parse_cache_table(&mut self) -> Result<Statement, ParserError> {
5504        let (mut table_flag, mut options, mut has_as, mut query) = (None, vec![], false, None);
5505        if self.parse_keyword(Keyword::TABLE) {
5506            let table_name = self.parse_object_name(false)?;
5507            if self.peek_token_ref().token != Token::EOF {
5508                if let Token::Word(word) = &self.peek_token_ref().token {
5509                    if word.keyword == Keyword::OPTIONS {
5510                        options = self.parse_options(Keyword::OPTIONS)?
5511                    }
5512                };
5513
5514                if self.peek_token_ref().token != Token::EOF {
5515                    let (a, q) = self.parse_as_query()?;
5516                    has_as = a;
5517                    query = Some(q);
5518                }
5519
5520                Ok(Statement::Cache {
5521                    table_flag,
5522                    table_name,
5523                    has_as,
5524                    options,
5525                    query,
5526                })
5527            } else {
5528                Ok(Statement::Cache {
5529                    table_flag,
5530                    table_name,
5531                    has_as,
5532                    options,
5533                    query,
5534                })
5535            }
5536        } else {
5537            table_flag = Some(self.parse_object_name(false)?);
5538            if self.parse_keyword(Keyword::TABLE) {
5539                let table_name = self.parse_object_name(false)?;
5540                if self.peek_token_ref().token != Token::EOF {
5541                    if let Token::Word(word) = &self.peek_token_ref().token {
5542                        if word.keyword == Keyword::OPTIONS {
5543                            options = self.parse_options(Keyword::OPTIONS)?
5544                        }
5545                    };
5546
5547                    if self.peek_token_ref().token != Token::EOF {
5548                        let (a, q) = self.parse_as_query()?;
5549                        has_as = a;
5550                        query = Some(q);
5551                    }
5552
5553                    Ok(Statement::Cache {
5554                        table_flag,
5555                        table_name,
5556                        has_as,
5557                        options,
5558                        query,
5559                    })
5560                } else {
5561                    Ok(Statement::Cache {
5562                        table_flag,
5563                        table_name,
5564                        has_as,
5565                        options,
5566                        query,
5567                    })
5568                }
5569            } else {
5570                if self.peek_token_ref().token == Token::EOF {
5571                    self.prev_token();
5572                }
5573                self.expected_ref("a `TABLE` keyword", self.peek_token_ref())
5574            }
5575        }
5576    }
5577
5578    /// Parse 'AS' before as query,such as `WITH XXX AS SELECT XXX` oer `CACHE TABLE AS SELECT XXX`
5579    pub fn parse_as_query(&mut self) -> Result<(bool, Box<Query>), ParserError> {
5580        match &self.peek_token_ref().token {
5581            Token::Word(word) => match word.keyword {
5582                Keyword::AS => {
5583                    self.next_token();
5584                    Ok((true, self.parse_query()?))
5585                }
5586                _ => Ok((false, self.parse_query()?)),
5587            },
5588            _ => self.expected_ref("a QUERY statement", self.peek_token_ref()),
5589        }
5590    }
5591
5592    /// Parse a UNCACHE TABLE statement
5593    pub fn parse_uncache_table(&mut self) -> Result<Statement, ParserError> {
5594        self.expect_keyword_is(Keyword::TABLE)?;
5595        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
5596        let table_name = self.parse_object_name(false)?;
5597        Ok(Statement::UNCache {
5598            table_name,
5599            if_exists,
5600        })
5601    }
5602
5603    /// SQLite-specific `CREATE VIRTUAL TABLE`
5604    pub fn parse_create_virtual_table(&mut self) -> Result<Statement, ParserError> {
5605        self.expect_keyword_is(Keyword::TABLE)?;
5606        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
5607        let table_name = self.parse_object_name(false)?;
5608        self.expect_keyword_is(Keyword::USING)?;
5609        let module_name = self.parse_identifier()?;
5610        // SQLite docs note that module "arguments syntax is sufficiently
5611        // general that the arguments can be made to appear as column
5612        // definitions in a traditional CREATE TABLE statement", but
5613        // we don't implement that.
5614        let module_args = self.parse_parenthesized_column_list(Optional, false)?;
5615        Ok(Statement::CreateVirtualTable {
5616            name: table_name,
5617            if_not_exists,
5618            module_name,
5619            module_args,
5620        })
5621    }
5622
5623    /// Parse a `CREATE SCHEMA` statement.
5624    pub fn parse_create_schema(&mut self) -> Result<Statement, ParserError> {
5625        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
5626
5627        let schema_name = self.parse_schema_name()?;
5628
5629        let default_collate_spec = if self.parse_keywords(&[Keyword::DEFAULT, Keyword::COLLATE]) {
5630            Some(self.parse_expr()?)
5631        } else {
5632            None
5633        };
5634
5635        let with = if self.peek_keyword(Keyword::WITH) {
5636            Some(self.parse_options(Keyword::WITH)?)
5637        } else {
5638            None
5639        };
5640
5641        let options = if self.peek_keyword(Keyword::OPTIONS) {
5642            Some(self.parse_options(Keyword::OPTIONS)?)
5643        } else {
5644            None
5645        };
5646
5647        let clone = if self.parse_keyword(Keyword::CLONE) {
5648            Some(self.parse_object_name(false)?)
5649        } else {
5650            None
5651        };
5652
5653        Ok(Statement::CreateSchema {
5654            schema_name,
5655            if_not_exists,
5656            with,
5657            options,
5658            default_collate_spec,
5659            clone,
5660        })
5661    }
5662
5663    fn parse_schema_name(&mut self) -> Result<SchemaName, ParserError> {
5664        if self.parse_keyword(Keyword::AUTHORIZATION) {
5665            Ok(SchemaName::UnnamedAuthorization(self.parse_identifier()?))
5666        } else {
5667            let name = self.parse_object_name(false)?;
5668
5669            if self.parse_keyword(Keyword::AUTHORIZATION) {
5670                Ok(SchemaName::NamedAuthorization(
5671                    name,
5672                    self.parse_identifier()?,
5673                ))
5674            } else {
5675                Ok(SchemaName::Simple(name))
5676            }
5677        }
5678    }
5679
5680    /// Parse a `CREATE DATABASE` statement.
5681    pub fn parse_create_database(&mut self) -> Result<Statement, ParserError> {
5682        let ine = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
5683        let db_name = self.parse_object_name(false)?;
5684        let mut location = None;
5685        let mut managed_location = None;
5686        loop {
5687            match self.parse_one_of_keywords(&[Keyword::LOCATION, Keyword::MANAGEDLOCATION]) {
5688                Some(Keyword::LOCATION) => location = Some(self.parse_literal_string()?),
5689                Some(Keyword::MANAGEDLOCATION) => {
5690                    managed_location = Some(self.parse_literal_string()?)
5691                }
5692                _ => break,
5693            }
5694        }
5695        let clone = if self.parse_keyword(Keyword::CLONE) {
5696            Some(self.parse_object_name(false)?)
5697        } else {
5698            None
5699        };
5700
5701        // Parse MySQL-style [DEFAULT] CHARACTER SET and [DEFAULT] COLLATE options
5702        //
5703        // Note: The docs only mention `CHARACTER SET`, but `CHARSET` is also supported.
5704        // Furthermore, MySQL will only accept one character set, raising an error if there is more
5705        // than one, but will accept multiple collations and use the last one.
5706        //
5707        // <https://dev.mysql.com/doc/refman/8.4/en/create-database.html>
5708        let mut default_charset = None;
5709        let mut default_collation = None;
5710        loop {
5711            let has_default = self.parse_keyword(Keyword::DEFAULT);
5712            if default_charset.is_none() && self.parse_keywords(&[Keyword::CHARACTER, Keyword::SET])
5713                || self.parse_keyword(Keyword::CHARSET)
5714            {
5715                let _ = self.consume_token(&Token::Eq);
5716                default_charset = Some(self.parse_identifier()?.value);
5717            } else if self.parse_keyword(Keyword::COLLATE) {
5718                let _ = self.consume_token(&Token::Eq);
5719                default_collation = Some(self.parse_identifier()?.value);
5720            } else if has_default {
5721                // DEFAULT keyword not followed by CHARACTER SET, CHARSET, or COLLATE
5722                self.prev_token();
5723                break;
5724            } else {
5725                break;
5726            }
5727        }
5728
5729        Ok(Statement::CreateDatabase {
5730            db_name,
5731            if_not_exists: ine,
5732            location,
5733            managed_location,
5734            or_replace: false,
5735            transient: false,
5736            clone,
5737            data_retention_time_in_days: None,
5738            max_data_extension_time_in_days: None,
5739            external_volume: None,
5740            catalog: None,
5741            replace_invalid_characters: None,
5742            default_ddl_collation: None,
5743            storage_serialization_policy: None,
5744            comment: None,
5745            default_charset,
5746            default_collation,
5747            catalog_sync: None,
5748            catalog_sync_namespace_mode: None,
5749            catalog_sync_namespace_flatten_delimiter: None,
5750            with_tags: None,
5751            with_contacts: None,
5752        })
5753    }
5754
5755    /// Parse an optional `USING` clause for `CREATE FUNCTION`.
5756    pub fn parse_optional_create_function_using(
5757        &mut self,
5758    ) -> Result<Option<CreateFunctionUsing>, ParserError> {
5759        if !self.parse_keyword(Keyword::USING) {
5760            return Ok(None);
5761        };
5762        let keyword =
5763            self.expect_one_of_keywords(&[Keyword::JAR, Keyword::FILE, Keyword::ARCHIVE])?;
5764
5765        let uri = self.parse_literal_string()?;
5766
5767        match keyword {
5768            Keyword::JAR => Ok(Some(CreateFunctionUsing::Jar(uri))),
5769            Keyword::FILE => Ok(Some(CreateFunctionUsing::File(uri))),
5770            Keyword::ARCHIVE => Ok(Some(CreateFunctionUsing::Archive(uri))),
5771            _ => self.expected(
5772                "JAR, FILE or ARCHIVE, got {:?}",
5773                TokenWithSpan::wrap(Token::make_keyword(format!("{keyword:?}").as_str())),
5774            ),
5775        }
5776    }
5777
5778    /// Parse a `CREATE FUNCTION` statement.
5779    pub fn parse_create_function(
5780        &mut self,
5781        or_alter: bool,
5782        or_replace: bool,
5783        temporary: bool,
5784    ) -> Result<Statement, ParserError> {
5785        if dialect_of!(self is HiveDialect) {
5786            self.parse_hive_create_function(or_replace, temporary)
5787                .map(Into::into)
5788        } else if dialect_of!(self is PostgreSqlDialect | GenericDialect) {
5789            self.parse_postgres_create_function(or_replace, temporary)
5790                .map(Into::into)
5791        } else if dialect_of!(self is DuckDbDialect) {
5792            self.parse_create_macro(or_replace, temporary)
5793        } else if dialect_of!(self is BigQueryDialect) {
5794            self.parse_bigquery_create_function(or_replace, temporary)
5795                .map(Into::into)
5796        } else if dialect_of!(self is MsSqlDialect) {
5797            self.parse_mssql_create_function(or_alter, or_replace, temporary)
5798                .map(Into::into)
5799        } else {
5800            self.prev_token();
5801            self.expected_ref("an object type after CREATE", self.peek_token_ref())
5802        }
5803    }
5804
5805    /// Parse `CREATE FUNCTION` for [PostgreSQL]
5806    ///
5807    /// [PostgreSQL]: https://www.postgresql.org/docs/15/sql-createfunction.html
5808    fn parse_postgres_create_function(
5809        &mut self,
5810        or_replace: bool,
5811        temporary: bool,
5812    ) -> Result<CreateFunction, ParserError> {
5813        let name = self.parse_object_name(false)?;
5814
5815        self.expect_token(&Token::LParen)?;
5816        let args = if Token::RParen != self.peek_token_ref().token {
5817            self.parse_comma_separated(Parser::parse_function_arg)?
5818        } else {
5819            vec![]
5820        };
5821        self.expect_token(&Token::RParen)?;
5822
5823        let return_type = if self.parse_keyword(Keyword::RETURNS) {
5824            Some(self.parse_function_return_type()?)
5825        } else {
5826            None
5827        };
5828
5829        #[derive(Default)]
5830        struct Body {
5831            language: Option<Ident>,
5832            behavior: Option<FunctionBehavior>,
5833            function_body: Option<CreateFunctionBody>,
5834            called_on_null: Option<FunctionCalledOnNull>,
5835            parallel: Option<FunctionParallel>,
5836            security: Option<FunctionSecurity>,
5837        }
5838        let mut body = Body::default();
5839        let mut set_params: Vec<FunctionDefinitionSetParam> = Vec::new();
5840        loop {
5841            fn ensure_not_set<T>(field: &Option<T>, name: &str) -> Result<(), ParserError> {
5842                if field.is_some() {
5843                    return Err(ParserError::ParserError(format!(
5844                        "{name} specified more than once",
5845                    )));
5846                }
5847                Ok(())
5848            }
5849            if self.parse_keyword(Keyword::AS) {
5850                ensure_not_set(&body.function_body, "AS")?;
5851                body.function_body = Some(self.parse_create_function_body_string()?);
5852            } else if self.parse_keyword(Keyword::LANGUAGE) {
5853                ensure_not_set(&body.language, "LANGUAGE")?;
5854                body.language = Some(self.parse_identifier()?);
5855            } else if self.parse_keyword(Keyword::IMMUTABLE) {
5856                ensure_not_set(&body.behavior, "IMMUTABLE | STABLE | VOLATILE")?;
5857                body.behavior = Some(FunctionBehavior::Immutable);
5858            } else if self.parse_keyword(Keyword::STABLE) {
5859                ensure_not_set(&body.behavior, "IMMUTABLE | STABLE | VOLATILE")?;
5860                body.behavior = Some(FunctionBehavior::Stable);
5861            } else if self.parse_keyword(Keyword::VOLATILE) {
5862                ensure_not_set(&body.behavior, "IMMUTABLE | STABLE | VOLATILE")?;
5863                body.behavior = Some(FunctionBehavior::Volatile);
5864            } else if self.parse_keywords(&[
5865                Keyword::CALLED,
5866                Keyword::ON,
5867                Keyword::NULL,
5868                Keyword::INPUT,
5869            ]) {
5870                ensure_not_set(
5871                    &body.called_on_null,
5872                    "CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT",
5873                )?;
5874                body.called_on_null = Some(FunctionCalledOnNull::CalledOnNullInput);
5875            } else if self.parse_keywords(&[
5876                Keyword::RETURNS,
5877                Keyword::NULL,
5878                Keyword::ON,
5879                Keyword::NULL,
5880                Keyword::INPUT,
5881            ]) {
5882                ensure_not_set(
5883                    &body.called_on_null,
5884                    "CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT",
5885                )?;
5886                body.called_on_null = Some(FunctionCalledOnNull::ReturnsNullOnNullInput);
5887            } else if self.parse_keyword(Keyword::STRICT) {
5888                ensure_not_set(
5889                    &body.called_on_null,
5890                    "CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT",
5891                )?;
5892                body.called_on_null = Some(FunctionCalledOnNull::Strict);
5893            } else if self.parse_keyword(Keyword::PARALLEL) {
5894                ensure_not_set(&body.parallel, "PARALLEL { UNSAFE | RESTRICTED | SAFE }")?;
5895                if self.parse_keyword(Keyword::UNSAFE) {
5896                    body.parallel = Some(FunctionParallel::Unsafe);
5897                } else if self.parse_keyword(Keyword::RESTRICTED) {
5898                    body.parallel = Some(FunctionParallel::Restricted);
5899                } else if self.parse_keyword(Keyword::SAFE) {
5900                    body.parallel = Some(FunctionParallel::Safe);
5901                } else {
5902                    return self
5903                        .expected_ref("one of UNSAFE | RESTRICTED | SAFE", self.peek_token_ref());
5904                }
5905            } else if self.parse_keyword(Keyword::SECURITY) {
5906                ensure_not_set(&body.security, "SECURITY { DEFINER | INVOKER }")?;
5907                if self.parse_keyword(Keyword::DEFINER) {
5908                    body.security = Some(FunctionSecurity::Definer);
5909                } else if self.parse_keyword(Keyword::INVOKER) {
5910                    body.security = Some(FunctionSecurity::Invoker);
5911                } else {
5912                    return self.expected_ref("DEFINER or INVOKER", self.peek_token_ref());
5913                }
5914            } else if self.parse_keyword(Keyword::SET) {
5915                let name = self.parse_object_name(false)?;
5916                let value = if self.parse_keywords(&[Keyword::FROM, Keyword::CURRENT]) {
5917                    FunctionSetValue::FromCurrent
5918                } else {
5919                    if !self.consume_token(&Token::Eq) && !self.parse_keyword(Keyword::TO) {
5920                        return self.expected_ref("= or TO", self.peek_token_ref());
5921                    }
5922                    if self.parse_keyword(Keyword::DEFAULT) {
5923                        FunctionSetValue::Default
5924                    } else {
5925                        let values = self.parse_comma_separated(Parser::parse_expr)?;
5926                        FunctionSetValue::Values(values)
5927                    }
5928                };
5929                set_params.push(FunctionDefinitionSetParam { name, value });
5930            } else if self.parse_keyword(Keyword::RETURN) {
5931                ensure_not_set(&body.function_body, "RETURN")?;
5932                body.function_body = Some(CreateFunctionBody::Return(self.parse_expr()?));
5933            } else {
5934                break;
5935            }
5936        }
5937
5938        Ok(CreateFunction {
5939            or_alter: false,
5940            or_replace,
5941            temporary,
5942            name,
5943            args: Some(args),
5944            return_type,
5945            behavior: body.behavior,
5946            called_on_null: body.called_on_null,
5947            parallel: body.parallel,
5948            security: body.security,
5949            set_params,
5950            language: body.language,
5951            function_body: body.function_body,
5952            if_not_exists: false,
5953            using: None,
5954            determinism_specifier: None,
5955            options: None,
5956            remote_connection: None,
5957        })
5958    }
5959
5960    /// Parse `CREATE FUNCTION` for [Hive]
5961    ///
5962    /// [Hive]: https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-Create/Drop/ReloadFunction
5963    fn parse_hive_create_function(
5964        &mut self,
5965        or_replace: bool,
5966        temporary: bool,
5967    ) -> Result<CreateFunction, ParserError> {
5968        let name = self.parse_object_name(false)?;
5969        self.expect_keyword_is(Keyword::AS)?;
5970
5971        let body = self.parse_create_function_body_string()?;
5972        let using = self.parse_optional_create_function_using()?;
5973
5974        Ok(CreateFunction {
5975            or_alter: false,
5976            or_replace,
5977            temporary,
5978            name,
5979            function_body: Some(body),
5980            using,
5981            if_not_exists: false,
5982            args: None,
5983            return_type: None,
5984            behavior: None,
5985            called_on_null: None,
5986            parallel: None,
5987            security: None,
5988            set_params: vec![],
5989            language: None,
5990            determinism_specifier: None,
5991            options: None,
5992            remote_connection: None,
5993        })
5994    }
5995
5996    /// Parse `CREATE FUNCTION` for [BigQuery]
5997    ///
5998    /// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_function_statement
5999    fn parse_bigquery_create_function(
6000        &mut self,
6001        or_replace: bool,
6002        temporary: bool,
6003    ) -> Result<CreateFunction, ParserError> {
6004        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
6005        let (name, args) = self.parse_create_function_name_and_params()?;
6006
6007        let return_type = if self.parse_keyword(Keyword::RETURNS) {
6008            Some(self.parse_function_return_type()?)
6009        } else {
6010            None
6011        };
6012
6013        let determinism_specifier = if self.parse_keyword(Keyword::DETERMINISTIC) {
6014            Some(FunctionDeterminismSpecifier::Deterministic)
6015        } else if self.parse_keywords(&[Keyword::NOT, Keyword::DETERMINISTIC]) {
6016            Some(FunctionDeterminismSpecifier::NotDeterministic)
6017        } else {
6018            None
6019        };
6020
6021        let language = if self.parse_keyword(Keyword::LANGUAGE) {
6022            Some(self.parse_identifier()?)
6023        } else {
6024            None
6025        };
6026
6027        let remote_connection =
6028            if self.parse_keywords(&[Keyword::REMOTE, Keyword::WITH, Keyword::CONNECTION]) {
6029                Some(self.parse_object_name(false)?)
6030            } else {
6031                None
6032            };
6033
6034        // `OPTIONS` may come before of after the function body but
6035        // may be specified at most once.
6036        let mut options = self.maybe_parse_options(Keyword::OPTIONS)?;
6037
6038        let function_body = if remote_connection.is_none() {
6039            self.expect_keyword_is(Keyword::AS)?;
6040            let expr = self.parse_expr()?;
6041            if options.is_none() {
6042                options = self.maybe_parse_options(Keyword::OPTIONS)?;
6043                Some(CreateFunctionBody::AsBeforeOptions {
6044                    body: expr,
6045                    link_symbol: None,
6046                })
6047            } else {
6048                Some(CreateFunctionBody::AsAfterOptions(expr))
6049            }
6050        } else {
6051            None
6052        };
6053
6054        Ok(CreateFunction {
6055            or_alter: false,
6056            or_replace,
6057            temporary,
6058            if_not_exists,
6059            name,
6060            args: Some(args),
6061            return_type,
6062            function_body,
6063            language,
6064            determinism_specifier,
6065            options,
6066            remote_connection,
6067            using: None,
6068            behavior: None,
6069            called_on_null: None,
6070            parallel: None,
6071            security: None,
6072            set_params: vec![],
6073        })
6074    }
6075
6076    /// Parse `CREATE FUNCTION` for [MsSql]
6077    ///
6078    /// [MsSql]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql
6079    fn parse_mssql_create_function(
6080        &mut self,
6081        or_alter: bool,
6082        or_replace: bool,
6083        temporary: bool,
6084    ) -> Result<CreateFunction, ParserError> {
6085        let (name, args) = self.parse_create_function_name_and_params()?;
6086
6087        self.expect_keyword(Keyword::RETURNS)?;
6088
6089        let return_table = self.maybe_parse(|p| {
6090            let return_table_name = p.parse_identifier()?;
6091
6092            p.expect_keyword_is(Keyword::TABLE)?;
6093            p.prev_token();
6094
6095            let table_column_defs = match p.parse_data_type()? {
6096                DataType::Table(Some(table_column_defs)) if !table_column_defs.is_empty() => {
6097                    table_column_defs
6098                }
6099                _ => parser_err!(
6100                    "Expected table column definitions after TABLE keyword",
6101                    p.peek_token_ref().span.start
6102                )?,
6103            };
6104
6105            Ok(DataType::NamedTable {
6106                name: ObjectName(vec![ObjectNamePart::Identifier(return_table_name)]),
6107                columns: table_column_defs,
6108            })
6109        })?;
6110
6111        let data_type = match return_table {
6112            Some(table_type) => table_type,
6113            None => self.parse_data_type()?,
6114        };
6115        let return_type = Some(FunctionReturnType::DataType(data_type));
6116
6117        let _ = self.parse_keyword(Keyword::AS);
6118
6119        let function_body = if self.peek_keyword(Keyword::BEGIN) {
6120            let begin_token = self.expect_keyword(Keyword::BEGIN)?;
6121            let statements = self.parse_statement_list(&[Keyword::END])?;
6122            let end_token = self.expect_keyword(Keyword::END)?;
6123
6124            Some(CreateFunctionBody::AsBeginEnd(BeginEndStatements {
6125                begin_token: AttachedToken(begin_token),
6126                statements,
6127                end_token: AttachedToken(end_token),
6128            }))
6129        } else if self.parse_keyword(Keyword::RETURN) {
6130            if self.peek_token_ref().token == Token::LParen {
6131                Some(CreateFunctionBody::AsReturnExpr(self.parse_expr()?))
6132            } else if self.peek_keyword(Keyword::SELECT) {
6133                let select = self.parse_select()?;
6134                Some(CreateFunctionBody::AsReturnSelect(select))
6135            } else {
6136                parser_err!(
6137                    "Expected a subquery (or bare SELECT statement) after RETURN",
6138                    self.peek_token_ref().span.start
6139                )?
6140            }
6141        } else {
6142            parser_err!("Unparsable function body", self.peek_token_ref().span.start)?
6143        };
6144
6145        Ok(CreateFunction {
6146            or_alter,
6147            or_replace,
6148            temporary,
6149            if_not_exists: false,
6150            name,
6151            args: Some(args),
6152            return_type,
6153            function_body,
6154            language: None,
6155            determinism_specifier: None,
6156            options: None,
6157            remote_connection: None,
6158            using: None,
6159            behavior: None,
6160            called_on_null: None,
6161            parallel: None,
6162            security: None,
6163            set_params: vec![],
6164        })
6165    }
6166
6167    fn parse_function_return_type(&mut self) -> Result<FunctionReturnType, ParserError> {
6168        if self.parse_keyword(Keyword::SETOF) {
6169            Ok(FunctionReturnType::SetOf(self.parse_data_type()?))
6170        } else {
6171            Ok(FunctionReturnType::DataType(self.parse_data_type()?))
6172        }
6173    }
6174
6175    fn parse_create_function_name_and_params(
6176        &mut self,
6177    ) -> Result<(ObjectName, Vec<OperateFunctionArg>), ParserError> {
6178        let name = self.parse_object_name(false)?;
6179        let parse_function_param =
6180            |parser: &mut Parser| -> Result<OperateFunctionArg, ParserError> {
6181                let name = parser.parse_identifier()?;
6182                let data_type = parser.parse_data_type()?;
6183                let default_expr = if parser.consume_token(&Token::Eq) {
6184                    Some(parser.parse_expr()?)
6185                } else {
6186                    None
6187                };
6188
6189                Ok(OperateFunctionArg {
6190                    mode: None,
6191                    name: Some(name),
6192                    data_type,
6193                    default_expr,
6194                })
6195            };
6196        self.expect_token(&Token::LParen)?;
6197        let args = self.parse_comma_separated0(parse_function_param, Token::RParen)?;
6198        self.expect_token(&Token::RParen)?;
6199        Ok((name, args))
6200    }
6201
6202    fn parse_function_arg(&mut self) -> Result<OperateFunctionArg, ParserError> {
6203        let mode = if self.parse_keyword(Keyword::IN) {
6204            Some(ArgMode::In)
6205        } else if self.parse_keyword(Keyword::OUT) {
6206            Some(ArgMode::Out)
6207        } else if self.parse_keyword(Keyword::INOUT) {
6208            Some(ArgMode::InOut)
6209        } else if self.parse_keyword(Keyword::VARIADIC) {
6210            Some(ArgMode::Variadic)
6211        } else {
6212            None
6213        };
6214
6215        // parse: [ argname ] argtype
6216        let mut name = None;
6217        let mut data_type = self.parse_data_type()?;
6218
6219        // To check whether the first token is a name or a type, we need to
6220        // peek the next token, which if it is another type keyword, then the
6221        // first token is a name and not a type in itself.
6222        let data_type_idx = self.get_current_index();
6223
6224        // DEFAULT will be parsed as `DataType::Custom`, which is undesirable in this context
6225        fn parse_data_type_no_default(parser: &mut Parser) -> Result<DataType, ParserError> {
6226            if parser.peek_keyword(Keyword::DEFAULT) {
6227                // This dummy error is ignored in `maybe_parse`
6228                parser_err!(
6229                    "The DEFAULT keyword is not a type",
6230                    parser.peek_token_ref().span.start
6231                )
6232            } else {
6233                parser.parse_data_type()
6234            }
6235        }
6236
6237        if let Some(next_data_type) = self.maybe_parse(parse_data_type_no_default)? {
6238            let token = self.token_at(data_type_idx);
6239
6240            // We ensure that the token is a `Word` token, and not other special tokens.
6241            if !matches!(token.token, Token::Word(_)) {
6242                return self.expected("a name or type", token.clone());
6243            }
6244
6245            name = Some(Ident::new(token.to_string()));
6246            data_type = next_data_type;
6247        }
6248
6249        let default_expr = if self.parse_keyword(Keyword::DEFAULT) || self.consume_token(&Token::Eq)
6250        {
6251            Some(self.parse_expr()?)
6252        } else {
6253            None
6254        };
6255        Ok(OperateFunctionArg {
6256            mode,
6257            name,
6258            data_type,
6259            default_expr,
6260        })
6261    }
6262
6263    fn parse_aggregate_function_arg(&mut self) -> Result<OperateFunctionArg, ParserError> {
6264        let mode = if self.parse_keyword(Keyword::IN) {
6265            Some(ArgMode::In)
6266        } else {
6267            if self
6268                .peek_one_of_keywords(&[Keyword::OUT, Keyword::INOUT, Keyword::VARIADIC])
6269                .is_some()
6270            {
6271                return self.expected_ref(
6272                    "IN or argument type in aggregate signature",
6273                    self.peek_token_ref(),
6274                );
6275            }
6276            None
6277        };
6278
6279        // Parse: [ argname ] argtype, but do not consume ORDER from
6280        // `... argtype ORDER BY ...` as a type-name disambiguator.
6281        let mut name = None;
6282        let mut data_type = self.parse_data_type()?;
6283        let data_type_idx = self.get_current_index();
6284
6285        fn parse_data_type_for_aggregate_arg(parser: &mut Parser) -> Result<DataType, ParserError> {
6286            if parser.peek_keyword(Keyword::DEFAULT)
6287                || parser.peek_keyword(Keyword::ORDER)
6288                || parser.peek_token_ref().token == Token::Comma
6289                || parser.peek_token_ref().token == Token::RParen
6290            {
6291                // Dummy error ignored by maybe_parse
6292                parser_err!(
6293                    "The current token cannot start an aggregate argument type",
6294                    parser.peek_token_ref().span.start
6295                )
6296            } else {
6297                parser.parse_data_type()
6298            }
6299        }
6300
6301        if let Some(next_data_type) = self.maybe_parse(parse_data_type_for_aggregate_arg)? {
6302            let token = self.token_at(data_type_idx);
6303            if !matches!(token.token, Token::Word(_)) {
6304                return self.expected("a name or type", token.clone());
6305            }
6306
6307            name = Some(Ident::new(token.to_string()));
6308            data_type = next_data_type;
6309        }
6310
6311        if self.peek_keyword(Keyword::DEFAULT) || self.peek_token_ref().token == Token::Eq {
6312            return self.expected_ref(
6313                "',' or ')' or ORDER BY after aggregate argument type",
6314                self.peek_token_ref(),
6315            );
6316        }
6317
6318        Ok(OperateFunctionArg {
6319            mode,
6320            name,
6321            data_type,
6322            default_expr: None,
6323        })
6324    }
6325
6326    /// Parse statements of the DropTrigger type such as:
6327    ///
6328    /// ```sql
6329    /// DROP TRIGGER [ IF EXISTS ] name ON table_name [ CASCADE | RESTRICT ]
6330    /// ```
6331    pub fn parse_drop_trigger(&mut self) -> Result<DropTrigger, ParserError> {
6332        if !dialect_of!(self is PostgreSqlDialect | SQLiteDialect | GenericDialect | MySqlDialect | MsSqlDialect)
6333        {
6334            self.prev_token();
6335            return self.expected_ref("an object type after DROP", self.peek_token_ref());
6336        }
6337        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
6338        let trigger_name = self.parse_object_name(false)?;
6339        let table_name = if self.parse_keyword(Keyword::ON) {
6340            Some(self.parse_object_name(false)?)
6341        } else {
6342            None
6343        };
6344        let option = match self.parse_one_of_keywords(&[Keyword::CASCADE, Keyword::RESTRICT]) {
6345            Some(Keyword::CASCADE) => Some(ReferentialAction::Cascade),
6346            Some(Keyword::RESTRICT) => Some(ReferentialAction::Restrict),
6347            Some(unexpected_keyword) => return Err(ParserError::ParserError(
6348                format!("Internal parser error: expected any of {{CASCADE, RESTRICT}}, got {unexpected_keyword:?}"),
6349            )),
6350            None => None,
6351        };
6352        Ok(DropTrigger {
6353            if_exists,
6354            trigger_name,
6355            table_name,
6356            option,
6357        })
6358    }
6359
6360    /// Parse a `CREATE TRIGGER` statement.
6361    pub fn parse_create_trigger(
6362        &mut self,
6363        temporary: bool,
6364        or_alter: bool,
6365        or_replace: bool,
6366        is_constraint: bool,
6367    ) -> Result<CreateTrigger, ParserError> {
6368        if !dialect_of!(self is PostgreSqlDialect | SQLiteDialect | GenericDialect | MySqlDialect | MsSqlDialect)
6369        {
6370            self.prev_token();
6371            return self.expected_ref("an object type after CREATE", self.peek_token_ref());
6372        }
6373
6374        let name = self.parse_object_name(false)?;
6375        let period = self.maybe_parse(|parser| parser.parse_trigger_period())?;
6376
6377        let events = self.parse_keyword_separated(Keyword::OR, Parser::parse_trigger_event)?;
6378        self.expect_keyword_is(Keyword::ON)?;
6379        let table_name = self.parse_object_name(false)?;
6380
6381        let referenced_table_name = if self.parse_keyword(Keyword::FROM) {
6382            self.parse_object_name(true).ok()
6383        } else {
6384            None
6385        };
6386
6387        let characteristics = self.parse_constraint_characteristics()?;
6388
6389        let mut referencing = vec![];
6390        if self.parse_keyword(Keyword::REFERENCING) {
6391            while let Some(refer) = self.parse_trigger_referencing()? {
6392                referencing.push(refer);
6393            }
6394        }
6395
6396        let trigger_object = if self.parse_keyword(Keyword::FOR) {
6397            let include_each = self.parse_keyword(Keyword::EACH);
6398            let trigger_object =
6399                match self.expect_one_of_keywords(&[Keyword::ROW, Keyword::STATEMENT])? {
6400                    Keyword::ROW => TriggerObject::Row,
6401                    Keyword::STATEMENT => TriggerObject::Statement,
6402                    unexpected_keyword => return Err(ParserError::ParserError(
6403                        format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in ROW/STATEMENT"),
6404                    )),
6405                };
6406
6407            Some(if include_each {
6408                TriggerObjectKind::ForEach(trigger_object)
6409            } else {
6410                TriggerObjectKind::For(trigger_object)
6411            })
6412        } else {
6413            let _ = self.parse_keyword(Keyword::FOR);
6414
6415            None
6416        };
6417
6418        let condition = self
6419            .parse_keyword(Keyword::WHEN)
6420            .then(|| self.parse_expr())
6421            .transpose()?;
6422
6423        let mut exec_body = None;
6424        let mut statements = None;
6425        if self.parse_keyword(Keyword::EXECUTE) {
6426            exec_body = Some(self.parse_trigger_exec_body()?);
6427        } else {
6428            statements = Some(self.parse_conditional_statements(&[Keyword::END])?);
6429        }
6430
6431        Ok(CreateTrigger {
6432            or_alter,
6433            temporary,
6434            or_replace,
6435            is_constraint,
6436            name,
6437            period,
6438            period_before_table: true,
6439            events,
6440            table_name,
6441            referenced_table_name,
6442            referencing,
6443            trigger_object,
6444            condition,
6445            exec_body,
6446            statements_as: false,
6447            statements,
6448            characteristics,
6449        })
6450    }
6451
6452    /// Parse the period part of a trigger (`BEFORE`, `AFTER`, etc.).
6453    pub fn parse_trigger_period(&mut self) -> Result<TriggerPeriod, ParserError> {
6454        Ok(
6455            match self.expect_one_of_keywords(&[
6456                Keyword::FOR,
6457                Keyword::BEFORE,
6458                Keyword::AFTER,
6459                Keyword::INSTEAD,
6460            ])? {
6461                Keyword::FOR => TriggerPeriod::For,
6462                Keyword::BEFORE => TriggerPeriod::Before,
6463                Keyword::AFTER => TriggerPeriod::After,
6464                Keyword::INSTEAD => self
6465                    .expect_keyword_is(Keyword::OF)
6466                    .map(|_| TriggerPeriod::InsteadOf)?,
6467                unexpected_keyword => return Err(ParserError::ParserError(
6468                    format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in trigger period"),
6469                )),
6470            },
6471        )
6472    }
6473
6474    /// Parse the event part of a trigger (`INSERT`, `UPDATE`, etc.).
6475    pub fn parse_trigger_event(&mut self) -> Result<TriggerEvent, ParserError> {
6476        Ok(
6477            match self.expect_one_of_keywords(&[
6478                Keyword::INSERT,
6479                Keyword::UPDATE,
6480                Keyword::DELETE,
6481                Keyword::TRUNCATE,
6482            ])? {
6483                Keyword::INSERT => TriggerEvent::Insert,
6484                Keyword::UPDATE => {
6485                    if self.parse_keyword(Keyword::OF) {
6486                        let cols = self.parse_comma_separated(Parser::parse_identifier)?;
6487                        TriggerEvent::Update(cols)
6488                    } else {
6489                        TriggerEvent::Update(vec![])
6490                    }
6491                }
6492                Keyword::DELETE => TriggerEvent::Delete,
6493                Keyword::TRUNCATE => TriggerEvent::Truncate,
6494                unexpected_keyword => return Err(ParserError::ParserError(
6495                    format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in trigger event"),
6496                )),
6497            },
6498        )
6499    }
6500
6501    /// Parse the `REFERENCING` clause of a trigger.
6502    pub fn parse_trigger_referencing(&mut self) -> Result<Option<TriggerReferencing>, ParserError> {
6503        let refer_type = match self.parse_one_of_keywords(&[Keyword::OLD, Keyword::NEW]) {
6504            Some(Keyword::OLD) if self.parse_keyword(Keyword::TABLE) => {
6505                TriggerReferencingType::OldTable
6506            }
6507            Some(Keyword::NEW) if self.parse_keyword(Keyword::TABLE) => {
6508                TriggerReferencingType::NewTable
6509            }
6510            _ => {
6511                return Ok(None);
6512            }
6513        };
6514
6515        let is_as = self.parse_keyword(Keyword::AS);
6516        let transition_relation_name = self.parse_object_name(false)?;
6517        Ok(Some(TriggerReferencing {
6518            refer_type,
6519            is_as,
6520            transition_relation_name,
6521        }))
6522    }
6523
6524    /// Parse the execution body of a trigger (`FUNCTION` or `PROCEDURE`).
6525    pub fn parse_trigger_exec_body(&mut self) -> Result<TriggerExecBody, ParserError> {
6526        Ok(TriggerExecBody {
6527            exec_type: match self
6528                .expect_one_of_keywords(&[Keyword::FUNCTION, Keyword::PROCEDURE])?
6529            {
6530                Keyword::FUNCTION => TriggerExecBodyType::Function,
6531                Keyword::PROCEDURE => TriggerExecBodyType::Procedure,
6532                unexpected_keyword => return Err(ParserError::ParserError(
6533                    format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in trigger exec body"),
6534                )),
6535            },
6536            func_desc: self.parse_function_desc()?,
6537        })
6538    }
6539
6540    /// Parse a `CREATE MACRO` statement.
6541    pub fn parse_create_macro(
6542        &mut self,
6543        or_replace: bool,
6544        temporary: bool,
6545    ) -> Result<Statement, ParserError> {
6546        if dialect_of!(self is DuckDbDialect |  GenericDialect) {
6547            let name = self.parse_object_name(false)?;
6548            self.expect_token(&Token::LParen)?;
6549            let args = if self.consume_token(&Token::RParen) {
6550                self.prev_token();
6551                None
6552            } else {
6553                Some(self.parse_comma_separated(Parser::parse_macro_arg)?)
6554            };
6555
6556            self.expect_token(&Token::RParen)?;
6557            self.expect_keyword_is(Keyword::AS)?;
6558
6559            Ok(Statement::CreateMacro {
6560                or_replace,
6561                temporary,
6562                name,
6563                args,
6564                definition: if self.parse_keyword(Keyword::TABLE) {
6565                    MacroDefinition::Table(self.parse_query()?)
6566                } else {
6567                    MacroDefinition::Expr(self.parse_expr()?)
6568                },
6569            })
6570        } else {
6571            self.prev_token();
6572            self.expected_ref("an object type after CREATE", self.peek_token_ref())
6573        }
6574    }
6575
6576    fn parse_macro_arg(&mut self) -> Result<MacroArg, ParserError> {
6577        let name = self.parse_identifier()?;
6578
6579        let default_expr =
6580            if self.consume_token(&Token::Assignment) || self.consume_token(&Token::RArrow) {
6581                Some(self.parse_expr()?)
6582            } else {
6583                None
6584            };
6585        Ok(MacroArg { name, default_expr })
6586    }
6587
6588    /// Parse a `CREATE EXTERNAL TABLE` statement.
6589    pub fn parse_create_external_table(
6590        &mut self,
6591        or_replace: bool,
6592    ) -> Result<CreateTable, ParserError> {
6593        self.expect_keyword_is(Keyword::TABLE)?;
6594        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
6595        let table_name = self.parse_object_name(false)?;
6596        let (columns, constraints) = self.parse_columns()?;
6597
6598        let hive_distribution = self.parse_hive_distribution()?;
6599        let hive_formats = self.parse_hive_formats()?;
6600
6601        let file_format = if let Some(ref hf) = hive_formats {
6602            if let Some(ref ff) = hf.storage {
6603                match ff {
6604                    HiveIOFormat::FileFormat { format } => Some(*format),
6605                    _ => None,
6606                }
6607            } else {
6608                None
6609            }
6610        } else {
6611            None
6612        };
6613        let location = hive_formats.as_ref().and_then(|hf| hf.location.clone());
6614
6615        let with_connection = if self.parse_keywords(&[Keyword::WITH, Keyword::CONNECTION]) {
6616            Some(self.parse_object_name(false)?)
6617        } else {
6618            None
6619        };
6620        let table_properties = self.parse_options(Keyword::TBLPROPERTIES)?;
6621        let table_options = if !table_properties.is_empty() {
6622            CreateTableOptions::TableProperties(table_properties)
6623        } else if let Some(options) = self.maybe_parse_options(Keyword::OPTIONS)? {
6624            CreateTableOptions::Options(options)
6625        } else {
6626            CreateTableOptions::None
6627        };
6628        Ok(CreateTableBuilder::new(table_name)
6629            .columns(columns)
6630            .constraints(constraints)
6631            .hive_distribution(hive_distribution)
6632            .hive_formats(hive_formats)
6633            .table_options(table_options)
6634            .with_connection(with_connection)
6635            .or_replace(or_replace)
6636            .if_not_exists(if_not_exists)
6637            .external(true)
6638            .file_format(file_format)
6639            .location(location)
6640            .build())
6641    }
6642
6643    /// Parse `CREATE SNAPSHOT TABLE` statement.
6644    ///
6645    /// <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_snapshot_table_statement>
6646    pub fn parse_create_snapshot_table(&mut self) -> Result<CreateTable, ParserError> {
6647        self.expect_keywords(&[Keyword::SNAPSHOT, Keyword::TABLE])?;
6648        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
6649        let table_name = self.parse_object_name(true)?;
6650
6651        self.expect_keyword_is(Keyword::CLONE)?;
6652        let clone = Some(self.parse_object_name(true)?);
6653
6654        let version =
6655            if self.parse_keywords(&[Keyword::FOR, Keyword::SYSTEM_TIME, Keyword::AS, Keyword::OF])
6656            {
6657                Some(TableVersion::ForSystemTimeAsOf(self.parse_expr()?))
6658            } else {
6659                None
6660            };
6661
6662        let table_options = if let Some(options) = self.maybe_parse_options(Keyword::OPTIONS)? {
6663            CreateTableOptions::Options(options)
6664        } else {
6665            CreateTableOptions::None
6666        };
6667
6668        Ok(CreateTableBuilder::new(table_name)
6669            .snapshot(true)
6670            .if_not_exists(if_not_exists)
6671            .clone_clause(clone)
6672            .version(version)
6673            .table_options(table_options)
6674            .build())
6675    }
6676
6677    /// Parse a file format for external tables.
6678    pub fn parse_file_format(&mut self) -> Result<FileFormat, ParserError> {
6679        let next_token = self.next_token();
6680        match &next_token.token {
6681            Token::Word(w) => match w.keyword {
6682                Keyword::AVRO => Ok(FileFormat::AVRO),
6683                Keyword::JSONFILE => Ok(FileFormat::JSONFILE),
6684                Keyword::ORC => Ok(FileFormat::ORC),
6685                Keyword::PARQUET => Ok(FileFormat::PARQUET),
6686                Keyword::RCFILE => Ok(FileFormat::RCFILE),
6687                Keyword::SEQUENCEFILE => Ok(FileFormat::SEQUENCEFILE),
6688                Keyword::TEXTFILE => Ok(FileFormat::TEXTFILE),
6689                _ => self.expected("fileformat", next_token),
6690            },
6691            _ => self.expected("fileformat", next_token),
6692        }
6693    }
6694
6695    fn parse_analyze_format_kind(&mut self) -> Result<AnalyzeFormatKind, ParserError> {
6696        if self.consume_token(&Token::Eq) {
6697            Ok(AnalyzeFormatKind::Assignment(self.parse_analyze_format()?))
6698        } else {
6699            Ok(AnalyzeFormatKind::Keyword(self.parse_analyze_format()?))
6700        }
6701    }
6702
6703    /// Parse an `ANALYZE FORMAT`.
6704    pub fn parse_analyze_format(&mut self) -> Result<AnalyzeFormat, ParserError> {
6705        let next_token = self.next_token();
6706        match &next_token.token {
6707            Token::Word(w) => match w.keyword {
6708                Keyword::TEXT => Ok(AnalyzeFormat::TEXT),
6709                Keyword::GRAPHVIZ => Ok(AnalyzeFormat::GRAPHVIZ),
6710                Keyword::JSON => Ok(AnalyzeFormat::JSON),
6711                Keyword::TREE => Ok(AnalyzeFormat::TREE),
6712                _ => self.expected("fileformat", next_token),
6713            },
6714            _ => self.expected("fileformat", next_token),
6715        }
6716    }
6717
6718    /// Parse a `CREATE VIEW` statement.
6719    pub fn parse_create_view(
6720        &mut self,
6721        or_alter: bool,
6722        or_replace: bool,
6723        temporary: bool,
6724        create_view_params: Option<CreateViewParams>,
6725    ) -> Result<CreateView, ParserError> {
6726        let secure = self.parse_keyword(Keyword::SECURE);
6727        let materialized = self.parse_keyword(Keyword::MATERIALIZED);
6728        self.expect_keyword_is(Keyword::VIEW)?;
6729        let allow_unquoted_hyphen = dialect_of!(self is BigQueryDialect);
6730        // Tries to parse IF NOT EXISTS either before name or after name
6731        // Name before IF NOT EXISTS is supported by snowflake but undocumented
6732        let if_not_exists_first =
6733            self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
6734        let name = self.parse_object_name(allow_unquoted_hyphen)?;
6735        let name_before_not_exists = !if_not_exists_first
6736            && self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
6737        let if_not_exists = if_not_exists_first || name_before_not_exists;
6738        let mut copy_grants = self.parse_keywords(&[Keyword::COPY, Keyword::GRANTS]);
6739        // Many dialects support `OR ALTER` right after `CREATE`, but we don't (yet).
6740        // ANSI SQL and Postgres support RECURSIVE here, but we don't support it either.
6741        let columns = self.parse_view_columns()?;
6742        // Snowflake also documents `COPY GRANTS` *after* the column list; accept
6743        // either position, but not both.
6744        // <https://docs.snowflake.com/en/sql-reference/sql/create-view#syntax>
6745        if !copy_grants {
6746            copy_grants = self.parse_keywords(&[Keyword::COPY, Keyword::GRANTS]);
6747        }
6748        let mut options = CreateTableOptions::None;
6749        let with_options = self.parse_options(Keyword::WITH)?;
6750        if !with_options.is_empty() {
6751            options = CreateTableOptions::With(with_options);
6752        }
6753
6754        let cluster_by = if self.parse_keyword(Keyword::CLUSTER) {
6755            self.expect_keyword_is(Keyword::BY)?;
6756            self.parse_parenthesized_column_list(Optional, false)?
6757        } else {
6758            vec![]
6759        };
6760
6761        if dialect_of!(self is BigQueryDialect | GenericDialect) {
6762            if let Some(opts) = self.maybe_parse_options(Keyword::OPTIONS)? {
6763                if !opts.is_empty() {
6764                    options = CreateTableOptions::Options(opts);
6765                }
6766            };
6767        }
6768
6769        let to = if dialect_of!(self is ClickHouseDialect | GenericDialect)
6770            && self.parse_keyword(Keyword::TO)
6771        {
6772            Some(self.parse_object_name(false)?)
6773        } else {
6774            None
6775        };
6776
6777        let comment = if self.dialect.supports_create_view_comment_syntax()
6778            && self.parse_keyword(Keyword::COMMENT)
6779        {
6780            self.expect_token(&Token::Eq)?;
6781            Some(self.parse_comment_value()?)
6782        } else {
6783            None
6784        };
6785
6786        self.expect_keyword_is(Keyword::AS)?;
6787        let query = self.parse_query()?;
6788        // Optional `WITH [ CASCADED | LOCAL ] CHECK OPTION` is widely supported here.
6789
6790        let with_no_schema_binding = dialect_of!(self is RedshiftSqlDialect | GenericDialect)
6791            && self.parse_keywords(&[
6792                Keyword::WITH,
6793                Keyword::NO,
6794                Keyword::SCHEMA,
6795                Keyword::BINDING,
6796            ]);
6797
6798        Ok(CreateView {
6799            or_alter,
6800            name,
6801            columns,
6802            query,
6803            materialized,
6804            secure,
6805            or_replace,
6806            options,
6807            cluster_by,
6808            comment,
6809            with_no_schema_binding,
6810            if_not_exists,
6811            temporary,
6812            copy_grants,
6813            to,
6814            params: create_view_params,
6815            name_before_not_exists,
6816        })
6817    }
6818
6819    /// Parse optional parameters for the `CREATE VIEW` statement supported by [MySQL].
6820    ///
6821    /// [MySQL]: https://dev.mysql.com/doc/refman/9.1/en/create-view.html
6822    fn parse_create_view_params(&mut self) -> Result<Option<CreateViewParams>, ParserError> {
6823        let algorithm = if self.parse_keyword(Keyword::ALGORITHM) {
6824            self.expect_token(&Token::Eq)?;
6825            Some(
6826                match self.expect_one_of_keywords(&[
6827                    Keyword::UNDEFINED,
6828                    Keyword::MERGE,
6829                    Keyword::TEMPTABLE,
6830                ])? {
6831                    Keyword::UNDEFINED => CreateViewAlgorithm::Undefined,
6832                    Keyword::MERGE => CreateViewAlgorithm::Merge,
6833                    Keyword::TEMPTABLE => CreateViewAlgorithm::TempTable,
6834                    _ => {
6835                        self.prev_token();
6836                        let found = self.next_token();
6837                        return self
6838                            .expected("UNDEFINED or MERGE or TEMPTABLE after ALGORITHM =", found);
6839                    }
6840                },
6841            )
6842        } else {
6843            None
6844        };
6845        let definer = if self.parse_keyword(Keyword::DEFINER) {
6846            self.expect_token(&Token::Eq)?;
6847            Some(self.parse_grantee_name()?)
6848        } else {
6849            None
6850        };
6851        let security = if self.parse_keywords(&[Keyword::SQL, Keyword::SECURITY]) {
6852            Some(
6853                match self.expect_one_of_keywords(&[Keyword::DEFINER, Keyword::INVOKER])? {
6854                    Keyword::DEFINER => CreateViewSecurity::Definer,
6855                    Keyword::INVOKER => CreateViewSecurity::Invoker,
6856                    _ => {
6857                        self.prev_token();
6858                        let found = self.next_token();
6859                        return self.expected("DEFINER or INVOKER after SQL SECURITY", found);
6860                    }
6861                },
6862            )
6863        } else {
6864            None
6865        };
6866        if algorithm.is_some() || definer.is_some() || security.is_some() {
6867            Ok(Some(CreateViewParams {
6868                algorithm,
6869                definer,
6870                security,
6871            }))
6872        } else {
6873            Ok(None)
6874        }
6875    }
6876
6877    /// Parse a `CREATE ROLE` statement.
6878    pub fn parse_create_role(&mut self) -> Result<CreateRole, ParserError> {
6879        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
6880        let names = self.parse_comma_separated(|p| p.parse_object_name(false))?;
6881
6882        let _ = self.parse_keyword(Keyword::WITH); // [ WITH ]
6883
6884        let optional_keywords = if dialect_of!(self is MsSqlDialect) {
6885            vec![Keyword::AUTHORIZATION]
6886        } else if dialect_of!(self is PostgreSqlDialect) {
6887            vec![
6888                Keyword::LOGIN,
6889                Keyword::NOLOGIN,
6890                Keyword::INHERIT,
6891                Keyword::NOINHERIT,
6892                Keyword::BYPASSRLS,
6893                Keyword::NOBYPASSRLS,
6894                Keyword::PASSWORD,
6895                Keyword::CREATEDB,
6896                Keyword::NOCREATEDB,
6897                Keyword::CREATEROLE,
6898                Keyword::NOCREATEROLE,
6899                Keyword::SUPERUSER,
6900                Keyword::NOSUPERUSER,
6901                Keyword::REPLICATION,
6902                Keyword::NOREPLICATION,
6903                Keyword::CONNECTION,
6904                Keyword::VALID,
6905                Keyword::IN,
6906                Keyword::ROLE,
6907                Keyword::ADMIN,
6908                Keyword::USER,
6909            ]
6910        } else {
6911            vec![]
6912        };
6913
6914        // MSSQL
6915        let mut authorization_owner = None;
6916        // Postgres
6917        let mut login = None;
6918        let mut inherit = None;
6919        let mut bypassrls = None;
6920        let mut password = None;
6921        let mut create_db = None;
6922        let mut create_role = None;
6923        let mut superuser = None;
6924        let mut replication = None;
6925        let mut connection_limit = None;
6926        let mut valid_until = None;
6927        let mut in_role = vec![];
6928        let mut in_group = vec![];
6929        let mut role = vec![];
6930        let mut user = vec![];
6931        let mut admin = vec![];
6932
6933        while let Some(keyword) = self.parse_one_of_keywords(&optional_keywords) {
6934            let loc = self
6935                .tokens
6936                .get(self.index - 1)
6937                .map_or(Location { line: 0, column: 0 }, |t| t.span.start);
6938            match keyword {
6939                Keyword::AUTHORIZATION => {
6940                    if authorization_owner.is_some() {
6941                        parser_err!("Found multiple AUTHORIZATION", loc)
6942                    } else {
6943                        authorization_owner = Some(self.parse_object_name(false)?);
6944                        Ok(())
6945                    }
6946                }
6947                Keyword::LOGIN | Keyword::NOLOGIN => {
6948                    if login.is_some() {
6949                        parser_err!("Found multiple LOGIN or NOLOGIN", loc)
6950                    } else {
6951                        login = Some(keyword == Keyword::LOGIN);
6952                        Ok(())
6953                    }
6954                }
6955                Keyword::INHERIT | Keyword::NOINHERIT => {
6956                    if inherit.is_some() {
6957                        parser_err!("Found multiple INHERIT or NOINHERIT", loc)
6958                    } else {
6959                        inherit = Some(keyword == Keyword::INHERIT);
6960                        Ok(())
6961                    }
6962                }
6963                Keyword::BYPASSRLS | Keyword::NOBYPASSRLS => {
6964                    if bypassrls.is_some() {
6965                        parser_err!("Found multiple BYPASSRLS or NOBYPASSRLS", loc)
6966                    } else {
6967                        bypassrls = Some(keyword == Keyword::BYPASSRLS);
6968                        Ok(())
6969                    }
6970                }
6971                Keyword::CREATEDB | Keyword::NOCREATEDB => {
6972                    if create_db.is_some() {
6973                        parser_err!("Found multiple CREATEDB or NOCREATEDB", loc)
6974                    } else {
6975                        create_db = Some(keyword == Keyword::CREATEDB);
6976                        Ok(())
6977                    }
6978                }
6979                Keyword::CREATEROLE | Keyword::NOCREATEROLE => {
6980                    if create_role.is_some() {
6981                        parser_err!("Found multiple CREATEROLE or NOCREATEROLE", loc)
6982                    } else {
6983                        create_role = Some(keyword == Keyword::CREATEROLE);
6984                        Ok(())
6985                    }
6986                }
6987                Keyword::SUPERUSER | Keyword::NOSUPERUSER => {
6988                    if superuser.is_some() {
6989                        parser_err!("Found multiple SUPERUSER or NOSUPERUSER", loc)
6990                    } else {
6991                        superuser = Some(keyword == Keyword::SUPERUSER);
6992                        Ok(())
6993                    }
6994                }
6995                Keyword::REPLICATION | Keyword::NOREPLICATION => {
6996                    if replication.is_some() {
6997                        parser_err!("Found multiple REPLICATION or NOREPLICATION", loc)
6998                    } else {
6999                        replication = Some(keyword == Keyword::REPLICATION);
7000                        Ok(())
7001                    }
7002                }
7003                Keyword::PASSWORD => {
7004                    if password.is_some() {
7005                        parser_err!("Found multiple PASSWORD", loc)
7006                    } else {
7007                        password = if self.parse_keyword(Keyword::NULL) {
7008                            Some(Password::NullPassword)
7009                        } else {
7010                            Some(Password::Password(Expr::Value(self.parse_value()?)))
7011                        };
7012                        Ok(())
7013                    }
7014                }
7015                Keyword::CONNECTION => {
7016                    self.expect_keyword_is(Keyword::LIMIT)?;
7017                    if connection_limit.is_some() {
7018                        parser_err!("Found multiple CONNECTION LIMIT", loc)
7019                    } else {
7020                        connection_limit = Some(Expr::Value(self.parse_number_value()?));
7021                        Ok(())
7022                    }
7023                }
7024                Keyword::VALID => {
7025                    self.expect_keyword_is(Keyword::UNTIL)?;
7026                    if valid_until.is_some() {
7027                        parser_err!("Found multiple VALID UNTIL", loc)
7028                    } else {
7029                        valid_until = Some(Expr::Value(self.parse_value()?));
7030                        Ok(())
7031                    }
7032                }
7033                Keyword::IN => {
7034                    if self.parse_keyword(Keyword::ROLE) {
7035                        if !in_role.is_empty() {
7036                            parser_err!("Found multiple IN ROLE", loc)
7037                        } else {
7038                            in_role = self.parse_comma_separated(|p| p.parse_identifier())?;
7039                            Ok(())
7040                        }
7041                    } else if self.parse_keyword(Keyword::GROUP) {
7042                        if !in_group.is_empty() {
7043                            parser_err!("Found multiple IN GROUP", loc)
7044                        } else {
7045                            in_group = self.parse_comma_separated(|p| p.parse_identifier())?;
7046                            Ok(())
7047                        }
7048                    } else {
7049                        self.expected_ref("ROLE or GROUP after IN", self.peek_token_ref())
7050                    }
7051                }
7052                Keyword::ROLE => {
7053                    if !role.is_empty() {
7054                        parser_err!("Found multiple ROLE", loc)
7055                    } else {
7056                        role = self.parse_comma_separated(|p| p.parse_identifier())?;
7057                        Ok(())
7058                    }
7059                }
7060                Keyword::USER => {
7061                    if !user.is_empty() {
7062                        parser_err!("Found multiple USER", loc)
7063                    } else {
7064                        user = self.parse_comma_separated(|p| p.parse_identifier())?;
7065                        Ok(())
7066                    }
7067                }
7068                Keyword::ADMIN => {
7069                    if !admin.is_empty() {
7070                        parser_err!("Found multiple ADMIN", loc)
7071                    } else {
7072                        admin = self.parse_comma_separated(|p| p.parse_identifier())?;
7073                        Ok(())
7074                    }
7075                }
7076                _ => break,
7077            }?
7078        }
7079
7080        Ok(CreateRole {
7081            names,
7082            if_not_exists,
7083            login,
7084            inherit,
7085            bypassrls,
7086            password,
7087            create_db,
7088            create_role,
7089            replication,
7090            superuser,
7091            connection_limit,
7092            valid_until,
7093            in_role,
7094            in_group,
7095            role,
7096            user,
7097            admin,
7098            authorization_owner,
7099        })
7100    }
7101
7102    /// Parse an `OWNER` clause.
7103    pub fn parse_owner(&mut self) -> Result<Owner, ParserError> {
7104        let owner = match self.parse_one_of_keywords(&[Keyword::CURRENT_USER, Keyword::CURRENT_ROLE, Keyword::SESSION_USER]) {
7105            Some(Keyword::CURRENT_USER) => Owner::CurrentUser,
7106            Some(Keyword::CURRENT_ROLE) => Owner::CurrentRole,
7107            Some(Keyword::SESSION_USER) => Owner::SessionUser,
7108            Some(unexpected_keyword) => return Err(ParserError::ParserError(
7109                format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in owner"),
7110            )),
7111            None => {
7112                match self.parse_identifier() {
7113                    Ok(ident) => Owner::Ident(ident),
7114                    Err(e) => {
7115                        return Err(ParserError::ParserError(format!("Expected: CURRENT_USER, CURRENT_ROLE, SESSION_USER or identifier after OWNER TO. {e}")))
7116                    }
7117                }
7118            }
7119        };
7120        Ok(owner)
7121    }
7122
7123    /// Parses a [Statement::CreateDomain] statement.
7124    fn parse_create_domain(&mut self) -> Result<CreateDomain, ParserError> {
7125        let name = self.parse_object_name(false)?;
7126        self.expect_keyword_is(Keyword::AS)?;
7127        let data_type = self.parse_data_type()?;
7128        let collation = if self.parse_keyword(Keyword::COLLATE) {
7129            Some(self.parse_identifier()?)
7130        } else {
7131            None
7132        };
7133        let default = if self.parse_keyword(Keyword::DEFAULT) {
7134            Some(self.parse_expr()?)
7135        } else {
7136            None
7137        };
7138        let mut constraints = Vec::new();
7139        while let Some(constraint) = self.parse_optional_table_constraint()? {
7140            constraints.push(constraint);
7141        }
7142
7143        Ok(CreateDomain {
7144            name,
7145            data_type,
7146            collation,
7147            default,
7148            constraints,
7149        })
7150    }
7151
7152    /// ```sql
7153    ///     CREATE POLICY name ON table_name [ AS { PERMISSIVE | RESTRICTIVE } ]
7154    ///     [ FOR { ALL | SELECT | INSERT | UPDATE | DELETE } ]
7155    ///     [ TO { role_name | PUBLIC | CURRENT_USER | CURRENT_ROLE | SESSION_USER } [, ...] ]
7156    ///     [ USING ( using_expression ) ]
7157    ///     [ WITH CHECK ( with_check_expression ) ]
7158    /// ```
7159    ///
7160    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-createpolicy.html)
7161    pub fn parse_create_policy(&mut self) -> Result<CreatePolicy, ParserError> {
7162        let name = self.parse_identifier()?;
7163        self.expect_keyword_is(Keyword::ON)?;
7164        let table_name = self.parse_object_name(false)?;
7165
7166        let policy_type = if self.parse_keyword(Keyword::AS) {
7167            let keyword =
7168                self.expect_one_of_keywords(&[Keyword::PERMISSIVE, Keyword::RESTRICTIVE])?;
7169            Some(match keyword {
7170                Keyword::PERMISSIVE => CreatePolicyType::Permissive,
7171                Keyword::RESTRICTIVE => CreatePolicyType::Restrictive,
7172                unexpected_keyword => return Err(ParserError::ParserError(
7173                    format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in policy type"),
7174                )),
7175            })
7176        } else {
7177            None
7178        };
7179
7180        let command = if self.parse_keyword(Keyword::FOR) {
7181            let keyword = self.expect_one_of_keywords(&[
7182                Keyword::ALL,
7183                Keyword::SELECT,
7184                Keyword::INSERT,
7185                Keyword::UPDATE,
7186                Keyword::DELETE,
7187            ])?;
7188            Some(match keyword {
7189                Keyword::ALL => CreatePolicyCommand::All,
7190                Keyword::SELECT => CreatePolicyCommand::Select,
7191                Keyword::INSERT => CreatePolicyCommand::Insert,
7192                Keyword::UPDATE => CreatePolicyCommand::Update,
7193                Keyword::DELETE => CreatePolicyCommand::Delete,
7194                unexpected_keyword => return Err(ParserError::ParserError(
7195                    format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in policy command"),
7196                )),
7197            })
7198        } else {
7199            None
7200        };
7201
7202        let to = if self.parse_keyword(Keyword::TO) {
7203            Some(self.parse_comma_separated(|p| p.parse_owner())?)
7204        } else {
7205            None
7206        };
7207
7208        let using = if self.parse_keyword(Keyword::USING) {
7209            self.expect_token(&Token::LParen)?;
7210            let expr = self.parse_expr()?;
7211            self.expect_token(&Token::RParen)?;
7212            Some(expr)
7213        } else {
7214            None
7215        };
7216
7217        let with_check = if self.parse_keywords(&[Keyword::WITH, Keyword::CHECK]) {
7218            self.expect_token(&Token::LParen)?;
7219            let expr = self.parse_expr()?;
7220            self.expect_token(&Token::RParen)?;
7221            Some(expr)
7222        } else {
7223            None
7224        };
7225
7226        Ok(CreatePolicy {
7227            name,
7228            table_name,
7229            policy_type,
7230            command,
7231            to,
7232            using,
7233            with_check,
7234        })
7235    }
7236
7237    /// ```sql
7238    /// CREATE CONNECTOR [IF NOT EXISTS] connector_name
7239    /// [TYPE datasource_type]
7240    /// [URL datasource_url]
7241    /// [COMMENT connector_comment]
7242    /// [WITH DCPROPERTIES(property_name=property_value, ...)]
7243    /// ```
7244    ///
7245    /// [Hive Documentation](https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=27362034#LanguageManualDDL-CreateDataConnectorCreateConnector)
7246    pub fn parse_create_connector(&mut self) -> Result<CreateConnector, ParserError> {
7247        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
7248        let name = self.parse_identifier()?;
7249
7250        let connector_type = if self.parse_keyword(Keyword::TYPE) {
7251            Some(self.parse_literal_string()?)
7252        } else {
7253            None
7254        };
7255
7256        let url = if self.parse_keyword(Keyword::URL) {
7257            Some(self.parse_literal_string()?)
7258        } else {
7259            None
7260        };
7261
7262        let comment = self.parse_optional_inline_comment()?;
7263
7264        let with_dcproperties =
7265            match self.parse_options_with_keywords(&[Keyword::WITH, Keyword::DCPROPERTIES])? {
7266                properties if !properties.is_empty() => Some(properties),
7267                _ => None,
7268            };
7269
7270        Ok(CreateConnector {
7271            name,
7272            if_not_exists,
7273            connector_type,
7274            url,
7275            comment,
7276            with_dcproperties,
7277        })
7278    }
7279
7280    /// Parse an operator name, which can contain special characters like +, -, <, >, =
7281    /// that are tokenized as operator tokens rather than identifiers.
7282    /// This is used for PostgreSQL CREATE OPERATOR statements.
7283    ///
7284    /// Examples: `+`, `myschema.+`, `pg_catalog.<=`
7285    fn parse_operator_name(&mut self) -> Result<ObjectName, ParserError> {
7286        let mut parts = vec![];
7287        loop {
7288            parts.push(ObjectNamePart::Identifier(Ident::new(
7289                self.next_token().to_string(),
7290            )));
7291            if !self.consume_token(&Token::Period) {
7292                break;
7293            }
7294        }
7295        Ok(ObjectName(parts))
7296    }
7297
7298    /// Parse a [Statement::CreateOperator]
7299    ///
7300    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-createoperator.html)
7301    pub fn parse_create_operator(&mut self) -> Result<CreateOperator, ParserError> {
7302        let name = self.parse_operator_name()?;
7303        self.expect_token(&Token::LParen)?;
7304
7305        let mut function: Option<ObjectName> = None;
7306        let mut is_procedure = false;
7307        let mut left_arg: Option<DataType> = None;
7308        let mut right_arg: Option<DataType> = None;
7309        let mut options: Vec<OperatorOption> = Vec::new();
7310
7311        loop {
7312            let keyword = self.expect_one_of_keywords(&[
7313                Keyword::FUNCTION,
7314                Keyword::PROCEDURE,
7315                Keyword::LEFTARG,
7316                Keyword::RIGHTARG,
7317                Keyword::COMMUTATOR,
7318                Keyword::NEGATOR,
7319                Keyword::RESTRICT,
7320                Keyword::JOIN,
7321                Keyword::HASHES,
7322                Keyword::MERGES,
7323            ])?;
7324
7325            match keyword {
7326                Keyword::HASHES if !options.iter().any(|o| matches!(o, OperatorOption::Hashes)) => {
7327                    options.push(OperatorOption::Hashes);
7328                }
7329                Keyword::MERGES if !options.iter().any(|o| matches!(o, OperatorOption::Merges)) => {
7330                    options.push(OperatorOption::Merges);
7331                }
7332                Keyword::FUNCTION | Keyword::PROCEDURE if function.is_none() => {
7333                    self.expect_token(&Token::Eq)?;
7334                    function = Some(self.parse_object_name(false)?);
7335                    is_procedure = keyword == Keyword::PROCEDURE;
7336                }
7337                Keyword::LEFTARG if left_arg.is_none() => {
7338                    self.expect_token(&Token::Eq)?;
7339                    left_arg = Some(self.parse_data_type()?);
7340                }
7341                Keyword::RIGHTARG if right_arg.is_none() => {
7342                    self.expect_token(&Token::Eq)?;
7343                    right_arg = Some(self.parse_data_type()?);
7344                }
7345                Keyword::COMMUTATOR
7346                    if !options
7347                        .iter()
7348                        .any(|o| matches!(o, OperatorOption::Commutator(_))) =>
7349                {
7350                    self.expect_token(&Token::Eq)?;
7351                    if self.parse_keyword(Keyword::OPERATOR) {
7352                        self.expect_token(&Token::LParen)?;
7353                        let op = self.parse_operator_name()?;
7354                        self.expect_token(&Token::RParen)?;
7355                        options.push(OperatorOption::Commutator(op));
7356                    } else {
7357                        options.push(OperatorOption::Commutator(self.parse_operator_name()?));
7358                    }
7359                }
7360                Keyword::NEGATOR
7361                    if !options
7362                        .iter()
7363                        .any(|o| matches!(o, OperatorOption::Negator(_))) =>
7364                {
7365                    self.expect_token(&Token::Eq)?;
7366                    if self.parse_keyword(Keyword::OPERATOR) {
7367                        self.expect_token(&Token::LParen)?;
7368                        let op = self.parse_operator_name()?;
7369                        self.expect_token(&Token::RParen)?;
7370                        options.push(OperatorOption::Negator(op));
7371                    } else {
7372                        options.push(OperatorOption::Negator(self.parse_operator_name()?));
7373                    }
7374                }
7375                Keyword::RESTRICT
7376                    if !options
7377                        .iter()
7378                        .any(|o| matches!(o, OperatorOption::Restrict(_))) =>
7379                {
7380                    self.expect_token(&Token::Eq)?;
7381                    options.push(OperatorOption::Restrict(Some(
7382                        self.parse_object_name(false)?,
7383                    )));
7384                }
7385                Keyword::JOIN if !options.iter().any(|o| matches!(o, OperatorOption::Join(_))) => {
7386                    self.expect_token(&Token::Eq)?;
7387                    options.push(OperatorOption::Join(Some(self.parse_object_name(false)?)));
7388                }
7389                _ => {
7390                    return Err(ParserError::ParserError(format!(
7391                        "Duplicate or unexpected keyword {:?} in CREATE OPERATOR",
7392                        keyword
7393                    )))
7394                }
7395            }
7396
7397            if !self.consume_token(&Token::Comma) {
7398                break;
7399            }
7400        }
7401
7402        // Expect closing parenthesis
7403        self.expect_token(&Token::RParen)?;
7404
7405        // FUNCTION is required
7406        let function = function.ok_or_else(|| {
7407            ParserError::ParserError("CREATE OPERATOR requires FUNCTION parameter".to_string())
7408        })?;
7409
7410        Ok(CreateOperator {
7411            name,
7412            function,
7413            is_procedure,
7414            left_arg,
7415            right_arg,
7416            options,
7417        })
7418    }
7419
7420    /// Parse a [Statement::CreateOperatorFamily]
7421    ///
7422    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-createopfamily.html)
7423    pub fn parse_create_operator_family(&mut self) -> Result<CreateOperatorFamily, ParserError> {
7424        let name = self.parse_object_name(false)?;
7425        self.expect_keyword(Keyword::USING)?;
7426        let using = self.parse_identifier()?;
7427
7428        Ok(CreateOperatorFamily { name, using })
7429    }
7430
7431    /// Parse a [Statement::CreateOperatorClass]
7432    ///
7433    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-createopclass.html)
7434    pub fn parse_create_operator_class(&mut self) -> Result<CreateOperatorClass, ParserError> {
7435        let name = self.parse_object_name(false)?;
7436        let default = self.parse_keyword(Keyword::DEFAULT);
7437        self.expect_keywords(&[Keyword::FOR, Keyword::TYPE])?;
7438        let for_type = self.parse_data_type()?;
7439        self.expect_keyword(Keyword::USING)?;
7440        let using = self.parse_identifier()?;
7441
7442        let family = if self.parse_keyword(Keyword::FAMILY) {
7443            Some(self.parse_object_name(false)?)
7444        } else {
7445            None
7446        };
7447
7448        self.expect_keyword(Keyword::AS)?;
7449
7450        let mut items = vec![];
7451        loop {
7452            if self.parse_keyword(Keyword::OPERATOR) {
7453                let strategy_number = self.parse_literal_uint()?;
7454                let operator_name = self.parse_operator_name()?;
7455
7456                // Optional operator argument types
7457                let op_types = if self.consume_token(&Token::LParen) {
7458                    let left = self.parse_data_type()?;
7459                    self.expect_token(&Token::Comma)?;
7460                    let right = self.parse_data_type()?;
7461                    self.expect_token(&Token::RParen)?;
7462                    Some(OperatorArgTypes { left, right })
7463                } else {
7464                    None
7465                };
7466
7467                // Optional purpose
7468                let purpose = if self.parse_keyword(Keyword::FOR) {
7469                    if self.parse_keyword(Keyword::SEARCH) {
7470                        Some(OperatorPurpose::ForSearch)
7471                    } else if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
7472                        let sort_family = self.parse_object_name(false)?;
7473                        Some(OperatorPurpose::ForOrderBy { sort_family })
7474                    } else {
7475                        return self
7476                            .expected_ref("SEARCH or ORDER BY after FOR", self.peek_token_ref());
7477                    }
7478                } else {
7479                    None
7480                };
7481
7482                items.push(OperatorClassItem::Operator {
7483                    strategy_number,
7484                    operator_name,
7485                    op_types,
7486                    purpose,
7487                });
7488            } else if self.parse_keyword(Keyword::FUNCTION) {
7489                let support_number = self.parse_literal_uint()?;
7490
7491                // Optional operator types
7492                let op_types = if self.consume_token(&Token::LParen)
7493                    && self.peek_token_ref().token != Token::RParen
7494                {
7495                    let mut types = vec![];
7496                    loop {
7497                        types.push(self.parse_data_type()?);
7498                        if !self.consume_token(&Token::Comma) {
7499                            break;
7500                        }
7501                    }
7502                    self.expect_token(&Token::RParen)?;
7503                    Some(types)
7504                } else if self.consume_token(&Token::LParen) {
7505                    self.expect_token(&Token::RParen)?;
7506                    Some(vec![])
7507                } else {
7508                    None
7509                };
7510
7511                let function_name = self.parse_object_name(false)?;
7512
7513                // Function argument types
7514                let argument_types = if self.consume_token(&Token::LParen) {
7515                    let mut types = vec![];
7516                    loop {
7517                        if self.peek_token_ref().token == Token::RParen {
7518                            break;
7519                        }
7520                        types.push(self.parse_data_type()?);
7521                        if !self.consume_token(&Token::Comma) {
7522                            break;
7523                        }
7524                    }
7525                    self.expect_token(&Token::RParen)?;
7526                    types
7527                } else {
7528                    vec![]
7529                };
7530
7531                items.push(OperatorClassItem::Function {
7532                    support_number,
7533                    op_types,
7534                    function_name,
7535                    argument_types,
7536                });
7537            } else if self.parse_keyword(Keyword::STORAGE) {
7538                let storage_type = self.parse_data_type()?;
7539                items.push(OperatorClassItem::Storage { storage_type });
7540            } else {
7541                break;
7542            }
7543
7544            // Check for comma separator
7545            if !self.consume_token(&Token::Comma) {
7546                break;
7547            }
7548        }
7549
7550        Ok(CreateOperatorClass {
7551            name,
7552            default,
7553            for_type,
7554            using,
7555            family,
7556            items,
7557        })
7558    }
7559
7560    /// Parse a `DROP` statement.
7561    pub fn parse_drop(&mut self) -> Result<Statement, ParserError> {
7562        // MySQL dialect supports `TEMPORARY`
7563        let temporary = dialect_of!(self is MySqlDialect | GenericDialect | DuckDbDialect)
7564            && self.parse_keyword(Keyword::TEMPORARY);
7565        let persistent = dialect_of!(self is DuckDbDialect)
7566            && self.parse_one_of_keywords(&[Keyword::PERSISTENT]).is_some();
7567
7568        let object_type = if self.parse_keyword(Keyword::TABLE) {
7569            ObjectType::Table
7570        } else if self.parse_keyword(Keyword::COLLATION) {
7571            ObjectType::Collation
7572        } else if self.parse_keyword(Keyword::VIEW) {
7573            ObjectType::View
7574        } else if self.parse_keywords(&[Keyword::MATERIALIZED, Keyword::VIEW]) {
7575            ObjectType::MaterializedView
7576        } else if self.parse_keyword(Keyword::INDEX) {
7577            ObjectType::Index
7578        } else if self.parse_keyword(Keyword::ROLE) {
7579            ObjectType::Role
7580        } else if self.parse_keyword(Keyword::SCHEMA) {
7581            ObjectType::Schema
7582        } else if self.parse_keyword(Keyword::DATABASE) {
7583            ObjectType::Database
7584        } else if self.parse_keyword(Keyword::SEQUENCE) {
7585            ObjectType::Sequence
7586        } else if self.parse_keyword(Keyword::STAGE) {
7587            ObjectType::Stage
7588        } else if self.parse_keyword(Keyword::TYPE) {
7589            ObjectType::Type
7590        } else if self.parse_keyword(Keyword::USER) {
7591            ObjectType::User
7592        } else if self.parse_keyword(Keyword::STREAM) {
7593            ObjectType::Stream
7594        } else if self.parse_keyword(Keyword::FUNCTION) {
7595            return self.parse_drop_function().map(Into::into);
7596        } else if self.parse_keyword(Keyword::POLICY) {
7597            return self.parse_drop_policy().map(Into::into);
7598        } else if self.parse_keyword(Keyword::CONNECTOR) {
7599            return self.parse_drop_connector();
7600        } else if self.parse_keyword(Keyword::DOMAIN) {
7601            return self.parse_drop_domain().map(Into::into);
7602        } else if self.parse_keyword(Keyword::PROCEDURE) {
7603            return self.parse_drop_procedure();
7604        } else if self.parse_keyword(Keyword::SECRET) {
7605            return self.parse_drop_secret(temporary, persistent);
7606        } else if self.parse_keyword(Keyword::TRIGGER) {
7607            return self.parse_drop_trigger().map(Into::into);
7608        } else if self.parse_keyword(Keyword::EXTENSION) {
7609            return self.parse_drop_extension();
7610        } else if self.parse_keyword(Keyword::OPERATOR) {
7611            // Check if this is DROP OPERATOR FAMILY or DROP OPERATOR CLASS
7612            return if self.parse_keyword(Keyword::FAMILY) {
7613                self.parse_drop_operator_family()
7614            } else if self.parse_keyword(Keyword::CLASS) {
7615                self.parse_drop_operator_class()
7616            } else {
7617                self.parse_drop_operator()
7618            };
7619        } else {
7620            return self.expected_ref(
7621                "COLLATION, CONNECTOR, DATABASE, EXTENSION, FUNCTION, INDEX, OPERATOR, POLICY, PROCEDURE, ROLE, SCHEMA, SECRET, SEQUENCE, STAGE, TABLE, TRIGGER, TYPE, VIEW, MATERIALIZED VIEW or USER after DROP",
7622                self.peek_token_ref(),
7623            );
7624        };
7625        // Many dialects support the non-standard `IF EXISTS` clause and allow
7626        // specifying multiple objects to delete in a single statement
7627        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
7628        let names = self.parse_comma_separated(|p| p.parse_object_name(false))?;
7629
7630        let loc = self.peek_token_ref().span.start;
7631        let cascade = self.parse_keyword(Keyword::CASCADE);
7632        let restrict = self.parse_keyword(Keyword::RESTRICT);
7633        let purge = self.parse_keyword(Keyword::PURGE);
7634        if cascade && restrict {
7635            return parser_err!("Cannot specify both CASCADE and RESTRICT in DROP", loc);
7636        }
7637        if object_type == ObjectType::Role && (cascade || restrict || purge) {
7638            return parser_err!(
7639                "Cannot specify CASCADE, RESTRICT, or PURGE in DROP ROLE",
7640                loc
7641            );
7642        }
7643        let table = if self.parse_keyword(Keyword::ON) {
7644            Some(self.parse_object_name(false)?)
7645        } else {
7646            None
7647        };
7648        Ok(Statement::Drop {
7649            object_type,
7650            if_exists,
7651            names,
7652            cascade,
7653            restrict,
7654            purge,
7655            temporary,
7656            table,
7657        })
7658    }
7659
7660    fn parse_optional_drop_behavior(&mut self) -> Option<DropBehavior> {
7661        match self.parse_one_of_keywords(&[Keyword::CASCADE, Keyword::RESTRICT]) {
7662            Some(Keyword::CASCADE) => Some(DropBehavior::Cascade),
7663            Some(Keyword::RESTRICT) => Some(DropBehavior::Restrict),
7664            _ => None,
7665        }
7666    }
7667
7668    /// ```sql
7669    /// DROP FUNCTION [ IF EXISTS ] name [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ] [, ...]
7670    /// [ CASCADE | RESTRICT ]
7671    /// ```
7672    fn parse_drop_function(&mut self) -> Result<DropFunction, ParserError> {
7673        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
7674        let func_desc = self.parse_comma_separated(Parser::parse_function_desc)?;
7675        let drop_behavior = self.parse_optional_drop_behavior();
7676        Ok(DropFunction {
7677            if_exists,
7678            func_desc,
7679            drop_behavior,
7680        })
7681    }
7682
7683    /// ```sql
7684    /// DROP POLICY [ IF EXISTS ] name ON table_name [ CASCADE | RESTRICT ]
7685    /// ```
7686    ///
7687    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-droppolicy.html)
7688    fn parse_drop_policy(&mut self) -> Result<DropPolicy, ParserError> {
7689        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
7690        let name = self.parse_identifier()?;
7691        self.expect_keyword_is(Keyword::ON)?;
7692        let table_name = self.parse_object_name(false)?;
7693        let drop_behavior = self.parse_optional_drop_behavior();
7694        Ok(DropPolicy {
7695            if_exists,
7696            name,
7697            table_name,
7698            drop_behavior,
7699        })
7700    }
7701    /// ```sql
7702    /// DROP CONNECTOR [IF EXISTS] name
7703    /// ```
7704    ///
7705    /// See [Hive](https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=27362034#LanguageManualDDL-DropConnector)
7706    fn parse_drop_connector(&mut self) -> Result<Statement, ParserError> {
7707        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
7708        let name = self.parse_identifier()?;
7709        Ok(Statement::DropConnector { if_exists, name })
7710    }
7711
7712    /// ```sql
7713    /// DROP DOMAIN [ IF EXISTS ] name [ CASCADE | RESTRICT ]
7714    /// ```
7715    fn parse_drop_domain(&mut self) -> Result<DropDomain, ParserError> {
7716        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
7717        let name = self.parse_object_name(false)?;
7718        let drop_behavior = self.parse_optional_drop_behavior();
7719        Ok(DropDomain {
7720            if_exists,
7721            name,
7722            drop_behavior,
7723        })
7724    }
7725
7726    /// ```sql
7727    /// DROP PROCEDURE [ IF EXISTS ] name [ ( [ [ argmode ] [ argname ] argtype [, ...] ] ) ] [, ...]
7728    /// [ CASCADE | RESTRICT ]
7729    /// ```
7730    fn parse_drop_procedure(&mut self) -> Result<Statement, ParserError> {
7731        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
7732        let proc_desc = self.parse_comma_separated(Parser::parse_function_desc)?;
7733        let drop_behavior = self.parse_optional_drop_behavior();
7734        Ok(Statement::DropProcedure {
7735            if_exists,
7736            proc_desc,
7737            drop_behavior,
7738        })
7739    }
7740
7741    fn parse_function_desc(&mut self) -> Result<FunctionDesc, ParserError> {
7742        let name = self.parse_object_name(false)?;
7743
7744        let args = if self.consume_token(&Token::LParen) {
7745            if self.consume_token(&Token::RParen) {
7746                Some(vec![])
7747            } else {
7748                let args = self.parse_comma_separated(Parser::parse_function_arg)?;
7749                self.expect_token(&Token::RParen)?;
7750                Some(args)
7751            }
7752        } else {
7753            None
7754        };
7755
7756        Ok(FunctionDesc { name, args })
7757    }
7758
7759    /// See [DuckDB Docs](https://duckdb.org/docs/sql/statements/create_secret.html) for more details.
7760    fn parse_drop_secret(
7761        &mut self,
7762        temporary: bool,
7763        persistent: bool,
7764    ) -> Result<Statement, ParserError> {
7765        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
7766        let name = self.parse_identifier()?;
7767        let storage_specifier = if self.parse_keyword(Keyword::FROM) {
7768            self.parse_identifier().ok()
7769        } else {
7770            None
7771        };
7772        let temp = match (temporary, persistent) {
7773            (true, false) => Some(true),
7774            (false, true) => Some(false),
7775            (false, false) => None,
7776            _ => self.expected_ref("TEMPORARY or PERSISTENT", self.peek_token_ref())?,
7777        };
7778
7779        Ok(Statement::DropSecret {
7780            if_exists,
7781            temporary: temp,
7782            name,
7783            storage_specifier,
7784        })
7785    }
7786
7787    /// Parse a `DECLARE` statement.
7788    ///
7789    /// ```sql
7790    /// DECLARE name [ BINARY ] [ ASENSITIVE | INSENSITIVE ] [ [ NO ] SCROLL ]
7791    ///     CURSOR [ { WITH | WITHOUT } HOLD ] FOR query
7792    /// ```
7793    ///
7794    /// The syntax can vary significantly between warehouses. See the grammar
7795    /// on the warehouse specific function in such cases.
7796    pub fn parse_declare(&mut self) -> Result<Statement, ParserError> {
7797        if dialect_of!(self is BigQueryDialect) {
7798            return self.parse_big_query_declare();
7799        }
7800        if dialect_of!(self is SnowflakeDialect) {
7801            return self.parse_snowflake_declare();
7802        }
7803        if dialect_of!(self is MsSqlDialect) {
7804            return self.parse_mssql_declare();
7805        }
7806
7807        let name = self.parse_identifier()?;
7808
7809        let binary = Some(self.parse_keyword(Keyword::BINARY));
7810        let sensitive = if self.parse_keyword(Keyword::INSENSITIVE) {
7811            Some(true)
7812        } else if self.parse_keyword(Keyword::ASENSITIVE) {
7813            Some(false)
7814        } else {
7815            None
7816        };
7817        let scroll = if self.parse_keyword(Keyword::SCROLL) {
7818            Some(true)
7819        } else if self.parse_keywords(&[Keyword::NO, Keyword::SCROLL]) {
7820            Some(false)
7821        } else {
7822            None
7823        };
7824
7825        self.expect_keyword_is(Keyword::CURSOR)?;
7826        let declare_type = Some(DeclareType::Cursor);
7827
7828        let hold = match self.parse_one_of_keywords(&[Keyword::WITH, Keyword::WITHOUT]) {
7829            Some(keyword) => {
7830                self.expect_keyword_is(Keyword::HOLD)?;
7831
7832                match keyword {
7833                    Keyword::WITH => Some(true),
7834                    Keyword::WITHOUT => Some(false),
7835                    unexpected_keyword => return Err(ParserError::ParserError(
7836                        format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in cursor hold"),
7837                    )),
7838                }
7839            }
7840            None => None,
7841        };
7842
7843        self.expect_keyword_is(Keyword::FOR)?;
7844
7845        let query = Some(self.parse_query()?);
7846
7847        Ok(Statement::Declare {
7848            stmts: vec![Declare {
7849                names: vec![name],
7850                data_type: None,
7851                assignment: None,
7852                declare_type,
7853                binary,
7854                sensitive,
7855                scroll,
7856                hold,
7857                for_query: query,
7858            }],
7859        })
7860    }
7861
7862    /// Parse a [BigQuery] `DECLARE` statement.
7863    ///
7864    /// Syntax:
7865    /// ```text
7866    /// DECLARE variable_name[, ...] [{ <variable_type> | <DEFAULT expression> }];
7867    /// ```
7868    /// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/procedural-language#declare
7869    pub fn parse_big_query_declare(&mut self) -> Result<Statement, ParserError> {
7870        let names = self.parse_comma_separated(Parser::parse_identifier)?;
7871
7872        let data_type = match &self.peek_token_ref().token {
7873            Token::Word(w) if w.keyword == Keyword::DEFAULT => None,
7874            _ => Some(self.parse_data_type()?),
7875        };
7876
7877        let expr = if data_type.is_some() {
7878            if self.parse_keyword(Keyword::DEFAULT) {
7879                Some(self.parse_expr()?)
7880            } else {
7881                None
7882            }
7883        } else {
7884            // If no variable type - default expression must be specified, per BQ docs.
7885            // i.e `DECLARE foo;` is invalid.
7886            self.expect_keyword_is(Keyword::DEFAULT)?;
7887            Some(self.parse_expr()?)
7888        };
7889
7890        Ok(Statement::Declare {
7891            stmts: vec![Declare {
7892                names,
7893                data_type,
7894                assignment: expr.map(|expr| DeclareAssignment::Default(Box::new(expr))),
7895                declare_type: None,
7896                binary: None,
7897                sensitive: None,
7898                scroll: None,
7899                hold: None,
7900                for_query: None,
7901            }],
7902        })
7903    }
7904
7905    /// Parse a [Snowflake] `DECLARE` statement.
7906    ///
7907    /// Syntax:
7908    /// ```text
7909    /// DECLARE
7910    ///   [{ <variable_declaration>
7911    ///      | <cursor_declaration>
7912    ///      | <resultset_declaration>
7913    ///      | <exception_declaration> }; ... ]
7914    ///
7915    /// <variable_declaration>
7916    /// <variable_name> [<type>] [ { DEFAULT | := } <expression>]
7917    ///
7918    /// <cursor_declaration>
7919    /// <cursor_name> CURSOR FOR <query>
7920    ///
7921    /// <resultset_declaration>
7922    /// <resultset_name> RESULTSET [ { DEFAULT | := } ( <query> ) ] ;
7923    ///
7924    /// <exception_declaration>
7925    /// <exception_name> EXCEPTION [ ( <exception_number> , '<exception_message>' ) ] ;
7926    /// ```
7927    ///
7928    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/snowflake-scripting/declare
7929    pub fn parse_snowflake_declare(&mut self) -> Result<Statement, ParserError> {
7930        let mut stmts = vec![];
7931        loop {
7932            let name = self.parse_identifier()?;
7933            let (declare_type, for_query, assigned_expr, data_type) =
7934                if self.parse_keyword(Keyword::CURSOR) {
7935                    self.expect_keyword_is(Keyword::FOR)?;
7936                    match &self.peek_token_ref().token {
7937                        Token::Word(w) if w.keyword == Keyword::SELECT => (
7938                            Some(DeclareType::Cursor),
7939                            Some(self.parse_query()?),
7940                            None,
7941                            None,
7942                        ),
7943                        _ => (
7944                            Some(DeclareType::Cursor),
7945                            None,
7946                            Some(DeclareAssignment::For(Box::new(self.parse_expr()?))),
7947                            None,
7948                        ),
7949                    }
7950                } else if self.parse_keyword(Keyword::RESULTSET) {
7951                    let assigned_expr = if self.peek_token_ref().token != Token::SemiColon {
7952                        self.parse_snowflake_variable_declaration_expression()?
7953                    } else {
7954                        // Nothing more to do. The statement has no further parameters.
7955                        None
7956                    };
7957
7958                    (Some(DeclareType::ResultSet), None, assigned_expr, None)
7959                } else if self.parse_keyword(Keyword::EXCEPTION) {
7960                    let assigned_expr = if self.peek_token_ref().token == Token::LParen {
7961                        Some(DeclareAssignment::Expr(Box::new(self.parse_expr()?)))
7962                    } else {
7963                        // Nothing more to do. The statement has no further parameters.
7964                        None
7965                    };
7966
7967                    (Some(DeclareType::Exception), None, assigned_expr, None)
7968                } else {
7969                    // Without an explicit keyword, the only valid option is variable declaration.
7970                    let (assigned_expr, data_type) = if let Some(assigned_expr) =
7971                        self.parse_snowflake_variable_declaration_expression()?
7972                    {
7973                        (Some(assigned_expr), None)
7974                    } else if let Token::Word(_) = &self.peek_token_ref().token {
7975                        let data_type = self.parse_data_type()?;
7976                        (
7977                            self.parse_snowflake_variable_declaration_expression()?,
7978                            Some(data_type),
7979                        )
7980                    } else {
7981                        (None, None)
7982                    };
7983                    (None, None, assigned_expr, data_type)
7984                };
7985            let stmt = Declare {
7986                names: vec![name],
7987                data_type,
7988                assignment: assigned_expr,
7989                declare_type,
7990                binary: None,
7991                sensitive: None,
7992                scroll: None,
7993                hold: None,
7994                for_query,
7995            };
7996
7997            stmts.push(stmt);
7998            if self.consume_token(&Token::SemiColon) {
7999                match &self.peek_token_ref().token {
8000                    Token::Word(w)
8001                        if ALL_KEYWORDS
8002                            .binary_search(&w.value.to_uppercase().as_str())
8003                            .is_err() =>
8004                    {
8005                        // Not a keyword - start of a new declaration.
8006                        continue;
8007                    }
8008                    _ => {
8009                        // Put back the semicolon, this is the end of the DECLARE statement.
8010                        self.prev_token();
8011                    }
8012                }
8013            }
8014
8015            break;
8016        }
8017
8018        Ok(Statement::Declare { stmts })
8019    }
8020
8021    /// Parse a [MsSql] `DECLARE` statement.
8022    ///
8023    /// Syntax:
8024    /// ```text
8025    /// DECLARE
8026    // {
8027    //   { @local_variable [AS] data_type [ = value ] }
8028    //   | { @cursor_variable_name CURSOR [ FOR ] }
8029    // } [ ,...n ]
8030    /// ```
8031    /// [MsSql]: https://learn.microsoft.com/en-us/sql/t-sql/language-elements/declare-local-variable-transact-sql?view=sql-server-ver16
8032    pub fn parse_mssql_declare(&mut self) -> Result<Statement, ParserError> {
8033        let stmts = self.parse_comma_separated(Parser::parse_mssql_declare_stmt)?;
8034
8035        Ok(Statement::Declare { stmts })
8036    }
8037
8038    /// Parse the body of a [MsSql] `DECLARE`statement.
8039    ///
8040    /// Syntax:
8041    /// ```text
8042    // {
8043    //   { @local_variable [AS] data_type [ = value ] }
8044    //   | { @cursor_variable_name CURSOR [ FOR ]}
8045    // } [ ,...n ]
8046    /// ```
8047    /// [MsSql]: https://learn.microsoft.com/en-us/sql/t-sql/language-elements/declare-local-variable-transact-sql?view=sql-server-ver16
8048    pub fn parse_mssql_declare_stmt(&mut self) -> Result<Declare, ParserError> {
8049        let name = {
8050            let ident = self.parse_identifier()?;
8051            if !ident.value.starts_with('@')
8052                && !matches!(
8053                    &self.peek_token_ref().token,
8054                    Token::Word(w) if w.keyword == Keyword::CURSOR
8055                )
8056            {
8057                Err(ParserError::TokenizerError(
8058                    "Invalid MsSql variable declaration.".to_string(),
8059                ))
8060            } else {
8061                Ok(ident)
8062            }
8063        }?;
8064
8065        let (declare_type, data_type) = match &self.peek_token_ref().token {
8066            Token::Word(w) => match w.keyword {
8067                Keyword::CURSOR => {
8068                    self.next_token();
8069                    (Some(DeclareType::Cursor), None)
8070                }
8071                Keyword::AS => {
8072                    self.next_token();
8073                    (None, Some(self.parse_data_type()?))
8074                }
8075                _ => (None, Some(self.parse_data_type()?)),
8076            },
8077            _ => (None, Some(self.parse_data_type()?)),
8078        };
8079
8080        let (for_query, assignment) = if self.peek_keyword(Keyword::FOR) {
8081            self.next_token();
8082            let query = Some(self.parse_query()?);
8083            (query, None)
8084        } else {
8085            let assignment = self.parse_mssql_variable_declaration_expression()?;
8086            (None, assignment)
8087        };
8088
8089        Ok(Declare {
8090            names: vec![name],
8091            data_type,
8092            assignment,
8093            declare_type,
8094            binary: None,
8095            sensitive: None,
8096            scroll: None,
8097            hold: None,
8098            for_query,
8099        })
8100    }
8101
8102    /// Parses the assigned expression in a variable declaration.
8103    ///
8104    /// Syntax:
8105    /// ```text
8106    /// [ { DEFAULT | := } <expression>]
8107    /// ```
8108    /// <https://docs.snowflake.com/en/sql-reference/snowflake-scripting/declare#variable-declaration-syntax>
8109    pub fn parse_snowflake_variable_declaration_expression(
8110        &mut self,
8111    ) -> Result<Option<DeclareAssignment>, ParserError> {
8112        Ok(match &self.peek_token_ref().token {
8113            Token::Word(w) if w.keyword == Keyword::DEFAULT => {
8114                self.next_token(); // Skip `DEFAULT`
8115                Some(DeclareAssignment::Default(Box::new(self.parse_expr()?)))
8116            }
8117            Token::Assignment => {
8118                self.next_token(); // Skip `:=`
8119                Some(DeclareAssignment::DuckAssignment(Box::new(
8120                    self.parse_expr()?,
8121                )))
8122            }
8123            _ => None,
8124        })
8125    }
8126
8127    /// Parses the assigned expression in a variable declaration.
8128    ///
8129    /// Syntax:
8130    /// ```text
8131    /// [ = <expression>]
8132    /// ```
8133    pub fn parse_mssql_variable_declaration_expression(
8134        &mut self,
8135    ) -> Result<Option<DeclareAssignment>, ParserError> {
8136        Ok(match &self.peek_token_ref().token {
8137            Token::Eq => {
8138                self.next_token(); // Skip `=`
8139                Some(DeclareAssignment::MsSqlAssignment(Box::new(
8140                    self.parse_expr()?,
8141                )))
8142            }
8143            _ => None,
8144        })
8145    }
8146
8147    /// Parse `FETCH [direction] { FROM | IN } cursor INTO target;` statement.
8148    pub fn parse_fetch_statement(&mut self) -> Result<Statement, ParserError> {
8149        let direction = if self.parse_keyword(Keyword::NEXT) {
8150            FetchDirection::Next
8151        } else if self.parse_keyword(Keyword::PRIOR) {
8152            FetchDirection::Prior
8153        } else if self.parse_keyword(Keyword::FIRST) {
8154            FetchDirection::First
8155        } else if self.parse_keyword(Keyword::LAST) {
8156            FetchDirection::Last
8157        } else if self.parse_keyword(Keyword::ABSOLUTE) {
8158            FetchDirection::Absolute {
8159                limit: self.parse_number_value()?,
8160            }
8161        } else if self.parse_keyword(Keyword::RELATIVE) {
8162            FetchDirection::Relative {
8163                limit: self.parse_number_value()?,
8164            }
8165        } else if self.parse_keyword(Keyword::FORWARD) {
8166            if self.parse_keyword(Keyword::ALL) {
8167                FetchDirection::ForwardAll
8168            } else {
8169                FetchDirection::Forward {
8170                    // TODO: Support optional
8171                    limit: Some(self.parse_number_value()?),
8172                }
8173            }
8174        } else if self.parse_keyword(Keyword::BACKWARD) {
8175            if self.parse_keyword(Keyword::ALL) {
8176                FetchDirection::BackwardAll
8177            } else {
8178                FetchDirection::Backward {
8179                    // TODO: Support optional
8180                    limit: Some(self.parse_number_value()?),
8181                }
8182            }
8183        } else if self.parse_keyword(Keyword::ALL) {
8184            FetchDirection::All
8185        } else {
8186            FetchDirection::Count {
8187                limit: self.parse_number_value()?,
8188            }
8189        };
8190
8191        let position = if self.peek_keyword(Keyword::FROM) {
8192            self.expect_keyword(Keyword::FROM)?;
8193            FetchPosition::From
8194        } else if self.peek_keyword(Keyword::IN) {
8195            self.expect_keyword(Keyword::IN)?;
8196            FetchPosition::In
8197        } else {
8198            return parser_err!("Expected FROM or IN", self.peek_token_ref().span.start);
8199        };
8200
8201        let name = self.parse_identifier()?;
8202
8203        let into = if self.parse_keyword(Keyword::INTO) {
8204            Some(self.parse_object_name(false)?)
8205        } else {
8206            None
8207        };
8208
8209        Ok(Statement::Fetch {
8210            name,
8211            direction,
8212            position,
8213            into,
8214        })
8215    }
8216
8217    /// Parse a `DISCARD` statement.
8218    pub fn parse_discard(&mut self) -> Result<Statement, ParserError> {
8219        let object_type = if self.parse_keyword(Keyword::ALL) {
8220            DiscardObject::ALL
8221        } else if self.parse_keyword(Keyword::PLANS) {
8222            DiscardObject::PLANS
8223        } else if self.parse_keyword(Keyword::SEQUENCES) {
8224            DiscardObject::SEQUENCES
8225        } else if self.parse_keyword(Keyword::TEMP) || self.parse_keyword(Keyword::TEMPORARY) {
8226            DiscardObject::TEMP
8227        } else {
8228            return self.expected_ref(
8229                "ALL, PLANS, SEQUENCES, TEMP or TEMPORARY after DISCARD",
8230                self.peek_token_ref(),
8231            );
8232        };
8233        Ok(Statement::Discard { object_type })
8234    }
8235
8236    /// Parse a `CREATE INDEX` statement.
8237    pub fn parse_create_index(&mut self, unique: bool) -> Result<CreateIndex, ParserError> {
8238        let concurrently = self.parse_keyword(Keyword::CONCURRENTLY);
8239        let r#async = self.parse_keyword(Keyword::ASYNC);
8240        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
8241
8242        let mut using = None;
8243
8244        let index_name = if if_not_exists || !self.parse_keyword(Keyword::ON) {
8245            let index_name = self.parse_object_name(false)?;
8246            // MySQL allows `USING index_type` either before or after `ON table_name`
8247            using = self.parse_optional_using_then_index_type()?;
8248            self.expect_keyword_is(Keyword::ON)?;
8249            Some(index_name)
8250        } else {
8251            None
8252        };
8253
8254        let table_name = self.parse_object_name(false)?;
8255
8256        // MySQL allows having two `USING` clauses.
8257        // In that case, the second clause overwrites the first.
8258        using = self.parse_optional_using_then_index_type()?.or(using);
8259
8260        let columns = self.parse_parenthesized_index_column_list()?;
8261
8262        let include = if self.parse_keyword(Keyword::INCLUDE) {
8263            self.expect_token(&Token::LParen)?;
8264            let columns = self.parse_comma_separated(|p| p.parse_identifier())?;
8265            self.expect_token(&Token::RParen)?;
8266            columns
8267        } else {
8268            vec![]
8269        };
8270
8271        let nulls_distinct = if self.parse_keyword(Keyword::NULLS) {
8272            let not = self.parse_keyword(Keyword::NOT);
8273            self.expect_keyword_is(Keyword::DISTINCT)?;
8274            Some(!not)
8275        } else {
8276            None
8277        };
8278
8279        let with = if self.dialect.supports_create_index_with_clause()
8280            && self.parse_keyword(Keyword::WITH)
8281        {
8282            self.expect_token(&Token::LParen)?;
8283            let with_params = self.parse_comma_separated(Parser::parse_expr)?;
8284            self.expect_token(&Token::RParen)?;
8285            with_params
8286        } else {
8287            Vec::new()
8288        };
8289
8290        let predicate = if self.parse_keyword(Keyword::WHERE) {
8291            Some(self.parse_expr()?)
8292        } else {
8293            None
8294        };
8295
8296        // MySQL options (including the modern style of `USING` after the column list instead of
8297        // before, which is deprecated) shouldn't conflict with other preceding options (e.g. `WITH
8298        // PARSER` won't be caught by the above `WITH` clause parsing because MySQL doesn't set that
8299        // support flag). This is probably invalid syntax for other dialects, but it is simpler to
8300        // parse it anyway (as we do inside `ALTER TABLE` and `CREATE TABLE` parsing).
8301        let index_options = self.parse_index_options()?;
8302
8303        // MySQL allows `ALGORITHM` and `LOCK` options. Unlike in `ALTER TABLE`, they need not be comma separated.
8304        let mut alter_options = Vec::new();
8305        while self
8306            .peek_one_of_keywords(&[Keyword::ALGORITHM, Keyword::LOCK])
8307            .is_some()
8308        {
8309            alter_options.push(self.parse_alter_table_operation()?)
8310        }
8311
8312        Ok(CreateIndex {
8313            name: index_name,
8314            table_name,
8315            using,
8316            columns,
8317            unique,
8318            concurrently,
8319            r#async,
8320            if_not_exists,
8321            include,
8322            nulls_distinct,
8323            with,
8324            predicate,
8325            index_options,
8326            alter_options,
8327            fulltext_or_spatial: None,
8328        })
8329    }
8330
8331    /// Parse a standalone MySQL `CREATE FULLTEXT INDEX` / `CREATE SPATIAL INDEX`.
8332    ///
8333    /// Syntax (MySQL):
8334    /// ```text
8335    /// CREATE [FULLTEXT | SPATIAL] INDEX [index_name] ON tbl_name (key_part,...)
8336    ///        [index_option] ... [algorithm_option | lock_option] ...
8337    /// ```
8338    ///
8339    /// Unlike `parse_create_index`, this form is MySQL-only and does not
8340    /// support PG-specific clauses like `CONCURRENTLY`, `IF NOT EXISTS`,
8341    /// `INCLUDE`, `NULLS DISTINCT`, `WITH (...)`, or `WHERE`.
8342    ///
8343    /// [MySQL]: https://dev.mysql.com/doc/refman/8.0/en/create-index.html
8344    pub fn parse_create_fulltext_or_spatial_index(
8345        &mut self,
8346        kind: FullTextOrSpatialKind,
8347    ) -> Result<CreateIndex, ParserError> {
8348        // Optional index name (the `INDEX` keyword was already consumed by the dispatch).
8349        let index_name = if self.parse_keyword(Keyword::ON) {
8350            None
8351        } else {
8352            let name = self.parse_object_name(false)?;
8353            self.expect_keyword_is(Keyword::ON)?;
8354            Some(name)
8355        };
8356
8357        let table_name = self.parse_object_name(false)?;
8358
8359        // MySQL allows `USING BTREE/HASH` after the table name.
8360        let using = self.parse_optional_using_then_index_type()?;
8361
8362        let columns = self.parse_parenthesized_index_column_list()?;
8363
8364        // MySQL index options (USING after column list, WITH PARSER, visible/hidden, etc.)
8365        let index_options = self.parse_index_options()?;
8366
8367        // MySQL allows `ALGORITHM` and `LOCK` options.
8368        let mut alter_options = Vec::new();
8369        while self
8370            .peek_one_of_keywords(&[Keyword::ALGORITHM, Keyword::LOCK])
8371            .is_some()
8372        {
8373            alter_options.push(self.parse_alter_table_operation()?)
8374        }
8375
8376        Ok(CreateIndex {
8377            name: index_name,
8378            table_name,
8379            using,
8380            columns,
8381            unique: false,
8382            concurrently: false,
8383            r#async: false,
8384            if_not_exists: false,
8385            include: vec![],
8386            nulls_distinct: None,
8387            with: vec![],
8388            predicate: None,
8389            index_options,
8390            alter_options,
8391            fulltext_or_spatial: Some(kind),
8392        })
8393    }
8394
8395    /// Parse a `CREATE EXTENSION` statement.
8396    pub fn parse_create_extension(&mut self) -> Result<CreateExtension, ParserError> {
8397        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
8398        let name = self.parse_identifier()?;
8399
8400        let (schema, version, cascade) = if self.parse_keyword(Keyword::WITH) {
8401            let schema = if self.parse_keyword(Keyword::SCHEMA) {
8402                Some(self.parse_identifier()?)
8403            } else {
8404                None
8405            };
8406
8407            let version = if self.parse_keyword(Keyword::VERSION) {
8408                Some(self.parse_identifier()?)
8409            } else {
8410                None
8411            };
8412
8413            let cascade = self.parse_keyword(Keyword::CASCADE);
8414
8415            (schema, version, cascade)
8416        } else {
8417            (None, None, false)
8418        };
8419
8420        Ok(CreateExtension {
8421            name,
8422            if_not_exists,
8423            schema,
8424            version,
8425            cascade,
8426        })
8427    }
8428
8429    /// Parse a PostgreSQL-specific [Statement::CreateCollation] statement.
8430    pub fn parse_create_collation(&mut self) -> Result<CreateCollation, ParserError> {
8431        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
8432        let name = self.parse_object_name(false)?;
8433
8434        let definition = if self.parse_keyword(Keyword::FROM) {
8435            CreateCollationDefinition::From(self.parse_object_name(false)?)
8436        } else if self.consume_token(&Token::LParen) {
8437            let options = self.parse_comma_separated(Parser::parse_sql_option)?;
8438            self.expect_token(&Token::RParen)?;
8439            CreateCollationDefinition::Options(options)
8440        } else {
8441            return self.expected_ref(
8442                "FROM or parenthesized option list after CREATE COLLATION name",
8443                self.peek_token_ref(),
8444            );
8445        };
8446
8447        Ok(CreateCollation {
8448            if_not_exists,
8449            name,
8450            definition,
8451        })
8452    }
8453
8454    /// Parse a PostgreSQL-specific [Statement::DropExtension] statement.
8455    pub fn parse_drop_extension(&mut self) -> Result<Statement, ParserError> {
8456        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
8457        let names = self.parse_comma_separated(|p| p.parse_identifier())?;
8458        let cascade_or_restrict =
8459            self.parse_one_of_keywords(&[Keyword::CASCADE, Keyword::RESTRICT]);
8460        Ok(Statement::DropExtension(DropExtension {
8461            names,
8462            if_exists,
8463            cascade_or_restrict: cascade_or_restrict
8464                .map(|k| match k {
8465                    Keyword::CASCADE => Ok(ReferentialAction::Cascade),
8466                    Keyword::RESTRICT => Ok(ReferentialAction::Restrict),
8467                    _ => self.expected_ref("CASCADE or RESTRICT", self.peek_token_ref()),
8468                })
8469                .transpose()?,
8470        }))
8471    }
8472
8473    /// Parse a[Statement::DropOperator] statement.
8474    ///
8475    pub fn parse_drop_operator(&mut self) -> Result<Statement, ParserError> {
8476        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
8477        let operators = self.parse_comma_separated(|p| p.parse_drop_operator_signature())?;
8478        let drop_behavior = self.parse_optional_drop_behavior();
8479        Ok(Statement::DropOperator(DropOperator {
8480            if_exists,
8481            operators,
8482            drop_behavior,
8483        }))
8484    }
8485
8486    /// Parse an operator signature for a [Statement::DropOperator]
8487    /// Format: `name ( { left_type | NONE } , right_type )`
8488    fn parse_drop_operator_signature(&mut self) -> Result<DropOperatorSignature, ParserError> {
8489        let name = self.parse_operator_name()?;
8490        self.expect_token(&Token::LParen)?;
8491
8492        // Parse left operand type (or NONE for prefix operators)
8493        let left_type = if self.parse_keyword(Keyword::NONE) {
8494            None
8495        } else {
8496            Some(self.parse_data_type()?)
8497        };
8498
8499        self.expect_token(&Token::Comma)?;
8500
8501        // Parse right operand type (always required)
8502        let right_type = self.parse_data_type()?;
8503
8504        self.expect_token(&Token::RParen)?;
8505
8506        Ok(DropOperatorSignature {
8507            name,
8508            left_type,
8509            right_type,
8510        })
8511    }
8512
8513    /// Parse a [Statement::DropOperatorFamily]
8514    ///
8515    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-dropopfamily.html)
8516    pub fn parse_drop_operator_family(&mut self) -> Result<Statement, ParserError> {
8517        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
8518        let names = self.parse_comma_separated(|p| p.parse_object_name(false))?;
8519        self.expect_keyword(Keyword::USING)?;
8520        let using = self.parse_identifier()?;
8521        let drop_behavior = self.parse_optional_drop_behavior();
8522        Ok(Statement::DropOperatorFamily(DropOperatorFamily {
8523            if_exists,
8524            names,
8525            using,
8526            drop_behavior,
8527        }))
8528    }
8529
8530    /// Parse a [Statement::DropOperatorClass]
8531    ///
8532    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-dropopclass.html)
8533    pub fn parse_drop_operator_class(&mut self) -> Result<Statement, ParserError> {
8534        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
8535        let names = self.parse_comma_separated(|p| p.parse_object_name(false))?;
8536        self.expect_keyword(Keyword::USING)?;
8537        let using = self.parse_identifier()?;
8538        let drop_behavior = self.parse_optional_drop_behavior();
8539        Ok(Statement::DropOperatorClass(DropOperatorClass {
8540            if_exists,
8541            names,
8542            using,
8543            drop_behavior,
8544        }))
8545    }
8546
8547    /// Parse Hive distribution style.
8548    ///
8549    /// TODO: Support parsing for `SKEWED` distribution style.
8550    pub fn parse_hive_distribution(&mut self) -> Result<HiveDistributionStyle, ParserError> {
8551        if self.parse_keywords(&[Keyword::PARTITIONED, Keyword::BY]) {
8552            self.expect_token(&Token::LParen)?;
8553            let columns =
8554                self.parse_comma_separated(|parser| parser.parse_column_def_inner(true))?;
8555            self.expect_token(&Token::RParen)?;
8556            Ok(HiveDistributionStyle::PARTITIONED { columns })
8557        } else {
8558            Ok(HiveDistributionStyle::NONE)
8559        }
8560    }
8561
8562    /// Parse Redshift `DISTSTYLE { AUTO | EVEN | KEY | ALL }`.
8563    ///
8564    /// See <https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html>
8565    fn parse_dist_style(&mut self) -> Result<DistStyle, ParserError> {
8566        let token = self.next_token();
8567        match &token.token {
8568            Token::Word(w) => match w.keyword {
8569                Keyword::AUTO => Ok(DistStyle::Auto),
8570                Keyword::EVEN => Ok(DistStyle::Even),
8571                Keyword::KEY => Ok(DistStyle::Key),
8572                Keyword::ALL => Ok(DistStyle::All),
8573                _ => self.expected("AUTO, EVEN, KEY, or ALL", token),
8574            },
8575            _ => self.expected("AUTO, EVEN, KEY, or ALL", token),
8576        }
8577    }
8578
8579    /// Parse Hive formats.
8580    pub fn parse_hive_formats(&mut self) -> Result<Option<HiveFormat>, ParserError> {
8581        let mut hive_format: Option<HiveFormat> = None;
8582        loop {
8583            match self.parse_one_of_keywords(&[
8584                Keyword::ROW,
8585                Keyword::STORED,
8586                Keyword::LOCATION,
8587                Keyword::WITH,
8588                Keyword::USING,
8589            ]) {
8590                Some(Keyword::ROW) => {
8591                    hive_format
8592                        .get_or_insert_with(HiveFormat::default)
8593                        .row_format = Some(self.parse_row_format()?);
8594                }
8595                Some(Keyword::STORED) => {
8596                    self.expect_keyword_is(Keyword::AS)?;
8597                    if self.parse_keyword(Keyword::INPUTFORMAT) {
8598                        let input_format = self.parse_expr()?;
8599                        self.expect_keyword_is(Keyword::OUTPUTFORMAT)?;
8600                        let output_format = self.parse_expr()?;
8601                        hive_format.get_or_insert_with(HiveFormat::default).storage =
8602                            Some(HiveIOFormat::IOF {
8603                                input_format,
8604                                output_format,
8605                            });
8606                    } else {
8607                        let format = self.parse_file_format()?;
8608                        hive_format.get_or_insert_with(HiveFormat::default).storage =
8609                            Some(HiveIOFormat::FileFormat { format });
8610                    }
8611                }
8612                Some(Keyword::LOCATION) => {
8613                    hive_format.get_or_insert_with(HiveFormat::default).location =
8614                        Some(self.parse_literal_string()?);
8615                }
8616                Some(Keyword::WITH) => {
8617                    self.prev_token();
8618                    let properties = self
8619                        .parse_options_with_keywords(&[Keyword::WITH, Keyword::SERDEPROPERTIES])?;
8620                    if !properties.is_empty() {
8621                        hive_format
8622                            .get_or_insert_with(HiveFormat::default)
8623                            .serde_properties = Some(properties);
8624                    } else {
8625                        break;
8626                    }
8627                }
8628                Some(Keyword::USING) if self.dialect.supports_create_table_using() => {
8629                    let format = self.parse_identifier()?;
8630                    hive_format.get_or_insert_with(HiveFormat::default).storage =
8631                        Some(HiveIOFormat::Using { format });
8632                }
8633                Some(Keyword::USING) => {
8634                    // USING is not a table format keyword in this dialect; put it back
8635                    self.prev_token();
8636                    break;
8637                }
8638                None => break,
8639                _ => break,
8640            }
8641        }
8642
8643        Ok(hive_format)
8644    }
8645
8646    /// Parse Hive row format.
8647    pub fn parse_row_format(&mut self) -> Result<HiveRowFormat, ParserError> {
8648        self.expect_keyword_is(Keyword::FORMAT)?;
8649        match self.parse_one_of_keywords(&[Keyword::SERDE, Keyword::DELIMITED]) {
8650            Some(Keyword::SERDE) => {
8651                let class = self.parse_literal_string()?;
8652                Ok(HiveRowFormat::SERDE { class })
8653            }
8654            _ => {
8655                let mut row_delimiters = vec![];
8656
8657                loop {
8658                    match self.parse_one_of_keywords(&[
8659                        Keyword::FIELDS,
8660                        Keyword::COLLECTION,
8661                        Keyword::MAP,
8662                        Keyword::LINES,
8663                        Keyword::NULL,
8664                    ]) {
8665                        Some(Keyword::FIELDS)
8666                            if self.parse_keywords(&[Keyword::TERMINATED, Keyword::BY]) =>
8667                        {
8668                            row_delimiters.push(HiveRowDelimiter {
8669                                delimiter: HiveDelimiter::FieldsTerminatedBy,
8670                                char: self.parse_identifier()?,
8671                            });
8672
8673                            if self.parse_keywords(&[Keyword::ESCAPED, Keyword::BY]) {
8674                                row_delimiters.push(HiveRowDelimiter {
8675                                    delimiter: HiveDelimiter::FieldsEscapedBy,
8676                                    char: self.parse_identifier()?,
8677                                });
8678                            }
8679                        }
8680                        Some(Keyword::COLLECTION)
8681                            if self.parse_keywords(&[
8682                                Keyword::ITEMS,
8683                                Keyword::TERMINATED,
8684                                Keyword::BY,
8685                            ]) =>
8686                        {
8687                            row_delimiters.push(HiveRowDelimiter {
8688                                delimiter: HiveDelimiter::CollectionItemsTerminatedBy,
8689                                char: self.parse_identifier()?,
8690                            });
8691                        }
8692                        Some(Keyword::MAP)
8693                            if self.parse_keywords(&[
8694                                Keyword::KEYS,
8695                                Keyword::TERMINATED,
8696                                Keyword::BY,
8697                            ]) =>
8698                        {
8699                            row_delimiters.push(HiveRowDelimiter {
8700                                delimiter: HiveDelimiter::MapKeysTerminatedBy,
8701                                char: self.parse_identifier()?,
8702                            });
8703                        }
8704                        Some(Keyword::LINES)
8705                            if self.parse_keywords(&[Keyword::TERMINATED, Keyword::BY]) =>
8706                        {
8707                            row_delimiters.push(HiveRowDelimiter {
8708                                delimiter: HiveDelimiter::LinesTerminatedBy,
8709                                char: self.parse_identifier()?,
8710                            });
8711                        }
8712                        Some(Keyword::NULL)
8713                            if self.parse_keywords(&[Keyword::DEFINED, Keyword::AS]) =>
8714                        {
8715                            row_delimiters.push(HiveRowDelimiter {
8716                                delimiter: HiveDelimiter::NullDefinedAs,
8717                                char: self.parse_identifier()?,
8718                            });
8719                        }
8720                        _ => {
8721                            break;
8722                        }
8723                    }
8724                }
8725
8726                Ok(HiveRowFormat::DELIMITED {
8727                    delimiters: row_delimiters,
8728                })
8729            }
8730        }
8731    }
8732
8733    fn parse_optional_on_cluster(&mut self) -> Result<Option<Ident>, ParserError> {
8734        if self.parse_keywords(&[Keyword::ON, Keyword::CLUSTER]) {
8735            Ok(Some(self.parse_identifier()?))
8736        } else {
8737            Ok(None)
8738        }
8739    }
8740
8741    /// Parse `CREATE TABLE` statement.
8742    #[allow(clippy::too_many_arguments)]
8743    pub fn parse_create_table(
8744        &mut self,
8745        or_replace: bool,
8746        temporary: bool,
8747        unlogged: bool,
8748        global: Option<bool>,
8749        transient: bool,
8750        volatile: bool,
8751        multiset: Option<bool>,
8752    ) -> Result<CreateTable, ParserError> {
8753        let allow_unquoted_hyphen = dialect_of!(self is BigQueryDialect);
8754        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
8755        let table_name = self.parse_object_name(allow_unquoted_hyphen)?;
8756
8757        let fallback = if self.dialect.supports_leading_comma_before_table_options()
8758            && self.consume_token(&Token::Comma)
8759        {
8760            let fallback = self.maybe_parse_fallback()?;
8761            if fallback.is_none() {
8762                self.prev_token(); // Put back comma.
8763            }
8764            fallback
8765        } else {
8766            None
8767        };
8768
8769        // PostgreSQL PARTITION OF for child partition tables
8770        // Note: This is a PostgreSQL-specific feature, but the dialect check was intentionally
8771        // removed to allow GenericDialect and other dialects to parse this syntax. This enables
8772        // multi-dialect SQL tools to work with PostgreSQL-specific DDL statements.
8773        //
8774        // PARTITION OF can be combined with other table definition clauses in the AST,
8775        // though PostgreSQL itself prohibits PARTITION OF with AS SELECT or LIKE clauses.
8776        // The parser accepts these combinations for flexibility; semantic validation
8777        // is left to downstream tools.
8778        // Child partitions can have their own constraints and indexes.
8779        let partition_of = if self.parse_keywords(&[Keyword::PARTITION, Keyword::OF]) {
8780            Some(self.parse_object_name(allow_unquoted_hyphen)?)
8781        } else {
8782            None
8783        };
8784
8785        // Clickhouse has `ON CLUSTER 'cluster'` syntax for DDLs
8786        let on_cluster = self.parse_optional_on_cluster()?;
8787
8788        let like = self.maybe_parse_create_table_like(allow_unquoted_hyphen)?;
8789
8790        let clone = if self.parse_keyword(Keyword::CLONE) {
8791            self.parse_object_name(allow_unquoted_hyphen).ok()
8792        } else {
8793            None
8794        };
8795
8796        // parse optional column list (schema)
8797        let (columns, constraints) = self.parse_columns()?;
8798        let comment_after_column_def =
8799            if dialect_of!(self is HiveDialect) && self.parse_keyword(Keyword::COMMENT) {
8800                let next_token = self.next_token();
8801                match next_token.token {
8802                    Token::SingleQuotedString(str) => Some(CommentDef::WithoutEq(str)),
8803                    _ => self.expected("comment", next_token)?,
8804                }
8805            } else {
8806                None
8807            };
8808
8809        // PostgreSQL PARTITION OF: partition bound specification
8810        let for_values = if partition_of.is_some() {
8811            if self.peek_keyword(Keyword::FOR) || self.peek_keyword(Keyword::DEFAULT) {
8812                Some(self.parse_partition_for_values()?)
8813            } else {
8814                return self.expected_ref(
8815                    "FOR VALUES or DEFAULT after PARTITION OF",
8816                    self.peek_token_ref(),
8817                );
8818            }
8819        } else {
8820            None
8821        };
8822
8823        // SQLite supports `WITHOUT ROWID` at the end of `CREATE TABLE`
8824        let without_rowid = self.parse_keywords(&[Keyword::WITHOUT, Keyword::ROWID]);
8825
8826        let hive_distribution = self.parse_hive_distribution()?;
8827        let clustered_by = self.parse_optional_clustered_by()?;
8828        let hive_formats = self.parse_hive_formats()?;
8829
8830        let create_table_config = self.parse_optional_create_table_config()?;
8831
8832        // ClickHouse supports `PRIMARY KEY`, before `ORDER BY`
8833        // https://clickhouse.com/docs/en/sql-reference/statements/create/table#primary-key
8834        let primary_key = if dialect_of!(self is ClickHouseDialect | GenericDialect)
8835            && self.parse_keywords(&[Keyword::PRIMARY, Keyword::KEY])
8836        {
8837            Some(Box::new(self.parse_expr()?))
8838        } else {
8839            None
8840        };
8841
8842        let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
8843            if self.consume_token(&Token::LParen) {
8844                let columns = if self.peek_token_ref().token != Token::RParen {
8845                    self.parse_comma_separated(|p| p.parse_expr())?
8846                } else {
8847                    vec![]
8848                };
8849                self.expect_token(&Token::RParen)?;
8850                Some(OneOrManyWithParens::Many(columns))
8851            } else {
8852                Some(OneOrManyWithParens::One(self.parse_expr()?))
8853            }
8854        } else {
8855            None
8856        };
8857
8858        // ClickHouse allows PARTITION BY after ORDER BY
8859        // https://clickhouse.com/docs/en/sql-reference/statements/create/table#partition-by
8860        let partition_by = if create_table_config.partition_by.is_none()
8861            && self.dialect.supports_partition_by_after_order_by()
8862            && self.parse_keywords(&[Keyword::PARTITION, Keyword::BY])
8863        {
8864            Some(Box::new(self.parse_expr()?))
8865        } else {
8866            create_table_config.partition_by
8867        };
8868
8869        let on_commit = if self.parse_keywords(&[Keyword::ON, Keyword::COMMIT]) {
8870            Some(self.parse_create_table_on_commit()?)
8871        } else {
8872            None
8873        };
8874
8875        let strict = self.parse_keyword(Keyword::STRICT);
8876
8877        // Redshift: BACKUP YES|NO
8878        let backup = if self.parse_keyword(Keyword::BACKUP) {
8879            let keyword = self.expect_one_of_keywords(&[Keyword::YES, Keyword::NO])?;
8880            Some(keyword == Keyword::YES)
8881        } else {
8882            None
8883        };
8884
8885        // Redshift: DISTSTYLE, DISTKEY, SORTKEY
8886        let diststyle = if self.parse_keyword(Keyword::DISTSTYLE) {
8887            Some(self.parse_dist_style()?)
8888        } else {
8889            None
8890        };
8891        let distkey = if self.parse_keyword(Keyword::DISTKEY) {
8892            self.expect_token(&Token::LParen)?;
8893            let expr = self.parse_expr()?;
8894            self.expect_token(&Token::RParen)?;
8895            Some(expr)
8896        } else {
8897            None
8898        };
8899        let sortkey = if self.parse_keyword(Keyword::SORTKEY) {
8900            self.expect_token(&Token::LParen)?;
8901            let columns = self.parse_comma_separated(|p| p.parse_expr())?;
8902            self.expect_token(&Token::RParen)?;
8903            Some(columns)
8904        } else {
8905            None
8906        };
8907
8908        // Parse optional `AS ( query )`
8909        let query = if self.parse_keyword(Keyword::AS) {
8910            Some(self.parse_query()?)
8911        } else if self.dialect.supports_create_table_select() && self.parse_keyword(Keyword::SELECT)
8912        {
8913            // rewind the SELECT keyword
8914            self.prev_token();
8915            Some(self.parse_query()?)
8916        } else {
8917            None
8918        };
8919
8920        // `WITH DATA` clause only applies if there is a query body.
8921        let with_data = if query.is_some() {
8922            self.maybe_parse_with_data()?
8923        } else {
8924            None
8925        };
8926
8927        Ok(CreateTableBuilder::new(table_name)
8928            .temporary(temporary)
8929            .unlogged(unlogged)
8930            .columns(columns)
8931            .constraints(constraints)
8932            .or_replace(or_replace)
8933            .if_not_exists(if_not_exists)
8934            .transient(transient)
8935            .volatile(volatile)
8936            .multiset(multiset)
8937            .fallback(fallback)
8938            .hive_distribution(hive_distribution)
8939            .hive_formats(hive_formats)
8940            .global(global)
8941            .query(query)
8942            .without_rowid(without_rowid)
8943            .like(like)
8944            .clone_clause(clone)
8945            .comment_after_column_def(comment_after_column_def)
8946            .order_by(order_by)
8947            .on_commit(on_commit)
8948            .on_cluster(on_cluster)
8949            .clustered_by(clustered_by)
8950            .partition_by(partition_by)
8951            .cluster_by(create_table_config.cluster_by)
8952            .inherits(create_table_config.inherits)
8953            .partition_of(partition_of)
8954            .for_values(for_values)
8955            .table_options(create_table_config.table_options)
8956            .primary_key(primary_key)
8957            .with_data(with_data)
8958            .strict(strict)
8959            .backup(backup)
8960            .diststyle(diststyle)
8961            .distkey(distkey)
8962            .sortkey(sortkey)
8963            .build())
8964    }
8965
8966    /// Parse `MULTISET` table-kind prefix on `CREATE TABLE`.
8967    fn maybe_parse_multiset(&mut self) -> Option<bool> {
8968        match self.parse_one_of_keywords(&[Keyword::SET, Keyword::MULTISET]) {
8969            Some(Keyword::MULTISET) => Some(true),
8970            Some(Keyword::SET) => Some(false),
8971            _ => None,
8972        }
8973    }
8974
8975    /// Parse `FALLBACK` option on a `CREATE TABLE` statement,
8976    fn maybe_parse_fallback(&mut self) -> Result<Option<bool>, ParserError> {
8977        if self.parse_keywords(&[Keyword::NO, Keyword::FALLBACK]) {
8978            Ok(Some(false))
8979        } else if self.parse_keyword(Keyword::FALLBACK) {
8980            Ok(Some(true))
8981        } else {
8982            Ok(None)
8983        }
8984    }
8985
8986    /// Parse [`WithData`] clause on `CREATE TABLE ... AS` statement.
8987    fn maybe_parse_with_data(&mut self) -> Result<Option<WithData>, ParserError> {
8988        let data = if self.parse_keywords(&[Keyword::WITH, Keyword::DATA]) {
8989            true
8990        } else if self.parse_keywords(&[Keyword::WITH, Keyword::NO, Keyword::DATA]) {
8991            false
8992        } else {
8993            return Ok(None);
8994        };
8995
8996        let statistics = if self.parse_keywords(&[Keyword::AND, Keyword::STATISTICS]) {
8997            Some(true)
8998        } else if self.parse_keywords(&[Keyword::AND, Keyword::NO, Keyword::STATISTICS]) {
8999            Some(false)
9000        } else {
9001            None
9002        };
9003
9004        Ok(Some(WithData { data, statistics }))
9005    }
9006
9007    fn maybe_parse_create_table_like(
9008        &mut self,
9009        allow_unquoted_hyphen: bool,
9010    ) -> Result<Option<CreateTableLikeKind>, ParserError> {
9011        let like = if self.dialect.supports_create_table_like_parenthesized()
9012            && self.consume_token(&Token::LParen)
9013        {
9014            if self.parse_keyword(Keyword::LIKE) {
9015                let name = self.parse_object_name(allow_unquoted_hyphen)?;
9016                let defaults = if self.parse_keywords(&[Keyword::INCLUDING, Keyword::DEFAULTS]) {
9017                    Some(CreateTableLikeDefaults::Including)
9018                } else if self.parse_keywords(&[Keyword::EXCLUDING, Keyword::DEFAULTS]) {
9019                    Some(CreateTableLikeDefaults::Excluding)
9020                } else {
9021                    None
9022                };
9023                self.expect_token(&Token::RParen)?;
9024                Some(CreateTableLikeKind::Parenthesized(CreateTableLike {
9025                    name,
9026                    defaults,
9027                }))
9028            } else {
9029                // Rollback the '(' it's probably the columns list
9030                self.prev_token();
9031                None
9032            }
9033        } else if self.parse_keyword(Keyword::LIKE) || self.parse_keyword(Keyword::ILIKE) {
9034            let name = self.parse_object_name(allow_unquoted_hyphen)?;
9035            Some(CreateTableLikeKind::Plain(CreateTableLike {
9036                name,
9037                defaults: None,
9038            }))
9039        } else {
9040            None
9041        };
9042        Ok(like)
9043    }
9044
9045    pub(crate) fn parse_create_table_on_commit(&mut self) -> Result<OnCommit, ParserError> {
9046        if self.parse_keywords(&[Keyword::DELETE, Keyword::ROWS]) {
9047            Ok(OnCommit::DeleteRows)
9048        } else if self.parse_keywords(&[Keyword::PRESERVE, Keyword::ROWS]) {
9049            Ok(OnCommit::PreserveRows)
9050        } else if self.parse_keywords(&[Keyword::DROP]) {
9051            Ok(OnCommit::Drop)
9052        } else {
9053            parser_err!(
9054                "Expecting DELETE ROWS, PRESERVE ROWS or DROP",
9055                self.peek_token_ref()
9056            )
9057        }
9058    }
9059
9060    /// Parse [ForValues] of a `PARTITION OF` clause.
9061    ///
9062    /// Parses: `FOR VALUES partition_bound_spec | DEFAULT`
9063    ///
9064    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtable.html)
9065    fn parse_partition_for_values(&mut self) -> Result<ForValues, ParserError> {
9066        if self.parse_keyword(Keyword::DEFAULT) {
9067            return Ok(ForValues::Default);
9068        }
9069
9070        self.expect_keywords(&[Keyword::FOR, Keyword::VALUES])?;
9071
9072        if self.parse_keyword(Keyword::IN) {
9073            // FOR VALUES IN (expr, ...)
9074            self.expect_token(&Token::LParen)?;
9075            if self.peek_token_ref().token == Token::RParen {
9076                return self.expected_ref("at least one value", self.peek_token_ref());
9077            }
9078            let values = self.parse_comma_separated(Parser::parse_expr)?;
9079            self.expect_token(&Token::RParen)?;
9080            Ok(ForValues::In(values))
9081        } else if self.parse_keyword(Keyword::FROM) {
9082            // FOR VALUES FROM (...) TO (...)
9083            self.expect_token(&Token::LParen)?;
9084            if self.peek_token_ref().token == Token::RParen {
9085                return self.expected_ref("at least one value", self.peek_token_ref());
9086            }
9087            let from = self.parse_comma_separated(Parser::parse_partition_bound_value)?;
9088            self.expect_token(&Token::RParen)?;
9089            self.expect_keyword(Keyword::TO)?;
9090            self.expect_token(&Token::LParen)?;
9091            if self.peek_token_ref().token == Token::RParen {
9092                return self.expected_ref("at least one value", self.peek_token_ref());
9093            }
9094            let to = self.parse_comma_separated(Parser::parse_partition_bound_value)?;
9095            self.expect_token(&Token::RParen)?;
9096            Ok(ForValues::From { from, to })
9097        } else if self.parse_keyword(Keyword::WITH) {
9098            // FOR VALUES WITH (MODULUS n, REMAINDER r)
9099            self.expect_token(&Token::LParen)?;
9100            self.expect_keyword(Keyword::MODULUS)?;
9101            let modulus = self.parse_literal_uint()?;
9102            self.expect_token(&Token::Comma)?;
9103            self.expect_keyword(Keyword::REMAINDER)?;
9104            let remainder = self.parse_literal_uint()?;
9105            self.expect_token(&Token::RParen)?;
9106            Ok(ForValues::With { modulus, remainder })
9107        } else {
9108            self.expected_ref("IN, FROM, or WITH after FOR VALUES", self.peek_token_ref())
9109        }
9110    }
9111
9112    /// Parse a single partition bound value (MINVALUE, MAXVALUE, or expression).
9113    fn parse_partition_bound_value(&mut self) -> Result<PartitionBoundValue, ParserError> {
9114        if self.parse_keyword(Keyword::MINVALUE) {
9115            Ok(PartitionBoundValue::MinValue)
9116        } else if self.parse_keyword(Keyword::MAXVALUE) {
9117            Ok(PartitionBoundValue::MaxValue)
9118        } else {
9119            Ok(PartitionBoundValue::Expr(self.parse_expr()?))
9120        }
9121    }
9122
9123    /// Parse configuration like inheritance, partitioning, clustering information during the table creation.
9124    ///
9125    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#syntax_2)
9126    /// [PostgreSQL](https://www.postgresql.org/docs/current/ddl-partitioning.html)
9127    /// [MySql](https://dev.mysql.com/doc/refman/8.4/en/create-table.html)
9128    fn parse_optional_create_table_config(
9129        &mut self,
9130    ) -> Result<CreateTableConfiguration, ParserError> {
9131        let mut table_options = CreateTableOptions::None;
9132
9133        let inherits = if self.parse_keyword(Keyword::INHERITS) {
9134            Some(self.parse_parenthesized_qualified_column_list(IsOptional::Mandatory, false)?)
9135        } else {
9136            None
9137        };
9138
9139        // PostgreSQL supports `WITH ( options )`, before `AS`
9140        let with_options = self.parse_options(Keyword::WITH)?;
9141        if !with_options.is_empty() {
9142            table_options = CreateTableOptions::With(with_options)
9143        }
9144
9145        let table_properties = self.parse_options(Keyword::TBLPROPERTIES)?;
9146        if !table_properties.is_empty() {
9147            table_options = CreateTableOptions::TableProperties(table_properties);
9148        }
9149        let partition_by = if dialect_of!(self is BigQueryDialect | PostgreSqlDialect | GenericDialect)
9150            && self.parse_keywords(&[Keyword::PARTITION, Keyword::BY])
9151        {
9152            Some(Box::new(self.parse_expr()?))
9153        } else {
9154            None
9155        };
9156
9157        let mut cluster_by = None;
9158        if dialect_of!(self is BigQueryDialect | GenericDialect) {
9159            if self.parse_keywords(&[Keyword::CLUSTER, Keyword::BY]) {
9160                cluster_by = Some(WrappedCollection::NoWrapping(
9161                    self.parse_comma_separated(|p| p.parse_expr())?,
9162                ));
9163            };
9164
9165            if let Token::Word(word) = &self.peek_token_ref().token {
9166                if word.keyword == Keyword::OPTIONS {
9167                    table_options =
9168                        CreateTableOptions::Options(self.parse_options(Keyword::OPTIONS)?)
9169                }
9170            };
9171        }
9172
9173        if !dialect_of!(self is HiveDialect) && table_options == CreateTableOptions::None {
9174            let plain_options = self.parse_plain_options()?;
9175            if !plain_options.is_empty() {
9176                table_options = CreateTableOptions::Plain(plain_options)
9177            }
9178        };
9179
9180        Ok(CreateTableConfiguration {
9181            partition_by,
9182            cluster_by,
9183            inherits,
9184            table_options,
9185        })
9186    }
9187
9188    fn parse_plain_option(&mut self) -> Result<Option<SqlOption>, ParserError> {
9189        // Single parameter option
9190        // <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
9191        if self.parse_keywords(&[Keyword::START, Keyword::TRANSACTION]) {
9192            return Ok(Some(SqlOption::Ident(Ident::new("START TRANSACTION"))));
9193        }
9194
9195        // Custom option
9196        // <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
9197        if self.parse_keywords(&[Keyword::COMMENT]) {
9198            let has_eq = self.consume_token(&Token::Eq);
9199            let value = self.next_token();
9200
9201            let comment = match (has_eq, value.token) {
9202                (true, Token::SingleQuotedString(s)) => {
9203                    Ok(Some(SqlOption::Comment(CommentDef::WithEq(s))))
9204                }
9205                (false, Token::SingleQuotedString(s)) => {
9206                    Ok(Some(SqlOption::Comment(CommentDef::WithoutEq(s))))
9207                }
9208                (_, token) => {
9209                    self.expected("Token::SingleQuotedString", TokenWithSpan::wrap(token))
9210                }
9211            };
9212            return comment;
9213        }
9214
9215        // <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
9216        // <https://clickhouse.com/docs/sql-reference/statements/create/table>
9217        if self.parse_keywords(&[Keyword::ENGINE]) {
9218            let _ = self.consume_token(&Token::Eq);
9219            let value = self.next_token();
9220
9221            let engine = match value.token {
9222                Token::Word(w) => {
9223                    let parameters = if self.peek_token_ref().token == Token::LParen {
9224                        self.parse_parenthesized_identifiers()?
9225                    } else {
9226                        vec![]
9227                    };
9228
9229                    Ok(Some(SqlOption::NamedParenthesizedList(
9230                        NamedParenthesizedList {
9231                            key: Ident::new("ENGINE"),
9232                            name: Some(Ident::new(w.value)),
9233                            values: parameters,
9234                        },
9235                    )))
9236                }
9237                _ => {
9238                    return self.expected("Token::Word", value)?;
9239                }
9240            };
9241
9242            return engine;
9243        }
9244
9245        // <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
9246        if self.parse_keywords(&[Keyword::TABLESPACE]) {
9247            let _ = self.consume_token(&Token::Eq);
9248            let value = self.next_token();
9249
9250            let tablespace = match value.token {
9251                Token::Word(Word { value: name, .. }) | Token::SingleQuotedString(name) => {
9252                    let storage = match self.parse_keyword(Keyword::STORAGE) {
9253                        true => {
9254                            let _ = self.consume_token(&Token::Eq);
9255                            let storage_token = self.next_token();
9256                            match &storage_token.token {
9257                                Token::Word(w) => match w.value.to_uppercase().as_str() {
9258                                    "DISK" => Some(StorageType::Disk),
9259                                    "MEMORY" => Some(StorageType::Memory),
9260                                    _ => self
9261                                        .expected("Storage type (DISK or MEMORY)", storage_token)?,
9262                                },
9263                                _ => self.expected("Token::Word", storage_token)?,
9264                            }
9265                        }
9266                        false => None,
9267                    };
9268
9269                    Ok(Some(SqlOption::TableSpace(TablespaceOption {
9270                        name,
9271                        storage,
9272                    })))
9273                }
9274                _ => {
9275                    return self.expected("Token::Word", value)?;
9276                }
9277            };
9278
9279            return tablespace;
9280        }
9281
9282        // <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
9283        if self.parse_keyword(Keyword::UNION) {
9284            let _ = self.consume_token(&Token::Eq);
9285            let value = self.next_token();
9286
9287            match value.token {
9288                Token::LParen => {
9289                    let tables: Vec<Ident> =
9290                        self.parse_comma_separated0(Parser::parse_identifier, Token::RParen)?;
9291                    self.expect_token(&Token::RParen)?;
9292
9293                    return Ok(Some(SqlOption::NamedParenthesizedList(
9294                        NamedParenthesizedList {
9295                            key: Ident::new("UNION"),
9296                            name: None,
9297                            values: tables,
9298                        },
9299                    )));
9300                }
9301                _ => {
9302                    return self.expected("Token::LParen", value)?;
9303                }
9304            }
9305        }
9306
9307        // Key/Value parameter option
9308        let key = if self.parse_keywords(&[Keyword::DEFAULT, Keyword::CHARSET]) {
9309            Ident::new("DEFAULT CHARSET")
9310        } else if self.parse_keyword(Keyword::CHARSET) {
9311            Ident::new("CHARSET")
9312        } else if self.parse_keywords(&[Keyword::DEFAULT, Keyword::CHARACTER, Keyword::SET]) {
9313            Ident::new("DEFAULT CHARACTER SET")
9314        } else if self.parse_keywords(&[Keyword::CHARACTER, Keyword::SET]) {
9315            Ident::new("CHARACTER SET")
9316        } else if self.parse_keywords(&[Keyword::DEFAULT, Keyword::COLLATE]) {
9317            Ident::new("DEFAULT COLLATE")
9318        } else if self.parse_keyword(Keyword::COLLATE) {
9319            Ident::new("COLLATE")
9320        } else if self.parse_keywords(&[Keyword::DATA, Keyword::DIRECTORY]) {
9321            Ident::new("DATA DIRECTORY")
9322        } else if self.parse_keywords(&[Keyword::INDEX, Keyword::DIRECTORY]) {
9323            Ident::new("INDEX DIRECTORY")
9324        } else if self.parse_keyword(Keyword::KEY_BLOCK_SIZE) {
9325            Ident::new("KEY_BLOCK_SIZE")
9326        } else if self.parse_keyword(Keyword::ROW_FORMAT) {
9327            Ident::new("ROW_FORMAT")
9328        } else if self.parse_keyword(Keyword::PACK_KEYS) {
9329            Ident::new("PACK_KEYS")
9330        } else if self.parse_keyword(Keyword::STATS_AUTO_RECALC) {
9331            Ident::new("STATS_AUTO_RECALC")
9332        } else if self.parse_keyword(Keyword::STATS_PERSISTENT) {
9333            Ident::new("STATS_PERSISTENT")
9334        } else if self.parse_keyword(Keyword::STATS_SAMPLE_PAGES) {
9335            Ident::new("STATS_SAMPLE_PAGES")
9336        } else if self.parse_keyword(Keyword::DELAY_KEY_WRITE) {
9337            Ident::new("DELAY_KEY_WRITE")
9338        } else if self.parse_keyword(Keyword::COMPRESSION) {
9339            Ident::new("COMPRESSION")
9340        } else if self.parse_keyword(Keyword::ENCRYPTION) {
9341            Ident::new("ENCRYPTION")
9342        } else if self.parse_keyword(Keyword::MAX_ROWS) {
9343            Ident::new("MAX_ROWS")
9344        } else if self.parse_keyword(Keyword::MIN_ROWS) {
9345            Ident::new("MIN_ROWS")
9346        } else if self.parse_keyword(Keyword::AUTOEXTEND_SIZE) {
9347            Ident::new("AUTOEXTEND_SIZE")
9348        } else if self.parse_keyword(Keyword::AVG_ROW_LENGTH) {
9349            Ident::new("AVG_ROW_LENGTH")
9350        } else if self.parse_keyword(Keyword::CHECKSUM) {
9351            Ident::new("CHECKSUM")
9352        } else if self.parse_keyword(Keyword::CONNECTION) {
9353            Ident::new("CONNECTION")
9354        } else if self.parse_keyword(Keyword::ENGINE_ATTRIBUTE) {
9355            Ident::new("ENGINE_ATTRIBUTE")
9356        } else if self.parse_keyword(Keyword::PASSWORD) {
9357            Ident::new("PASSWORD")
9358        } else if self.parse_keyword(Keyword::SECONDARY_ENGINE_ATTRIBUTE) {
9359            Ident::new("SECONDARY_ENGINE_ATTRIBUTE")
9360        } else if self.parse_keyword(Keyword::INSERT_METHOD) {
9361            Ident::new("INSERT_METHOD")
9362        } else if self.parse_keyword(Keyword::AUTO_INCREMENT) {
9363            Ident::new("AUTO_INCREMENT")
9364        } else {
9365            return Ok(None);
9366        };
9367
9368        let _ = self.consume_token(&Token::Eq);
9369
9370        let value = match self
9371            .maybe_parse(|parser| parser.parse_value())?
9372            .map(Expr::Value)
9373        {
9374            Some(expr) => expr,
9375            None => Expr::Identifier(self.parse_identifier()?),
9376        };
9377
9378        Ok(Some(SqlOption::KeyValue { key, value }))
9379    }
9380
9381    /// Parse plain options.
9382    pub fn parse_plain_options(&mut self) -> Result<Vec<SqlOption>, ParserError> {
9383        let mut options = Vec::new();
9384
9385        while let Some(option) = self.parse_plain_option()? {
9386            options.push(option);
9387            // Some dialects support comma-separated options; it shouldn't introduce ambiguity to
9388            // consume it for all dialects.
9389            let _ = self.consume_token(&Token::Comma);
9390        }
9391
9392        Ok(options)
9393    }
9394
9395    /// Parse optional inline comment.
9396    pub fn parse_optional_inline_comment(&mut self) -> Result<Option<CommentDef>, ParserError> {
9397        let comment = if self.parse_keyword(Keyword::COMMENT) {
9398            let has_eq = self.consume_token(&Token::Eq);
9399            let comment = self.parse_comment_value()?;
9400            Some(if has_eq {
9401                CommentDef::WithEq(comment)
9402            } else {
9403                CommentDef::WithoutEq(comment)
9404            })
9405        } else {
9406            None
9407        };
9408        Ok(comment)
9409    }
9410
9411    /// Parse comment value.
9412    pub fn parse_comment_value(&mut self) -> Result<String, ParserError> {
9413        let next_token = self.next_token();
9414        let value = match next_token.token {
9415            Token::SingleQuotedString(str) => str,
9416            Token::DollarQuotedString(str) => str.value,
9417            _ => self.expected("string literal", next_token)?,
9418        };
9419        Ok(value)
9420    }
9421
9422    /// Parse optional procedure parameters.
9423    pub fn parse_optional_procedure_parameters(
9424        &mut self,
9425    ) -> Result<Option<Vec<ProcedureParam>>, ParserError> {
9426        let mut params = vec![];
9427        if !self.consume_token(&Token::LParen) || self.consume_token(&Token::RParen) {
9428            return Ok(Some(params));
9429        }
9430        loop {
9431            if let Token::Word(_) = &self.peek_token_ref().token {
9432                params.push(self.parse_procedure_param()?)
9433            }
9434            let comma = self.consume_token(&Token::Comma);
9435            if self.consume_token(&Token::RParen) {
9436                // allow a trailing comma, even though it's not in standard
9437                break;
9438            } else if !comma {
9439                return self.expected_ref(
9440                    "',' or ')' after parameter definition",
9441                    self.peek_token_ref(),
9442                );
9443            }
9444        }
9445        Ok(Some(params))
9446    }
9447
9448    /// Parse columns and constraints.
9449    pub fn parse_columns(&mut self) -> Result<(Vec<ColumnDef>, Vec<TableConstraint>), ParserError> {
9450        let mut columns = vec![];
9451        let mut constraints = vec![];
9452        if !self.consume_token(&Token::LParen) || self.consume_token(&Token::RParen) {
9453            return Ok((columns, constraints));
9454        }
9455
9456        loop {
9457            if let Some(constraint) = self.parse_optional_table_constraint()? {
9458                constraints.push(constraint);
9459            } else if let Token::Word(_) = &self.peek_token_ref().token {
9460                columns.push(self.parse_column_def()?);
9461            } else {
9462                return self.expected_ref(
9463                    "column name or constraint definition",
9464                    self.peek_token_ref(),
9465                );
9466            }
9467
9468            let comma = self.consume_token(&Token::Comma);
9469            let rparen = self.peek_token_ref().token == Token::RParen;
9470
9471            if !comma && !rparen {
9472                return self
9473                    .expected_ref("',' or ')' after column definition", self.peek_token_ref());
9474            };
9475
9476            if rparen
9477                && (!comma
9478                    || self.dialect.supports_column_definition_trailing_commas()
9479                    || self.options.trailing_commas)
9480            {
9481                let _ = self.consume_token(&Token::RParen);
9482                break;
9483            }
9484        }
9485
9486        Ok((columns, constraints))
9487    }
9488
9489    /// Parse procedure parameter.
9490    pub fn parse_procedure_param(&mut self) -> Result<ProcedureParam, ParserError> {
9491        let mode = if self.parse_keyword(Keyword::IN) {
9492            Some(ArgMode::In)
9493        } else if self.parse_keyword(Keyword::OUT) {
9494            Some(ArgMode::Out)
9495        } else if self.parse_keyword(Keyword::INOUT) {
9496            Some(ArgMode::InOut)
9497        } else {
9498            None
9499        };
9500        let name = self.parse_identifier()?;
9501        let data_type = self.parse_data_type()?;
9502        let default = if self.consume_token(&Token::Eq) {
9503            Some(self.parse_expr()?)
9504        } else {
9505            None
9506        };
9507
9508        Ok(ProcedureParam {
9509            name,
9510            data_type,
9511            mode,
9512            default,
9513        })
9514    }
9515
9516    /// Parse column definition.
9517    pub fn parse_column_def(&mut self) -> Result<ColumnDef, ParserError> {
9518        self.parse_column_def_inner(false)
9519    }
9520
9521    fn parse_column_def_inner(
9522        &mut self,
9523        optional_data_type: bool,
9524    ) -> Result<ColumnDef, ParserError> {
9525        let col_name = self.parse_identifier()?;
9526        let data_type = if self.is_column_type_sqlite_unspecified() {
9527            DataType::Unspecified
9528        } else if optional_data_type {
9529            self.maybe_parse(|parser| parser.parse_data_type())?
9530                .unwrap_or(DataType::Unspecified)
9531        } else {
9532            self.parse_data_type()?
9533        };
9534        let mut options = vec![];
9535        loop {
9536            if self.parse_keyword(Keyword::CONSTRAINT) {
9537                let name = Some(self.parse_identifier()?);
9538                if let Some(option) = self.parse_optional_column_option()? {
9539                    options.push(ColumnOptionDef { name, option });
9540                } else {
9541                    return self.expected_ref(
9542                        "constraint details after CONSTRAINT <name>",
9543                        self.peek_token_ref(),
9544                    );
9545                }
9546            } else if let Some(option) = self.parse_optional_column_option()? {
9547                options.push(ColumnOptionDef { name: None, option });
9548            } else {
9549                break;
9550            };
9551        }
9552        Ok(ColumnDef {
9553            name: col_name,
9554            data_type,
9555            options,
9556        })
9557    }
9558
9559    fn is_column_type_sqlite_unspecified(&mut self) -> bool {
9560        if dialect_of!(self is SQLiteDialect) {
9561            match &self.peek_token_ref().token {
9562                Token::Word(word) => matches!(
9563                    word.keyword,
9564                    Keyword::CONSTRAINT
9565                        | Keyword::PRIMARY
9566                        | Keyword::NOT
9567                        | Keyword::UNIQUE
9568                        | Keyword::CHECK
9569                        | Keyword::DEFAULT
9570                        | Keyword::COLLATE
9571                        | Keyword::REFERENCES
9572                        | Keyword::GENERATED
9573                        | Keyword::AS
9574                ),
9575                _ => true, // e.g. comma immediately after column name
9576            }
9577        } else {
9578            false
9579        }
9580    }
9581
9582    /// Parse optional column option.
9583    pub fn parse_optional_column_option(&mut self) -> Result<Option<ColumnOption>, ParserError> {
9584        if let Some(option) = self.dialect.parse_column_option(self)? {
9585            return option;
9586        }
9587
9588        self.with_state(
9589            ColumnDefinition,
9590            |parser| -> Result<Option<ColumnOption>, ParserError> {
9591                parser.parse_optional_column_option_inner()
9592            },
9593        )
9594    }
9595
9596    fn parse_optional_column_option_inner(&mut self) -> Result<Option<ColumnOption>, ParserError> {
9597        if self.parse_keywords(&[Keyword::CHARACTER, Keyword::SET]) {
9598            Ok(Some(ColumnOption::CharacterSet(
9599                self.parse_object_name(false)?,
9600            )))
9601        } else if self.parse_keywords(&[Keyword::COLLATE]) {
9602            Ok(Some(ColumnOption::Collation(
9603                self.parse_object_name(false)?,
9604            )))
9605        } else if self.parse_keywords(&[Keyword::NOT, Keyword::NULL]) {
9606            Ok(Some(ColumnOption::NotNull))
9607        } else if self.parse_keywords(&[Keyword::COMMENT]) {
9608            Ok(Some(ColumnOption::Comment(self.parse_comment_value()?)))
9609        } else if self.parse_keyword(Keyword::NULL) {
9610            Ok(Some(ColumnOption::Null))
9611        } else if self.parse_keyword(Keyword::DEFAULT) {
9612            Ok(Some(ColumnOption::Default(self.parse_expr()?)))
9613        } else if dialect_of!(self is ClickHouseDialect| GenericDialect)
9614            && self.parse_keyword(Keyword::MATERIALIZED)
9615        {
9616            Ok(Some(ColumnOption::Materialized(self.parse_expr()?)))
9617        } else if dialect_of!(self is ClickHouseDialect| GenericDialect)
9618            && self.parse_keyword(Keyword::ALIAS)
9619        {
9620            Ok(Some(ColumnOption::Alias(self.parse_expr()?)))
9621        } else if dialect_of!(self is ClickHouseDialect| GenericDialect)
9622            && self.parse_keyword(Keyword::EPHEMERAL)
9623        {
9624            // The expression is optional for the EPHEMERAL syntax, so we need to check
9625            // if the column definition has remaining tokens before parsing the expression.
9626            if matches!(self.peek_token_ref().token, Token::Comma | Token::RParen) {
9627                Ok(Some(ColumnOption::Ephemeral(None)))
9628            } else {
9629                Ok(Some(ColumnOption::Ephemeral(Some(self.parse_expr()?))))
9630            }
9631        } else if self.parse_keywords(&[Keyword::PRIMARY, Keyword::KEY]) {
9632            let characteristics = self.parse_constraint_characteristics()?;
9633            Ok(Some(
9634                PrimaryKeyConstraint {
9635                    name: None,
9636                    index_name: None,
9637                    index_type: None,
9638                    columns: vec![],
9639                    index_options: vec![],
9640                    characteristics,
9641                }
9642                .into(),
9643            ))
9644        } else if self.parse_keyword(Keyword::UNIQUE) {
9645            let index_type_display =
9646                if self.dialect.supports_key_column_option() && self.parse_keyword(Keyword::KEY) {
9647                    KeyOrIndexDisplay::Key
9648                } else {
9649                    KeyOrIndexDisplay::None
9650                };
9651            let characteristics = self.parse_constraint_characteristics()?;
9652            Ok(Some(
9653                UniqueConstraint {
9654                    name: None,
9655                    index_name: None,
9656                    index_type_display,
9657                    index_type: None,
9658                    columns: vec![],
9659                    index_options: vec![],
9660                    characteristics,
9661                    nulls_distinct: NullsDistinctOption::None,
9662                }
9663                .into(),
9664            ))
9665        } else if self.dialect.supports_key_column_option() && self.parse_keyword(Keyword::KEY) {
9666            // In MySQL, `KEY` in a column definition is shorthand for `PRIMARY KEY`.
9667            // See: https://dev.mysql.com/doc/refman/8.4/en/create-table.html
9668            let characteristics = self.parse_constraint_characteristics()?;
9669            Ok(Some(
9670                PrimaryKeyConstraint {
9671                    name: None,
9672                    index_name: None,
9673                    index_type: None,
9674                    columns: vec![],
9675                    index_options: vec![],
9676                    characteristics,
9677                }
9678                .into(),
9679            ))
9680        } else if self.parse_keyword(Keyword::REFERENCES) {
9681            let foreign_table = self.parse_object_name(false)?;
9682            // PostgreSQL allows omitting the column list and
9683            // uses the primary key column of the foreign table by default
9684            let referred_columns = self.parse_parenthesized_column_list(Optional, false)?;
9685            let mut match_kind = None;
9686            let mut on_delete = None;
9687            let mut on_update = None;
9688            loop {
9689                if match_kind.is_none() && self.parse_keyword(Keyword::MATCH) {
9690                    match_kind = Some(self.parse_match_kind()?);
9691                } else if on_delete.is_none()
9692                    && self.parse_keywords(&[Keyword::ON, Keyword::DELETE])
9693                {
9694                    on_delete = Some(self.parse_referential_action()?);
9695                } else if on_update.is_none()
9696                    && self.parse_keywords(&[Keyword::ON, Keyword::UPDATE])
9697                {
9698                    on_update = Some(self.parse_referential_action()?);
9699                } else {
9700                    break;
9701                }
9702            }
9703            let characteristics = self.parse_constraint_characteristics()?;
9704
9705            Ok(Some(
9706                ForeignKeyConstraint {
9707                    name: None,       // Column-level constraints don't have names
9708                    index_name: None, // Not applicable for column-level constraints
9709                    columns: vec![],  // Not applicable for column-level constraints
9710                    foreign_table,
9711                    referred_columns,
9712                    on_delete,
9713                    on_update,
9714                    match_kind,
9715                    characteristics,
9716                }
9717                .into(),
9718            ))
9719        } else if self.parse_keyword(Keyword::CHECK) {
9720            self.expect_token(&Token::LParen)?;
9721            // since `CHECK` requires parentheses, we can parse the inner expression in ParserState::Normal
9722            let expr: Expr = self.with_state(ParserState::Normal, |p| p.parse_expr())?;
9723            self.expect_token(&Token::RParen)?;
9724
9725            let enforced = if self.parse_keyword(Keyword::ENFORCED) {
9726                Some(true)
9727            } else if self.parse_keywords(&[Keyword::NOT, Keyword::ENFORCED]) {
9728                Some(false)
9729            } else {
9730                None
9731            };
9732
9733            Ok(Some(
9734                CheckConstraint {
9735                    name: None, // Column-level check constraints don't have names
9736                    expr: Box::new(expr),
9737                    enforced,
9738                }
9739                .into(),
9740            ))
9741        } else if self.parse_keyword(Keyword::AUTO_INCREMENT)
9742            && dialect_of!(self is MySqlDialect | GenericDialect)
9743        {
9744            // Support AUTO_INCREMENT for MySQL
9745            Ok(Some(ColumnOption::DialectSpecific(vec![
9746                Token::make_keyword("AUTO_INCREMENT"),
9747            ])))
9748        } else if self.parse_keyword(Keyword::AUTOINCREMENT)
9749            && dialect_of!(self is SQLiteDialect |  GenericDialect)
9750        {
9751            // Support AUTOINCREMENT for SQLite
9752            Ok(Some(ColumnOption::DialectSpecific(vec![
9753                Token::make_keyword("AUTOINCREMENT"),
9754            ])))
9755        } else if self.parse_keyword(Keyword::ASC)
9756            && self.dialect.supports_asc_desc_in_column_definition()
9757        {
9758            // Support ASC for SQLite
9759            Ok(Some(ColumnOption::DialectSpecific(vec![
9760                Token::make_keyword("ASC"),
9761            ])))
9762        } else if self.parse_keyword(Keyword::DESC)
9763            && self.dialect.supports_asc_desc_in_column_definition()
9764        {
9765            // Support DESC for SQLite
9766            Ok(Some(ColumnOption::DialectSpecific(vec![
9767                Token::make_keyword("DESC"),
9768            ])))
9769        } else if self.parse_keywords(&[Keyword::ON, Keyword::UPDATE])
9770            && dialect_of!(self is MySqlDialect | GenericDialect)
9771        {
9772            let expr = self.parse_expr()?;
9773            Ok(Some(ColumnOption::OnUpdate(expr)))
9774        } else if self.parse_keyword(Keyword::GENERATED) {
9775            self.parse_optional_column_option_generated()
9776        } else if dialect_of!(self is BigQueryDialect | GenericDialect)
9777            && self.parse_keyword(Keyword::OPTIONS)
9778        {
9779            self.prev_token();
9780            Ok(Some(ColumnOption::Options(
9781                self.parse_options(Keyword::OPTIONS)?,
9782            )))
9783        } else if self.parse_keyword(Keyword::AS)
9784            && dialect_of!(self is MySqlDialect | SQLiteDialect | DuckDbDialect | GenericDialect)
9785        {
9786            self.parse_optional_column_option_as()
9787        } else if self.parse_keyword(Keyword::SRID)
9788            && dialect_of!(self is MySqlDialect | GenericDialect)
9789        {
9790            Ok(Some(ColumnOption::Srid(Box::new(self.parse_expr()?))))
9791        } else if self.parse_keyword(Keyword::IDENTITY)
9792            && dialect_of!(self is MsSqlDialect | GenericDialect)
9793        {
9794            let parameters = if self.consume_token(&Token::LParen) {
9795                let seed = self.parse_number()?;
9796                self.expect_token(&Token::Comma)?;
9797                let increment = self.parse_number()?;
9798                self.expect_token(&Token::RParen)?;
9799
9800                Some(IdentityPropertyFormatKind::FunctionCall(
9801                    IdentityParameters { seed, increment },
9802                ))
9803            } else {
9804                None
9805            };
9806            Ok(Some(ColumnOption::Identity(
9807                IdentityPropertyKind::Identity(IdentityProperty {
9808                    parameters,
9809                    order: None,
9810                }),
9811            )))
9812        } else if dialect_of!(self is SQLiteDialect | GenericDialect)
9813            && self.parse_keywords(&[Keyword::ON, Keyword::CONFLICT])
9814        {
9815            // Support ON CONFLICT for SQLite
9816            Ok(Some(ColumnOption::OnConflict(
9817                self.expect_one_of_keywords(&[
9818                    Keyword::ROLLBACK,
9819                    Keyword::ABORT,
9820                    Keyword::FAIL,
9821                    Keyword::IGNORE,
9822                    Keyword::REPLACE,
9823                ])?,
9824            )))
9825        } else if self.parse_keyword(Keyword::INVISIBLE) {
9826            Ok(Some(ColumnOption::Invisible))
9827        } else {
9828            Ok(None)
9829        }
9830    }
9831
9832    pub(crate) fn parse_tag(&mut self) -> Result<Tag, ParserError> {
9833        let name = self.parse_object_name(false)?;
9834        self.expect_token(&Token::Eq)?;
9835        let value = self.parse_literal_string()?;
9836
9837        Ok(Tag::new(name, value))
9838    }
9839
9840    fn parse_optional_column_option_generated(
9841        &mut self,
9842    ) -> Result<Option<ColumnOption>, ParserError> {
9843        if self.parse_keywords(&[Keyword::ALWAYS, Keyword::AS, Keyword::IDENTITY]) {
9844            let mut sequence_options = vec![];
9845            if self.expect_token(&Token::LParen).is_ok() {
9846                sequence_options = self.parse_create_sequence_options()?;
9847                self.expect_token(&Token::RParen)?;
9848            }
9849            Ok(Some(ColumnOption::Generated {
9850                generated_as: GeneratedAs::Always,
9851                sequence_options: Some(sequence_options),
9852                generation_expr: None,
9853                generation_expr_mode: None,
9854                generated_keyword: true,
9855            }))
9856        } else if self.parse_keywords(&[
9857            Keyword::BY,
9858            Keyword::DEFAULT,
9859            Keyword::AS,
9860            Keyword::IDENTITY,
9861        ]) {
9862            let mut sequence_options = vec![];
9863            if self.expect_token(&Token::LParen).is_ok() {
9864                sequence_options = self.parse_create_sequence_options()?;
9865                self.expect_token(&Token::RParen)?;
9866            }
9867            Ok(Some(ColumnOption::Generated {
9868                generated_as: GeneratedAs::ByDefault,
9869                sequence_options: Some(sequence_options),
9870                generation_expr: None,
9871                generation_expr_mode: None,
9872                generated_keyword: true,
9873            }))
9874        } else if self.parse_keywords(&[Keyword::ALWAYS, Keyword::AS]) {
9875            if self.expect_token(&Token::LParen).is_ok() {
9876                let expr: Expr = self.with_state(ParserState::Normal, |p| p.parse_expr())?;
9877                self.expect_token(&Token::RParen)?;
9878                let (gen_as, expr_mode) = if self.parse_keywords(&[Keyword::STORED]) {
9879                    Ok((
9880                        GeneratedAs::ExpStored,
9881                        Some(GeneratedExpressionMode::Stored),
9882                    ))
9883                } else if dialect_of!(self is PostgreSqlDialect) {
9884                    // Postgres' AS IDENTITY branches are above, this one needs STORED
9885                    self.expected_ref("STORED", self.peek_token_ref())
9886                } else if self.parse_keywords(&[Keyword::VIRTUAL]) {
9887                    Ok((GeneratedAs::Always, Some(GeneratedExpressionMode::Virtual)))
9888                } else {
9889                    Ok((GeneratedAs::Always, None))
9890                }?;
9891
9892                Ok(Some(ColumnOption::Generated {
9893                    generated_as: gen_as,
9894                    sequence_options: None,
9895                    generation_expr: Some(expr),
9896                    generation_expr_mode: expr_mode,
9897                    generated_keyword: true,
9898                }))
9899            } else {
9900                Ok(None)
9901            }
9902        } else {
9903            Ok(None)
9904        }
9905    }
9906
9907    fn parse_optional_column_option_as(&mut self) -> Result<Option<ColumnOption>, ParserError> {
9908        // Some DBs allow 'AS (expr)', shorthand for GENERATED ALWAYS AS
9909        self.expect_token(&Token::LParen)?;
9910        let expr = self.parse_expr()?;
9911        self.expect_token(&Token::RParen)?;
9912
9913        let (gen_as, expr_mode) = if self.parse_keywords(&[Keyword::STORED]) {
9914            (
9915                GeneratedAs::ExpStored,
9916                Some(GeneratedExpressionMode::Stored),
9917            )
9918        } else if self.parse_keywords(&[Keyword::VIRTUAL]) {
9919            (GeneratedAs::Always, Some(GeneratedExpressionMode::Virtual))
9920        } else {
9921            (GeneratedAs::Always, None)
9922        };
9923
9924        Ok(Some(ColumnOption::Generated {
9925            generated_as: gen_as,
9926            sequence_options: None,
9927            generation_expr: Some(expr),
9928            generation_expr_mode: expr_mode,
9929            generated_keyword: false,
9930        }))
9931    }
9932
9933    /// Parse optional `CLUSTERED BY` clause for Hive/Generic dialects.
9934    pub fn parse_optional_clustered_by(&mut self) -> Result<Option<ClusteredBy>, ParserError> {
9935        let clustered_by = if dialect_of!(self is HiveDialect|GenericDialect)
9936            && self.parse_keywords(&[Keyword::CLUSTERED, Keyword::BY])
9937        {
9938            let columns = self.parse_parenthesized_column_list(Mandatory, false)?;
9939
9940            let sorted_by = if self.parse_keywords(&[Keyword::SORTED, Keyword::BY]) {
9941                self.expect_token(&Token::LParen)?;
9942                let sorted_by_columns = self.parse_comma_separated(|p| p.parse_order_by_expr())?;
9943                self.expect_token(&Token::RParen)?;
9944                Some(sorted_by_columns)
9945            } else {
9946                None
9947            };
9948
9949            self.expect_keyword_is(Keyword::INTO)?;
9950            let num_buckets = self.parse_number_value()?.value;
9951            self.expect_keyword_is(Keyword::BUCKETS)?;
9952            Some(ClusteredBy {
9953                columns,
9954                sorted_by,
9955                num_buckets,
9956            })
9957        } else {
9958            None
9959        };
9960        Ok(clustered_by)
9961    }
9962
9963    /// Parse a referential action used in foreign key clauses.
9964    ///
9965    /// Recognized forms: `RESTRICT`, `CASCADE`, `SET NULL`, `NO ACTION`, `SET DEFAULT`.
9966    pub fn parse_referential_action(&mut self) -> Result<ReferentialAction, ParserError> {
9967        if self.parse_keyword(Keyword::RESTRICT) {
9968            Ok(ReferentialAction::Restrict)
9969        } else if self.parse_keyword(Keyword::CASCADE) {
9970            Ok(ReferentialAction::Cascade)
9971        } else if self.parse_keywords(&[Keyword::SET, Keyword::NULL]) {
9972            Ok(ReferentialAction::SetNull)
9973        } else if self.parse_keywords(&[Keyword::NO, Keyword::ACTION]) {
9974            Ok(ReferentialAction::NoAction)
9975        } else if self.parse_keywords(&[Keyword::SET, Keyword::DEFAULT]) {
9976            Ok(ReferentialAction::SetDefault)
9977        } else {
9978            self.expected_ref(
9979                "one of RESTRICT, CASCADE, SET NULL, NO ACTION or SET DEFAULT",
9980                self.peek_token_ref(),
9981            )
9982        }
9983    }
9984
9985    /// Parse a `MATCH` kind for constraint references: `FULL`, `PARTIAL`, or `SIMPLE`.
9986    pub fn parse_match_kind(&mut self) -> Result<ConstraintReferenceMatchKind, ParserError> {
9987        if self.parse_keyword(Keyword::FULL) {
9988            Ok(ConstraintReferenceMatchKind::Full)
9989        } else if self.parse_keyword(Keyword::PARTIAL) {
9990            Ok(ConstraintReferenceMatchKind::Partial)
9991        } else if self.parse_keyword(Keyword::SIMPLE) {
9992            Ok(ConstraintReferenceMatchKind::Simple)
9993        } else {
9994            self.expected_ref("one of FULL, PARTIAL or SIMPLE", self.peek_token_ref())
9995        }
9996    }
9997
9998    /// Parse `index_name [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]`
9999    /// after `{ PRIMARY KEY | UNIQUE } USING INDEX`.
10000    fn parse_constraint_using_index(
10001        &mut self,
10002        name: Option<Ident>,
10003    ) -> Result<ConstraintUsingIndex, ParserError> {
10004        let index_name = self.parse_identifier()?;
10005        let characteristics = self.parse_constraint_characteristics()?;
10006        Ok(ConstraintUsingIndex {
10007            name,
10008            index_name,
10009            characteristics,
10010        })
10011    }
10012
10013    /// Parse optional constraint characteristics such as `DEFERRABLE`, `INITIALLY` and `ENFORCED`.
10014    pub fn parse_constraint_characteristics(
10015        &mut self,
10016    ) -> Result<Option<ConstraintCharacteristics>, ParserError> {
10017        let mut cc = ConstraintCharacteristics::default();
10018
10019        loop {
10020            if cc.deferrable.is_none() && self.parse_keywords(&[Keyword::NOT, Keyword::DEFERRABLE])
10021            {
10022                cc.deferrable = Some(false);
10023            } else if cc.deferrable.is_none() && self.parse_keyword(Keyword::DEFERRABLE) {
10024                cc.deferrable = Some(true);
10025            } else if cc.initially.is_none() && self.parse_keyword(Keyword::INITIALLY) {
10026                if self.parse_keyword(Keyword::DEFERRED) {
10027                    cc.initially = Some(DeferrableInitial::Deferred);
10028                } else if self.parse_keyword(Keyword::IMMEDIATE) {
10029                    cc.initially = Some(DeferrableInitial::Immediate);
10030                } else {
10031                    self.expected_ref("one of DEFERRED or IMMEDIATE", self.peek_token_ref())?;
10032                }
10033            } else if cc.enforced.is_none() && self.parse_keyword(Keyword::ENFORCED) {
10034                cc.enforced = Some(true);
10035            } else if cc.enforced.is_none()
10036                && self.parse_keywords(&[Keyword::NOT, Keyword::ENFORCED])
10037            {
10038                cc.enforced = Some(false);
10039            } else {
10040                break;
10041            }
10042        }
10043
10044        if cc.deferrable.is_some() || cc.initially.is_some() || cc.enforced.is_some() {
10045            Ok(Some(cc))
10046        } else {
10047            Ok(None)
10048        }
10049    }
10050
10051    /// Parse an optional table constraint (e.g. `PRIMARY KEY`, `UNIQUE`, `FOREIGN KEY`, `CHECK`).
10052    pub fn parse_optional_table_constraint(
10053        &mut self,
10054    ) -> Result<Option<TableConstraint>, ParserError> {
10055        let name = if self.parse_keyword(Keyword::CONSTRAINT) {
10056            if self.dialect.supports_constraint_keyword_without_name()
10057                && self
10058                    .peek_one_of_keywords(&[
10059                        Keyword::CHECK,
10060                        Keyword::PRIMARY,
10061                        Keyword::UNIQUE,
10062                        Keyword::FOREIGN,
10063                    ])
10064                    .is_some()
10065            {
10066                None
10067            } else {
10068                Some(self.parse_identifier()?)
10069            }
10070        } else {
10071            None
10072        };
10073
10074        let next_token = self.next_token();
10075        match next_token.token {
10076            Token::Word(w) if w.keyword == Keyword::UNIQUE => {
10077                // PostgreSQL: UNIQUE USING INDEX index_name
10078                // https://www.postgresql.org/docs/current/sql-altertable.html
10079                if self.parse_keywords(&[Keyword::USING, Keyword::INDEX]) {
10080                    return Ok(Some(TableConstraint::UniqueUsingIndex(
10081                        self.parse_constraint_using_index(name)?,
10082                    )));
10083                }
10084
10085                let index_type_display = self.parse_index_type_display();
10086                if !dialect_of!(self is GenericDialect | MySqlDialect)
10087                    && !index_type_display.is_none()
10088                {
10089                    return self.expected_ref(
10090                        "`index_name` or `(column_name [, ...])`",
10091                        self.peek_token_ref(),
10092                    );
10093                }
10094
10095                let nulls_distinct = self.parse_optional_nulls_distinct()?;
10096
10097                // optional index name
10098                let index_name = self.parse_optional_ident()?;
10099                let index_type = self.parse_optional_using_then_index_type()?;
10100
10101                let columns = self.parse_parenthesized_index_column_list()?;
10102                let index_options = self.parse_index_options()?;
10103                let characteristics = self.parse_constraint_characteristics()?;
10104                Ok(Some(
10105                    UniqueConstraint {
10106                        name,
10107                        index_name,
10108                        index_type_display,
10109                        index_type,
10110                        columns,
10111                        index_options,
10112                        characteristics,
10113                        nulls_distinct,
10114                    }
10115                    .into(),
10116                ))
10117            }
10118            Token::Word(w) if w.keyword == Keyword::PRIMARY => {
10119                // after `PRIMARY` always stay `KEY`
10120                self.expect_keyword_is(Keyword::KEY)?;
10121
10122                // PostgreSQL: PRIMARY KEY USING INDEX index_name
10123                // https://www.postgresql.org/docs/current/sql-altertable.html
10124                if self.parse_keywords(&[Keyword::USING, Keyword::INDEX]) {
10125                    return Ok(Some(TableConstraint::PrimaryKeyUsingIndex(
10126                        self.parse_constraint_using_index(name)?,
10127                    )));
10128                }
10129
10130                // optional index name
10131                let index_name = self.parse_optional_ident()?;
10132                let index_type = self.parse_optional_using_then_index_type()?;
10133
10134                let columns = self.parse_parenthesized_index_column_list()?;
10135                let index_options = self.parse_index_options()?;
10136                let characteristics = self.parse_constraint_characteristics()?;
10137                Ok(Some(
10138                    PrimaryKeyConstraint {
10139                        name,
10140                        index_name,
10141                        index_type,
10142                        columns,
10143                        index_options,
10144                        characteristics,
10145                    }
10146                    .into(),
10147                ))
10148            }
10149            Token::Word(w) if w.keyword == Keyword::FOREIGN => {
10150                self.expect_keyword_is(Keyword::KEY)?;
10151                let index_name = self.parse_optional_ident()?;
10152                let columns = self.parse_parenthesized_column_list(Mandatory, false)?;
10153                self.expect_keyword_is(Keyword::REFERENCES)?;
10154                let foreign_table = self.parse_object_name(false)?;
10155                let referred_columns = self.parse_parenthesized_column_list(Optional, false)?;
10156                let mut match_kind = None;
10157                let mut on_delete = None;
10158                let mut on_update = None;
10159                loop {
10160                    if match_kind.is_none() && self.parse_keyword(Keyword::MATCH) {
10161                        match_kind = Some(self.parse_match_kind()?);
10162                    } else if on_delete.is_none()
10163                        && self.parse_keywords(&[Keyword::ON, Keyword::DELETE])
10164                    {
10165                        on_delete = Some(self.parse_referential_action()?);
10166                    } else if on_update.is_none()
10167                        && self.parse_keywords(&[Keyword::ON, Keyword::UPDATE])
10168                    {
10169                        on_update = Some(self.parse_referential_action()?);
10170                    } else {
10171                        break;
10172                    }
10173                }
10174
10175                let characteristics = self.parse_constraint_characteristics()?;
10176
10177                Ok(Some(
10178                    ForeignKeyConstraint {
10179                        name,
10180                        index_name,
10181                        columns,
10182                        foreign_table,
10183                        referred_columns,
10184                        on_delete,
10185                        on_update,
10186                        match_kind,
10187                        characteristics,
10188                    }
10189                    .into(),
10190                ))
10191            }
10192            Token::Word(w) if w.keyword == Keyword::CHECK => {
10193                self.expect_token(&Token::LParen)?;
10194                let expr = Box::new(self.parse_expr()?);
10195                self.expect_token(&Token::RParen)?;
10196
10197                let enforced = if self.parse_keyword(Keyword::ENFORCED) {
10198                    Some(true)
10199                } else if self.parse_keywords(&[Keyword::NOT, Keyword::ENFORCED]) {
10200                    Some(false)
10201                } else {
10202                    None
10203                };
10204
10205                Ok(Some(
10206                    CheckConstraint {
10207                        name,
10208                        expr,
10209                        enforced,
10210                    }
10211                    .into(),
10212                ))
10213            }
10214            Token::Word(w)
10215                if (w.keyword == Keyword::INDEX || w.keyword == Keyword::KEY)
10216                    && dialect_of!(self is GenericDialect | MySqlDialect)
10217                    && name.is_none() =>
10218            {
10219                let display_as_key = w.keyword == Keyword::KEY;
10220
10221                let name = match &self.peek_token_ref().token {
10222                    Token::Word(word) if word.keyword == Keyword::USING => None,
10223                    _ => self.parse_optional_ident()?,
10224                };
10225
10226                let index_type = self.parse_optional_using_then_index_type()?;
10227                let columns = self.parse_parenthesized_index_column_list()?;
10228                let index_options = self.parse_index_options()?;
10229
10230                Ok(Some(
10231                    IndexConstraint {
10232                        display_as_key,
10233                        name,
10234                        index_type,
10235                        columns,
10236                        index_options,
10237                    }
10238                    .into(),
10239                ))
10240            }
10241            Token::Word(w)
10242                if (w.keyword == Keyword::FULLTEXT || w.keyword == Keyword::SPATIAL)
10243                    && dialect_of!(self is GenericDialect | MySqlDialect) =>
10244            {
10245                if let Some(name) = name {
10246                    return self.expected(
10247                        "FULLTEXT or SPATIAL option without constraint name",
10248                        TokenWithSpan {
10249                            token: Token::make_keyword(&name.to_string()),
10250                            span: next_token.span,
10251                        },
10252                    );
10253                }
10254
10255                let fulltext = w.keyword == Keyword::FULLTEXT;
10256
10257                let index_type_display = self.parse_index_type_display();
10258
10259                let opt_index_name = self.parse_optional_ident()?;
10260
10261                let columns = self.parse_parenthesized_index_column_list()?;
10262                // MySQL index options (USING/COMMENT/WITH PARSER/VISIBLE/INVISIBLE).
10263                // `SHOW CREATE TABLE` emits `WITH PARSER ngram` (wrapped in a
10264                // `/*!50100 ... */` versioned comment that the tokenizer expands),
10265                // so this must be consumed here or the surrounding CREATE TABLE
10266                // loop rejects the leftover `WITH` token.
10267                let index_options = self.parse_index_options()?;
10268
10269                Ok(Some(
10270                    FullTextOrSpatialConstraint {
10271                        fulltext,
10272                        index_type_display,
10273                        opt_index_name,
10274                        columns,
10275                        index_options,
10276                    }
10277                    .into(),
10278                ))
10279            }
10280            Token::Word(w)
10281                if w.keyword == Keyword::EXCLUDE && self.dialect.supports_exclude_constraint() =>
10282            {
10283                // `EXCLUDE` is a non-reserved keyword in PostgreSQL, so it is a
10284                // valid column name. Only treat it as an exclusion constraint
10285                // when it begins one (named, or followed by `USING` / `(`);
10286                // otherwise backtrack and let it parse as a column.
10287                if name.is_some()
10288                    || self.peek_keyword(Keyword::USING)
10289                    || self.peek_token_ref().token == Token::LParen
10290                {
10291                    Ok(Some(self.parse_exclude_constraint(name)?.into()))
10292                } else {
10293                    self.prev_token();
10294                    Ok(None)
10295                }
10296            }
10297            _ => {
10298                if name.is_some() {
10299                    self.expected("PRIMARY, UNIQUE, FOREIGN, CHECK, or EXCLUDE", next_token)
10300                } else {
10301                    self.prev_token();
10302                    Ok(None)
10303                }
10304            }
10305        }
10306    }
10307
10308    // The leading `EXCLUDE` keyword is already consumed by the caller.
10309    fn parse_exclude_constraint(
10310        &mut self,
10311        name: Option<Ident>,
10312    ) -> Result<ExcludeConstraint, ParserError> {
10313        let index_method = if self.parse_keyword(Keyword::USING) {
10314            Some(self.parse_identifier()?)
10315        } else {
10316            None
10317        };
10318
10319        self.expect_token(&Token::LParen)?;
10320        let elements = self.parse_comma_separated(|p| p.parse_exclude_constraint_element())?;
10321        self.expect_token(&Token::RParen)?;
10322
10323        let include = if self.parse_keyword(Keyword::INCLUDE) {
10324            self.expect_token(&Token::LParen)?;
10325            let cols = self.parse_comma_separated(|p| p.parse_identifier())?;
10326            self.expect_token(&Token::RParen)?;
10327            cols
10328        } else {
10329            vec![]
10330        };
10331
10332        let where_clause = if self.parse_keyword(Keyword::WHERE) {
10333            self.expect_token(&Token::LParen)?;
10334            let predicate = self.parse_expr()?;
10335            self.expect_token(&Token::RParen)?;
10336            Some(Box::new(predicate))
10337        } else {
10338            None
10339        };
10340
10341        let characteristics = self.parse_constraint_characteristics()?;
10342
10343        Ok(ExcludeConstraint {
10344            name,
10345            index_method,
10346            elements,
10347            include,
10348            where_clause,
10349            characteristics,
10350        })
10351    }
10352
10353    fn parse_exclude_constraint_element(
10354        &mut self,
10355    ) -> Result<ExcludeConstraintElement, ParserError> {
10356        let column = self.parse_create_index_expr()?;
10357        self.expect_keyword_is(Keyword::WITH)?;
10358        let operator = self.parse_exclude_constraint_operator()?;
10359        Ok(ExcludeConstraintElement { column, operator })
10360    }
10361
10362    /// Parse the operator that follows `WITH` in an `EXCLUDE` element.
10363    fn parse_exclude_constraint_operator(
10364        &mut self,
10365    ) -> Result<ExcludeConstraintOperator, ParserError> {
10366        if self.parse_keyword(Keyword::OPERATOR) {
10367            return Ok(ExcludeConstraintOperator::PGOperator(
10368                self.parse_pg_operator_ident_parts()?,
10369            ));
10370        }
10371
10372        let operator_token = self.next_token();
10373        Ok(ExcludeConstraintOperator::Token(
10374            operator_token.token.to_string(),
10375        ))
10376    }
10377
10378    /// Parse the body of a Postgres `OPERATOR(schema.op)` form: the
10379    /// parenthesized `.`-separated path of name parts after the `OPERATOR`
10380    /// keyword. Shared between binary expression parsing and exclusion
10381    /// constraint parsing.
10382    fn parse_pg_operator_ident_parts(&mut self) -> Result<Vec<String>, ParserError> {
10383        self.expect_token(&Token::LParen)?;
10384        if self.peek_token_ref().token == Token::RParen {
10385            let token = self.next_token();
10386            return self.expected("operator name", token);
10387        }
10388        let mut idents = vec![];
10389        loop {
10390            self.advance_token();
10391            idents.push(self.get_current_token().to_string());
10392            if !self.consume_token(&Token::Period) {
10393                break;
10394            }
10395        }
10396        self.expect_token(&Token::RParen)?;
10397        Ok(idents)
10398    }
10399
10400    fn parse_optional_nulls_distinct(&mut self) -> Result<NullsDistinctOption, ParserError> {
10401        Ok(if self.parse_keyword(Keyword::NULLS) {
10402            let not = self.parse_keyword(Keyword::NOT);
10403            self.expect_keyword_is(Keyword::DISTINCT)?;
10404            if not {
10405                NullsDistinctOption::NotDistinct
10406            } else {
10407                NullsDistinctOption::Distinct
10408            }
10409        } else {
10410            NullsDistinctOption::None
10411        })
10412    }
10413
10414    /// Optionally parse a parenthesized list of `SqlOption`s introduced by `keyword`.
10415    pub fn maybe_parse_options(
10416        &mut self,
10417        keyword: Keyword,
10418    ) -> Result<Option<Vec<SqlOption>>, ParserError> {
10419        if let Token::Word(word) = &self.peek_token_ref().token {
10420            if word.keyword == keyword {
10421                return Ok(Some(self.parse_options(keyword)?));
10422            }
10423        };
10424        Ok(None)
10425    }
10426
10427    /// Parse a parenthesized list of `SqlOption`s following `keyword`, or return an empty vec.
10428    pub fn parse_options(&mut self, keyword: Keyword) -> Result<Vec<SqlOption>, ParserError> {
10429        if self.parse_keyword(keyword) {
10430            self.expect_token(&Token::LParen)?;
10431            let options = self.parse_comma_separated0(Parser::parse_sql_option, Token::RParen)?;
10432            self.expect_token(&Token::RParen)?;
10433            Ok(options)
10434        } else {
10435            Ok(vec![])
10436        }
10437    }
10438
10439    /// Parse options introduced by one of `keywords` followed by a parenthesized list.
10440    pub fn parse_options_with_keywords(
10441        &mut self,
10442        keywords: &[Keyword],
10443    ) -> Result<Vec<SqlOption>, ParserError> {
10444        if self.parse_keywords(keywords) {
10445            self.expect_token(&Token::LParen)?;
10446            let options = self.parse_comma_separated(Parser::parse_sql_option)?;
10447            self.expect_token(&Token::RParen)?;
10448            Ok(options)
10449        } else {
10450            Ok(vec![])
10451        }
10452    }
10453
10454    /// Parse an index type token (e.g. `BTREE`, `HASH`, or a custom identifier).
10455    pub fn parse_index_type(&mut self) -> Result<IndexType, ParserError> {
10456        Ok(if self.parse_keyword(Keyword::BTREE) {
10457            IndexType::BTree
10458        } else if self.parse_keyword(Keyword::HASH) {
10459            IndexType::Hash
10460        } else if self.parse_keyword(Keyword::GIN) {
10461            IndexType::GIN
10462        } else if self.parse_keyword(Keyword::GIST) {
10463            IndexType::GiST
10464        } else if self.parse_keyword(Keyword::SPGIST) {
10465            IndexType::SPGiST
10466        } else if self.parse_keyword(Keyword::BRIN) {
10467            IndexType::BRIN
10468        } else if self.parse_keyword(Keyword::BLOOM) {
10469            IndexType::Bloom
10470        } else {
10471            IndexType::Custom(self.parse_identifier()?)
10472        })
10473    }
10474
10475    /// Optionally parse the `USING` keyword, followed by an [IndexType]
10476    /// Example:
10477    /// ```sql
10478    //// USING BTREE (name, age DESC)
10479    /// ```
10480    /// Optionally parse `USING <index_type>` and return the parsed `IndexType` if present.
10481    pub fn parse_optional_using_then_index_type(
10482        &mut self,
10483    ) -> Result<Option<IndexType>, ParserError> {
10484        if self.parse_keyword(Keyword::USING) {
10485            Ok(Some(self.parse_index_type()?))
10486        } else {
10487            Ok(None)
10488        }
10489    }
10490
10491    /// Parse `[ident]`, mostly `ident` is name, like:
10492    /// `window_name`, `index_name`, ...
10493    /// Parse an optional identifier, returning `Some(Ident)` if present.
10494    pub fn parse_optional_ident(&mut self) -> Result<Option<Ident>, ParserError> {
10495        self.maybe_parse(|parser| parser.parse_identifier())
10496    }
10497
10498    #[must_use]
10499    /// Parse optional `KEY` or `INDEX` display tokens used in index/constraint declarations.
10500    pub fn parse_index_type_display(&mut self) -> KeyOrIndexDisplay {
10501        if self.parse_keyword(Keyword::KEY) {
10502            KeyOrIndexDisplay::Key
10503        } else if self.parse_keyword(Keyword::INDEX) {
10504            KeyOrIndexDisplay::Index
10505        } else {
10506            KeyOrIndexDisplay::None
10507        }
10508    }
10509
10510    /// Parse an optional index option such as `USING <type>` or `COMMENT <string>`.
10511    pub fn parse_optional_index_option(&mut self) -> Result<Option<IndexOption>, ParserError> {
10512        if let Some(index_type) = self.parse_optional_using_then_index_type()? {
10513            Ok(Some(IndexOption::Using(index_type)))
10514        } else if self.parse_keyword(Keyword::COMMENT) {
10515            let s = self.parse_literal_string()?;
10516            Ok(Some(IndexOption::Comment(s)))
10517        } else if self.parse_keywords(&[Keyword::WITH, Keyword::PARSER]) {
10518            // MySQL: `WITH PARSER parser_name` (used by FULLTEXT indexes, e.g. ngram).
10519            let name = self.parse_identifier()?;
10520            Ok(Some(IndexOption::WithParser(name)))
10521        } else if self.parse_keyword(Keyword::VISIBLE) {
10522            Ok(Some(IndexOption::Visible))
10523        } else if self.parse_keyword(Keyword::INVISIBLE) {
10524            Ok(Some(IndexOption::Invisible))
10525        } else {
10526            Ok(None)
10527        }
10528    }
10529
10530    /// Parse zero or more index options and return them as a vector.
10531    pub fn parse_index_options(&mut self) -> Result<Vec<IndexOption>, ParserError> {
10532        let mut options = Vec::new();
10533
10534        loop {
10535            match self.parse_optional_index_option()? {
10536                Some(index_option) => options.push(index_option),
10537                None => return Ok(options),
10538            }
10539        }
10540    }
10541
10542    /// Parse a single `SqlOption` used by various dialect-specific DDL statements.
10543    pub fn parse_sql_option(&mut self) -> Result<SqlOption, ParserError> {
10544        let is_mssql = dialect_of!(self is MsSqlDialect|GenericDialect);
10545
10546        match &self.peek_token_ref().token {
10547            Token::Word(w) if w.keyword == Keyword::HEAP && is_mssql => {
10548                Ok(SqlOption::Ident(self.parse_identifier()?))
10549            }
10550            Token::Word(w) if w.keyword == Keyword::PARTITION && is_mssql => {
10551                self.parse_option_partition()
10552            }
10553            Token::Word(w) if w.keyword == Keyword::CLUSTERED && is_mssql => {
10554                self.parse_option_clustered()
10555            }
10556            _ => {
10557                let name = self.parse_identifier()?;
10558                self.expect_token(&Token::Eq)?;
10559                let value = self.parse_expr()?;
10560
10561                Ok(SqlOption::KeyValue { key: name, value })
10562            }
10563        }
10564    }
10565
10566    /// Parse a `CLUSTERED` table option (MSSQL-specific syntaxes supported).
10567    pub fn parse_option_clustered(&mut self) -> Result<SqlOption, ParserError> {
10568        if self.parse_keywords(&[
10569            Keyword::CLUSTERED,
10570            Keyword::COLUMNSTORE,
10571            Keyword::INDEX,
10572            Keyword::ORDER,
10573        ]) {
10574            Ok(SqlOption::Clustered(
10575                TableOptionsClustered::ColumnstoreIndexOrder(
10576                    self.parse_parenthesized_column_list(IsOptional::Mandatory, false)?,
10577                ),
10578            ))
10579        } else if self.parse_keywords(&[Keyword::CLUSTERED, Keyword::COLUMNSTORE, Keyword::INDEX]) {
10580            Ok(SqlOption::Clustered(
10581                TableOptionsClustered::ColumnstoreIndex,
10582            ))
10583        } else if self.parse_keywords(&[Keyword::CLUSTERED, Keyword::INDEX]) {
10584            self.expect_token(&Token::LParen)?;
10585
10586            let columns = self.parse_comma_separated(|p| {
10587                let name = p.parse_identifier()?;
10588                let asc = p.parse_asc_desc();
10589
10590                Ok(ClusteredIndex { name, asc })
10591            })?;
10592
10593            self.expect_token(&Token::RParen)?;
10594
10595            Ok(SqlOption::Clustered(TableOptionsClustered::Index(columns)))
10596        } else {
10597            Err(ParserError::ParserError(
10598                "invalid CLUSTERED sequence".to_string(),
10599            ))
10600        }
10601    }
10602
10603    /// Parse a `PARTITION(...) FOR VALUES(...)` table option.
10604    pub fn parse_option_partition(&mut self) -> Result<SqlOption, ParserError> {
10605        self.expect_keyword_is(Keyword::PARTITION)?;
10606        self.expect_token(&Token::LParen)?;
10607        let column_name = self.parse_identifier()?;
10608
10609        self.expect_keyword_is(Keyword::RANGE)?;
10610        let range_direction = if self.parse_keyword(Keyword::LEFT) {
10611            Some(PartitionRangeDirection::Left)
10612        } else if self.parse_keyword(Keyword::RIGHT) {
10613            Some(PartitionRangeDirection::Right)
10614        } else {
10615            None
10616        };
10617
10618        self.expect_keywords(&[Keyword::FOR, Keyword::VALUES])?;
10619        self.expect_token(&Token::LParen)?;
10620
10621        let for_values = self.parse_comma_separated(Parser::parse_expr)?;
10622
10623        self.expect_token(&Token::RParen)?;
10624        self.expect_token(&Token::RParen)?;
10625
10626        Ok(SqlOption::Partition {
10627            column_name,
10628            range_direction,
10629            for_values,
10630        })
10631    }
10632
10633    /// Parse a parenthesized list of partition expressions and return a `Partition` value.
10634    pub fn parse_partition(&mut self) -> Result<Partition, ParserError> {
10635        self.expect_token(&Token::LParen)?;
10636        let partitions = self.parse_comma_separated(Parser::parse_expr)?;
10637        self.expect_token(&Token::RParen)?;
10638        Ok(Partition::Partitions(partitions))
10639    }
10640
10641    /// Parse a parenthesized `SELECT` projection used for projection-based operations.
10642    pub fn parse_projection_select(&mut self) -> Result<ProjectionSelect, ParserError> {
10643        self.expect_token(&Token::LParen)?;
10644        self.expect_keyword_is(Keyword::SELECT)?;
10645        let projection = self.parse_projection()?;
10646        let group_by = self.parse_optional_group_by()?;
10647        let order_by = self.parse_optional_order_by()?;
10648        self.expect_token(&Token::RParen)?;
10649        Ok(ProjectionSelect {
10650            projection,
10651            group_by,
10652            order_by,
10653        })
10654    }
10655    /// Parse `ALTER TABLE ... ADD PROJECTION ...` operation.
10656    pub fn parse_alter_table_add_projection(&mut self) -> Result<AlterTableOperation, ParserError> {
10657        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
10658        let name = self.parse_identifier()?;
10659        let query = self.parse_projection_select()?;
10660        Ok(AlterTableOperation::AddProjection {
10661            if_not_exists,
10662            name,
10663            select: query,
10664        })
10665    }
10666
10667    /// Parse Redshift `ALTER SORTKEY (column_list)`.
10668    ///
10669    /// See <https://docs.aws.amazon.com/redshift/latest/dg/r_ALTER_TABLE.html>
10670    fn parse_alter_sort_key(&mut self) -> Result<AlterTableOperation, ParserError> {
10671        self.expect_keyword_is(Keyword::ALTER)?;
10672        self.expect_keyword_is(Keyword::SORTKEY)?;
10673        self.expect_token(&Token::LParen)?;
10674        let columns = self.parse_comma_separated(|p| p.parse_expr())?;
10675        self.expect_token(&Token::RParen)?;
10676        Ok(AlterTableOperation::AlterSortKey { columns })
10677    }
10678
10679    /// Parse a single `ALTER TABLE` operation and return an `AlterTableOperation`.
10680    pub fn parse_alter_table_operation(&mut self) -> Result<AlterTableOperation, ParserError> {
10681        let operation = if self.parse_keyword(Keyword::ADD) {
10682            if let Some(constraint) = self.parse_optional_table_constraint()? {
10683                let not_valid = self.parse_keywords(&[Keyword::NOT, Keyword::VALID]);
10684                AlterTableOperation::AddConstraint {
10685                    constraint,
10686                    not_valid,
10687                }
10688            } else if dialect_of!(self is ClickHouseDialect|GenericDialect)
10689                && self.parse_keyword(Keyword::PROJECTION)
10690            {
10691                return self.parse_alter_table_add_projection();
10692            } else {
10693                let if_not_exists =
10694                    self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
10695                let mut new_partitions = vec![];
10696                loop {
10697                    if self.parse_keyword(Keyword::PARTITION) {
10698                        new_partitions.push(self.parse_partition()?);
10699                    } else {
10700                        break;
10701                    }
10702                }
10703                if !new_partitions.is_empty() {
10704                    AlterTableOperation::AddPartitions {
10705                        if_not_exists,
10706                        new_partitions,
10707                    }
10708                } else {
10709                    let column_keyword = self.parse_keyword(Keyword::COLUMN);
10710
10711                    let if_not_exists = if dialect_of!(self is PostgreSqlDialect | BigQueryDialect | DuckDbDialect | GenericDialect)
10712                    {
10713                        self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS])
10714                            || if_not_exists
10715                    } else {
10716                        false
10717                    };
10718
10719                    let column_def = self.parse_column_def()?;
10720
10721                    let column_position = self.parse_column_position()?;
10722
10723                    AlterTableOperation::AddColumn {
10724                        column_keyword,
10725                        if_not_exists,
10726                        column_def,
10727                        column_position,
10728                    }
10729                }
10730            }
10731        } else if self.parse_keyword(Keyword::RENAME) {
10732            if dialect_of!(self is PostgreSqlDialect) && self.parse_keyword(Keyword::CONSTRAINT) {
10733                let old_name = self.parse_identifier()?;
10734                self.expect_keyword_is(Keyword::TO)?;
10735                let new_name = self.parse_identifier()?;
10736                AlterTableOperation::RenameConstraint { old_name, new_name }
10737            } else if self.parse_keyword(Keyword::TO) {
10738                let table_name = self.parse_object_name(false)?;
10739                AlterTableOperation::RenameTable {
10740                    table_name: RenameTableNameKind::To(table_name),
10741                }
10742            } else if self.parse_keyword(Keyword::AS) {
10743                let table_name = self.parse_object_name(false)?;
10744                AlterTableOperation::RenameTable {
10745                    table_name: RenameTableNameKind::As(table_name),
10746                }
10747            } else {
10748                let _ = self.parse_keyword(Keyword::COLUMN); // [ COLUMN ]
10749                let old_column_name = self.parse_identifier()?;
10750                self.expect_keyword_is(Keyword::TO)?;
10751                let new_column_name = self.parse_identifier()?;
10752                AlterTableOperation::RenameColumn {
10753                    old_column_name,
10754                    new_column_name,
10755                }
10756            }
10757        } else if self.parse_keyword(Keyword::DISABLE) {
10758            if self.parse_keywords(&[Keyword::ROW, Keyword::LEVEL, Keyword::SECURITY]) {
10759                AlterTableOperation::DisableRowLevelSecurity {}
10760            } else if self.parse_keyword(Keyword::RULE) {
10761                let name = self.parse_identifier()?;
10762                AlterTableOperation::DisableRule { name }
10763            } else if self.parse_keyword(Keyword::TRIGGER) {
10764                let name = self.parse_identifier()?;
10765                AlterTableOperation::DisableTrigger { name }
10766            } else {
10767                return self.expected_ref(
10768                    "ROW LEVEL SECURITY, RULE, or TRIGGER after DISABLE",
10769                    self.peek_token_ref(),
10770                );
10771            }
10772        } else if self.parse_keyword(Keyword::ENABLE) {
10773            if self.parse_keywords(&[Keyword::ALWAYS, Keyword::RULE]) {
10774                let name = self.parse_identifier()?;
10775                AlterTableOperation::EnableAlwaysRule { name }
10776            } else if self.parse_keywords(&[Keyword::ALWAYS, Keyword::TRIGGER]) {
10777                let name = self.parse_identifier()?;
10778                AlterTableOperation::EnableAlwaysTrigger { name }
10779            } else if self.parse_keywords(&[Keyword::ROW, Keyword::LEVEL, Keyword::SECURITY]) {
10780                AlterTableOperation::EnableRowLevelSecurity {}
10781            } else if self.parse_keywords(&[Keyword::REPLICA, Keyword::RULE]) {
10782                let name = self.parse_identifier()?;
10783                AlterTableOperation::EnableReplicaRule { name }
10784            } else if self.parse_keywords(&[Keyword::REPLICA, Keyword::TRIGGER]) {
10785                let name = self.parse_identifier()?;
10786                AlterTableOperation::EnableReplicaTrigger { name }
10787            } else if self.parse_keyword(Keyword::RULE) {
10788                let name = self.parse_identifier()?;
10789                AlterTableOperation::EnableRule { name }
10790            } else if self.parse_keyword(Keyword::TRIGGER) {
10791                let name = self.parse_identifier()?;
10792                AlterTableOperation::EnableTrigger { name }
10793            } else {
10794                return self.expected_ref(
10795                    "ALWAYS, REPLICA, ROW LEVEL SECURITY, RULE, or TRIGGER after ENABLE",
10796                    self.peek_token_ref(),
10797                );
10798            }
10799        } else if self.parse_keywords(&[
10800            Keyword::FORCE,
10801            Keyword::ROW,
10802            Keyword::LEVEL,
10803            Keyword::SECURITY,
10804        ]) {
10805            AlterTableOperation::ForceRowLevelSecurity
10806        } else if self.parse_keywords(&[
10807            Keyword::NO,
10808            Keyword::FORCE,
10809            Keyword::ROW,
10810            Keyword::LEVEL,
10811            Keyword::SECURITY,
10812        ]) {
10813            AlterTableOperation::NoForceRowLevelSecurity
10814        } else if self.parse_keywords(&[Keyword::CLEAR, Keyword::PROJECTION])
10815            && dialect_of!(self is ClickHouseDialect|GenericDialect)
10816        {
10817            let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
10818            let name = self.parse_identifier()?;
10819            let partition = if self.parse_keywords(&[Keyword::IN, Keyword::PARTITION]) {
10820                Some(self.parse_identifier()?)
10821            } else {
10822                None
10823            };
10824            AlterTableOperation::ClearProjection {
10825                if_exists,
10826                name,
10827                partition,
10828            }
10829        } else if self.parse_keywords(&[Keyword::MATERIALIZE, Keyword::PROJECTION])
10830            && dialect_of!(self is ClickHouseDialect|GenericDialect)
10831        {
10832            let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
10833            let name = self.parse_identifier()?;
10834            let partition = if self.parse_keywords(&[Keyword::IN, Keyword::PARTITION]) {
10835                Some(self.parse_identifier()?)
10836            } else {
10837                None
10838            };
10839            AlterTableOperation::MaterializeProjection {
10840                if_exists,
10841                name,
10842                partition,
10843            }
10844        } else if self.parse_keyword(Keyword::DROP) {
10845            if self.parse_keywords(&[Keyword::IF, Keyword::EXISTS, Keyword::PARTITION]) {
10846                self.expect_token(&Token::LParen)?;
10847                let partitions = self.parse_comma_separated(Parser::parse_expr)?;
10848                self.expect_token(&Token::RParen)?;
10849                AlterTableOperation::DropPartitions {
10850                    partitions,
10851                    if_exists: true,
10852                }
10853            } else if self.parse_keyword(Keyword::PARTITION) {
10854                self.expect_token(&Token::LParen)?;
10855                let partitions = self.parse_comma_separated(Parser::parse_expr)?;
10856                self.expect_token(&Token::RParen)?;
10857                AlterTableOperation::DropPartitions {
10858                    partitions,
10859                    if_exists: false,
10860                }
10861            } else if self.parse_keyword(Keyword::CONSTRAINT) {
10862                let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
10863                let name = self.parse_identifier()?;
10864                let drop_behavior = self.parse_optional_drop_behavior();
10865                AlterTableOperation::DropConstraint {
10866                    if_exists,
10867                    name,
10868                    drop_behavior,
10869                }
10870            } else if self.parse_keywords(&[Keyword::PRIMARY, Keyword::KEY]) {
10871                let drop_behavior = self.parse_optional_drop_behavior();
10872                AlterTableOperation::DropPrimaryKey { drop_behavior }
10873            } else if self.parse_keywords(&[Keyword::FOREIGN, Keyword::KEY]) {
10874                let name = self.parse_identifier()?;
10875                let drop_behavior = self.parse_optional_drop_behavior();
10876                AlterTableOperation::DropForeignKey {
10877                    name,
10878                    drop_behavior,
10879                }
10880            } else if self.parse_keyword(Keyword::INDEX) {
10881                let name = self.parse_identifier()?;
10882                AlterTableOperation::DropIndex { name }
10883            } else if self.parse_keyword(Keyword::PROJECTION)
10884                && dialect_of!(self is ClickHouseDialect|GenericDialect)
10885            {
10886                let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
10887                let name = self.parse_identifier()?;
10888                AlterTableOperation::DropProjection { if_exists, name }
10889            } else if self.parse_keywords(&[Keyword::CLUSTERING, Keyword::KEY]) {
10890                AlterTableOperation::DropClusteringKey
10891            } else {
10892                let has_column_keyword = self.parse_keyword(Keyword::COLUMN); // [ COLUMN ]
10893                let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
10894                let column_names = if self.dialect.supports_comma_separated_drop_column_list() {
10895                    self.parse_comma_separated(Parser::parse_identifier)?
10896                } else {
10897                    vec![self.parse_identifier()?]
10898                };
10899                let drop_behavior = self.parse_optional_drop_behavior();
10900                AlterTableOperation::DropColumn {
10901                    has_column_keyword,
10902                    column_names,
10903                    if_exists,
10904                    drop_behavior,
10905                }
10906            }
10907        } else if self.parse_keyword(Keyword::PARTITION) {
10908            self.expect_token(&Token::LParen)?;
10909            let before = self.parse_comma_separated(Parser::parse_expr)?;
10910            self.expect_token(&Token::RParen)?;
10911            self.expect_keyword_is(Keyword::RENAME)?;
10912            self.expect_keywords(&[Keyword::TO, Keyword::PARTITION])?;
10913            self.expect_token(&Token::LParen)?;
10914            let renames = self.parse_comma_separated(Parser::parse_expr)?;
10915            self.expect_token(&Token::RParen)?;
10916            AlterTableOperation::RenamePartitions {
10917                old_partitions: before,
10918                new_partitions: renames,
10919            }
10920        } else if self.parse_keyword(Keyword::CHANGE) {
10921            let _ = self.parse_keyword(Keyword::COLUMN); // [ COLUMN ]
10922            let old_name = self.parse_identifier()?;
10923            let new_name = self.parse_identifier()?;
10924            let data_type = self.parse_data_type()?;
10925            let mut options = vec![];
10926            while let Some(option) = self.parse_optional_column_option()? {
10927                options.push(option);
10928            }
10929
10930            let column_position = self.parse_column_position()?;
10931
10932            AlterTableOperation::ChangeColumn {
10933                old_name,
10934                new_name,
10935                data_type,
10936                options,
10937                column_position,
10938            }
10939        } else if self.parse_keyword(Keyword::MODIFY) {
10940            let _ = self.parse_keyword(Keyword::COLUMN); // [ COLUMN ]
10941            let col_name = self.parse_identifier()?;
10942            let data_type = self.parse_data_type()?;
10943            let mut options = vec![];
10944            while let Some(option) = self.parse_optional_column_option()? {
10945                options.push(option);
10946            }
10947
10948            let column_position = self.parse_column_position()?;
10949
10950            AlterTableOperation::ModifyColumn {
10951                col_name,
10952                data_type,
10953                options,
10954                column_position,
10955            }
10956        } else if self.parse_keyword(Keyword::ALTER) {
10957            if self.peek_keyword(Keyword::SORTKEY) {
10958                self.prev_token();
10959                return self.parse_alter_sort_key();
10960            }
10961
10962            let _ = self.parse_keyword(Keyword::COLUMN); // [ COLUMN ]
10963            let column_name = self.parse_identifier()?;
10964            let is_postgresql = dialect_of!(self is PostgreSqlDialect);
10965
10966            let op: AlterColumnOperation = if self.parse_keywords(&[
10967                Keyword::SET,
10968                Keyword::NOT,
10969                Keyword::NULL,
10970            ]) {
10971                AlterColumnOperation::SetNotNull {}
10972            } else if self.parse_keywords(&[Keyword::DROP, Keyword::NOT, Keyword::NULL]) {
10973                AlterColumnOperation::DropNotNull {}
10974            } else if self.parse_keywords(&[Keyword::SET, Keyword::DEFAULT]) {
10975                AlterColumnOperation::SetDefault {
10976                    value: self.parse_expr()?,
10977                }
10978            } else if self.parse_keywords(&[Keyword::DROP, Keyword::DEFAULT]) {
10979                AlterColumnOperation::DropDefault {}
10980            } else if self.parse_keywords(&[Keyword::SET, Keyword::DATA, Keyword::TYPE]) {
10981                self.parse_set_data_type(true)?
10982            } else if self.parse_keyword(Keyword::TYPE) {
10983                self.parse_set_data_type(false)?
10984            } else if self.parse_keywords(&[Keyword::ADD, Keyword::GENERATED]) {
10985                let generated_as = if self.parse_keyword(Keyword::ALWAYS) {
10986                    Some(GeneratedAs::Always)
10987                } else if self.parse_keywords(&[Keyword::BY, Keyword::DEFAULT]) {
10988                    Some(GeneratedAs::ByDefault)
10989                } else {
10990                    None
10991                };
10992
10993                self.expect_keywords(&[Keyword::AS, Keyword::IDENTITY])?;
10994
10995                let mut sequence_options: Option<Vec<SequenceOptions>> = None;
10996
10997                if self.peek_token_ref().token == Token::LParen {
10998                    self.expect_token(&Token::LParen)?;
10999                    sequence_options = Some(self.parse_create_sequence_options()?);
11000                    self.expect_token(&Token::RParen)?;
11001                }
11002
11003                AlterColumnOperation::AddGenerated {
11004                    generated_as,
11005                    sequence_options,
11006                }
11007            } else {
11008                let message = if is_postgresql {
11009                    "SET/DROP NOT NULL, SET DEFAULT, SET DATA TYPE, or ADD GENERATED after ALTER COLUMN"
11010                } else {
11011                    "SET/DROP NOT NULL, SET DEFAULT, or SET DATA TYPE after ALTER COLUMN"
11012                };
11013
11014                return self.expected_ref(message, self.peek_token_ref());
11015            };
11016            AlterTableOperation::AlterColumn { column_name, op }
11017        } else if self.parse_keyword(Keyword::SWAP) {
11018            self.expect_keyword_is(Keyword::WITH)?;
11019            let table_name = self.parse_object_name(false)?;
11020            AlterTableOperation::SwapWith { table_name }
11021        } else if dialect_of!(self is PostgreSqlDialect | GenericDialect)
11022            && self.parse_keywords(&[Keyword::OWNER, Keyword::TO])
11023        {
11024            let new_owner = self.parse_owner()?;
11025            AlterTableOperation::OwnerTo { new_owner }
11026        } else if dialect_of!(self is ClickHouseDialect|GenericDialect)
11027            && self.parse_keyword(Keyword::ATTACH)
11028        {
11029            AlterTableOperation::AttachPartition {
11030                partition: self.parse_part_or_partition()?,
11031            }
11032        } else if dialect_of!(self is ClickHouseDialect|GenericDialect)
11033            && self.parse_keyword(Keyword::DETACH)
11034        {
11035            AlterTableOperation::DetachPartition {
11036                partition: self.parse_part_or_partition()?,
11037            }
11038        } else if dialect_of!(self is ClickHouseDialect|GenericDialect)
11039            && self.parse_keyword(Keyword::FREEZE)
11040        {
11041            let partition = self.parse_part_or_partition()?;
11042            let with_name = if self.parse_keyword(Keyword::WITH) {
11043                self.expect_keyword_is(Keyword::NAME)?;
11044                Some(self.parse_identifier()?)
11045            } else {
11046                None
11047            };
11048            AlterTableOperation::FreezePartition {
11049                partition,
11050                with_name,
11051            }
11052        } else if dialect_of!(self is ClickHouseDialect|GenericDialect)
11053            && self.parse_keyword(Keyword::UNFREEZE)
11054        {
11055            let partition = self.parse_part_or_partition()?;
11056            let with_name = if self.parse_keyword(Keyword::WITH) {
11057                self.expect_keyword_is(Keyword::NAME)?;
11058                Some(self.parse_identifier()?)
11059            } else {
11060                None
11061            };
11062            AlterTableOperation::UnfreezePartition {
11063                partition,
11064                with_name,
11065            }
11066        } else if self.parse_keywords(&[Keyword::CLUSTER, Keyword::BY]) {
11067            self.expect_token(&Token::LParen)?;
11068            let exprs = self.parse_comma_separated(|parser| parser.parse_expr())?;
11069            self.expect_token(&Token::RParen)?;
11070            AlterTableOperation::ClusterBy { exprs }
11071        } else if self.parse_keywords(&[Keyword::SUSPEND, Keyword::RECLUSTER]) {
11072            AlterTableOperation::SuspendRecluster
11073        } else if self.parse_keywords(&[Keyword::RESUME, Keyword::RECLUSTER]) {
11074            AlterTableOperation::ResumeRecluster
11075        } else if self.parse_keyword(Keyword::LOCK) {
11076            let equals = self.consume_token(&Token::Eq);
11077            let lock = match self.parse_one_of_keywords(&[
11078                Keyword::DEFAULT,
11079                Keyword::EXCLUSIVE,
11080                Keyword::NONE,
11081                Keyword::SHARED,
11082            ]) {
11083                Some(Keyword::DEFAULT) => AlterTableLock::Default,
11084                Some(Keyword::EXCLUSIVE) => AlterTableLock::Exclusive,
11085                Some(Keyword::NONE) => AlterTableLock::None,
11086                Some(Keyword::SHARED) => AlterTableLock::Shared,
11087                _ => self.expected_ref(
11088                    "DEFAULT, EXCLUSIVE, NONE or SHARED after LOCK [=]",
11089                    self.peek_token_ref(),
11090                )?,
11091            };
11092            AlterTableOperation::Lock { equals, lock }
11093        } else if self.parse_keyword(Keyword::ALGORITHM) {
11094            let equals = self.consume_token(&Token::Eq);
11095            let algorithm = match self.parse_one_of_keywords(&[
11096                Keyword::DEFAULT,
11097                Keyword::INSTANT,
11098                Keyword::INPLACE,
11099                Keyword::COPY,
11100            ]) {
11101                Some(Keyword::DEFAULT) => AlterTableAlgorithm::Default,
11102                Some(Keyword::INSTANT) => AlterTableAlgorithm::Instant,
11103                Some(Keyword::INPLACE) => AlterTableAlgorithm::Inplace,
11104                Some(Keyword::COPY) => AlterTableAlgorithm::Copy,
11105                _ => self.expected_ref(
11106                    "DEFAULT, INSTANT, INPLACE, or COPY after ALGORITHM [=]",
11107                    self.peek_token_ref(),
11108                )?,
11109            };
11110            AlterTableOperation::Algorithm { equals, algorithm }
11111        } else if self.parse_keyword(Keyword::AUTO_INCREMENT) {
11112            let equals = self.consume_token(&Token::Eq);
11113            let value = self.parse_number_value()?;
11114            AlterTableOperation::AutoIncrement { equals, value }
11115        } else if self.parse_keywords(&[Keyword::REPLICA, Keyword::IDENTITY]) {
11116            let identity = if self.parse_keyword(Keyword::NOTHING) {
11117                ReplicaIdentity::Nothing
11118            } else if self.parse_keyword(Keyword::FULL) {
11119                ReplicaIdentity::Full
11120            } else if self.parse_keyword(Keyword::DEFAULT) {
11121                ReplicaIdentity::Default
11122            } else if self.parse_keywords(&[Keyword::USING, Keyword::INDEX]) {
11123                ReplicaIdentity::Index(self.parse_identifier()?)
11124            } else {
11125                return self.expected_ref(
11126                    "NOTHING, FULL, DEFAULT, or USING INDEX index_name after REPLICA IDENTITY",
11127                    self.peek_token_ref(),
11128                );
11129            };
11130
11131            AlterTableOperation::ReplicaIdentity { identity }
11132        } else if self.parse_keywords(&[Keyword::VALIDATE, Keyword::CONSTRAINT]) {
11133            let name = self.parse_identifier()?;
11134            AlterTableOperation::ValidateConstraint { name }
11135        } else if self.parse_keywords(&[Keyword::SET, Keyword::LOGGED]) {
11136            AlterTableOperation::SetLogged
11137        } else if self.parse_keywords(&[Keyword::SET, Keyword::UNLOGGED]) {
11138            AlterTableOperation::SetUnlogged
11139        } else {
11140            let mut options =
11141                self.parse_options_with_keywords(&[Keyword::SET, Keyword::TBLPROPERTIES])?;
11142            if !options.is_empty() {
11143                AlterTableOperation::SetTblProperties {
11144                    table_properties: options,
11145                }
11146            } else {
11147                options = self.parse_options(Keyword::SET)?;
11148                if !options.is_empty() {
11149                    AlterTableOperation::SetOptionsParens { options }
11150                } else {
11151                    return self.expected_ref(
11152                    "ADD, RENAME, PARTITION, SWAP, DROP, REPLICA IDENTITY, SET, or SET TBLPROPERTIES after ALTER TABLE",
11153                    self.peek_token_ref(),
11154                  );
11155                }
11156            }
11157        };
11158        Ok(operation)
11159    }
11160
11161    fn parse_set_data_type(&mut self, had_set: bool) -> Result<AlterColumnOperation, ParserError> {
11162        let data_type = self.parse_data_type()?;
11163        let using = if self.dialect.supports_alter_column_type_using()
11164            && self.parse_keyword(Keyword::USING)
11165        {
11166            Some(self.parse_expr()?)
11167        } else {
11168            None
11169        };
11170        Ok(AlterColumnOperation::SetDataType {
11171            data_type,
11172            using,
11173            had_set,
11174        })
11175    }
11176
11177    fn parse_part_or_partition(&mut self) -> Result<Partition, ParserError> {
11178        let keyword = self.expect_one_of_keywords(&[Keyword::PART, Keyword::PARTITION])?;
11179        match keyword {
11180            Keyword::PART => Ok(Partition::Part(self.parse_expr()?)),
11181            Keyword::PARTITION => Ok(Partition::Expr(self.parse_expr()?)),
11182            // unreachable because expect_one_of_keywords used above
11183            unexpected_keyword => Err(ParserError::ParserError(
11184                format!("Internal parser error: expected any of {{PART, PARTITION}}, got {unexpected_keyword:?}"),
11185            )),
11186        }
11187    }
11188
11189    /// Parse an `ALTER <object>` statement and dispatch to the appropriate alter handler.
11190    pub fn parse_alter(&mut self) -> Result<Statement, ParserError> {
11191        if self.peek_keywords(&[Keyword::TEXT, Keyword::SEARCH]) {
11192            return self.parse_alter_text_search().map(Into::into);
11193        }
11194
11195        let object_type = self.expect_one_of_keywords(&[
11196            Keyword::VIEW,
11197            Keyword::TYPE,
11198            Keyword::COLLATION,
11199            Keyword::TABLE,
11200            Keyword::INDEX,
11201            Keyword::FUNCTION,
11202            Keyword::AGGREGATE,
11203            Keyword::ROLE,
11204            Keyword::POLICY,
11205            Keyword::CONNECTOR,
11206            Keyword::ICEBERG,
11207            Keyword::SCHEMA,
11208            Keyword::USER,
11209            Keyword::OPERATOR,
11210        ])?;
11211        match object_type {
11212            Keyword::SCHEMA => {
11213                self.prev_token();
11214                self.prev_token();
11215                self.parse_alter_schema()
11216            }
11217            Keyword::VIEW => self.parse_alter_view(),
11218            Keyword::TYPE => self.parse_alter_type(),
11219            Keyword::COLLATION => self.parse_alter_collation().map(Into::into),
11220            Keyword::TABLE => self.parse_alter_table(false),
11221            Keyword::ICEBERG => {
11222                self.expect_keyword(Keyword::TABLE)?;
11223                self.parse_alter_table(true)
11224            }
11225            Keyword::INDEX => {
11226                let index_name = self.parse_object_name(false)?;
11227                let operation = if self.parse_keyword(Keyword::RENAME) {
11228                    if self.parse_keyword(Keyword::TO) {
11229                        let index_name = self.parse_object_name(false)?;
11230                        AlterIndexOperation::RenameIndex { index_name }
11231                    } else {
11232                        return self.expected_ref("TO after RENAME", self.peek_token_ref());
11233                    }
11234                } else {
11235                    return self.expected_ref("RENAME after ALTER INDEX", self.peek_token_ref());
11236                };
11237
11238                Ok(Statement::AlterIndex {
11239                    name: index_name,
11240                    operation,
11241                })
11242            }
11243            Keyword::FUNCTION => self.parse_alter_function(AlterFunctionKind::Function),
11244            Keyword::AGGREGATE => self.parse_alter_function(AlterFunctionKind::Aggregate),
11245            Keyword::OPERATOR => {
11246                if self.parse_keyword(Keyword::FAMILY) {
11247                    self.parse_alter_operator_family().map(Into::into)
11248                } else if self.parse_keyword(Keyword::CLASS) {
11249                    self.parse_alter_operator_class().map(Into::into)
11250                } else {
11251                    self.parse_alter_operator().map(Into::into)
11252                }
11253            }
11254            Keyword::ROLE => self.parse_alter_role(),
11255            Keyword::POLICY => self.parse_alter_policy().map(Into::into),
11256            Keyword::CONNECTOR => self.parse_alter_connector(),
11257            Keyword::USER if self.dialect.supports_alter_user_as_alter_role() => {
11258                self.parse_alter_role()
11259            }
11260            Keyword::USER => self.parse_alter_user().map(Into::into),
11261            // unreachable because expect_one_of_keywords used above
11262            unexpected_keyword => Err(ParserError::ParserError(
11263                format!("Internal parser error: expected any of {{TEXT SEARCH, VIEW, TYPE, COLLATION, TABLE, INDEX, FUNCTION, AGGREGATE, ROLE, POLICY, CONNECTOR, ICEBERG, SCHEMA, USER, OPERATOR}}, got {unexpected_keyword:?}"),
11264            )),
11265        }
11266    }
11267
11268    fn parse_alter_aggregate_signature(
11269        &mut self,
11270    ) -> Result<(FunctionDesc, bool, Option<Vec<OperateFunctionArg>>), ParserError> {
11271        let name = self.parse_object_name(false)?;
11272        self.expect_token(&Token::LParen)?;
11273
11274        if self.consume_token(&Token::Mul) {
11275            self.expect_token(&Token::RParen)?;
11276            return Ok((
11277                FunctionDesc {
11278                    name,
11279                    args: Some(vec![]),
11280                },
11281                true,
11282                None,
11283            ));
11284        }
11285
11286        let args =
11287            if self.peek_keyword(Keyword::ORDER) || self.peek_token_ref().token == Token::RParen {
11288                vec![]
11289            } else {
11290                self.parse_comma_separated(Parser::parse_aggregate_function_arg)?
11291            };
11292
11293        let aggregate_order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
11294            Some(self.parse_comma_separated(Parser::parse_aggregate_function_arg)?)
11295        } else {
11296            None
11297        };
11298
11299        self.expect_token(&Token::RParen)?;
11300        Ok((
11301            FunctionDesc {
11302                name,
11303                args: Some(args),
11304            },
11305            false,
11306            aggregate_order_by,
11307        ))
11308    }
11309
11310    fn parse_alter_function_action(&mut self) -> Result<Option<AlterFunctionAction>, ParserError> {
11311        let action = if self.parse_keywords(&[
11312            Keyword::CALLED,
11313            Keyword::ON,
11314            Keyword::NULL,
11315            Keyword::INPUT,
11316        ]) {
11317            Some(AlterFunctionAction::CalledOnNull(
11318                FunctionCalledOnNull::CalledOnNullInput,
11319            ))
11320        } else if self.parse_keywords(&[
11321            Keyword::RETURNS,
11322            Keyword::NULL,
11323            Keyword::ON,
11324            Keyword::NULL,
11325            Keyword::INPUT,
11326        ]) {
11327            Some(AlterFunctionAction::CalledOnNull(
11328                FunctionCalledOnNull::ReturnsNullOnNullInput,
11329            ))
11330        } else if self.parse_keyword(Keyword::STRICT) {
11331            Some(AlterFunctionAction::CalledOnNull(
11332                FunctionCalledOnNull::Strict,
11333            ))
11334        } else if self.parse_keyword(Keyword::IMMUTABLE) {
11335            Some(AlterFunctionAction::Behavior(FunctionBehavior::Immutable))
11336        } else if self.parse_keyword(Keyword::STABLE) {
11337            Some(AlterFunctionAction::Behavior(FunctionBehavior::Stable))
11338        } else if self.parse_keyword(Keyword::VOLATILE) {
11339            Some(AlterFunctionAction::Behavior(FunctionBehavior::Volatile))
11340        } else if self.parse_keyword(Keyword::NOT) {
11341            self.expect_keyword(Keyword::LEAKPROOF)?;
11342            Some(AlterFunctionAction::Leakproof(false))
11343        } else if self.parse_keyword(Keyword::LEAKPROOF) {
11344            Some(AlterFunctionAction::Leakproof(true))
11345        } else if self.parse_keyword(Keyword::EXTERNAL) {
11346            self.expect_keyword(Keyword::SECURITY)?;
11347            let security = if self.parse_keyword(Keyword::DEFINER) {
11348                FunctionSecurity::Definer
11349            } else if self.parse_keyword(Keyword::INVOKER) {
11350                FunctionSecurity::Invoker
11351            } else {
11352                return self.expected_ref("DEFINER or INVOKER", self.peek_token_ref());
11353            };
11354            Some(AlterFunctionAction::Security {
11355                external: true,
11356                security,
11357            })
11358        } else if self.parse_keyword(Keyword::SECURITY) {
11359            let security = if self.parse_keyword(Keyword::DEFINER) {
11360                FunctionSecurity::Definer
11361            } else if self.parse_keyword(Keyword::INVOKER) {
11362                FunctionSecurity::Invoker
11363            } else {
11364                return self.expected_ref("DEFINER or INVOKER", self.peek_token_ref());
11365            };
11366            Some(AlterFunctionAction::Security {
11367                external: false,
11368                security,
11369            })
11370        } else if self.parse_keyword(Keyword::PARALLEL) {
11371            let parallel = if self.parse_keyword(Keyword::UNSAFE) {
11372                FunctionParallel::Unsafe
11373            } else if self.parse_keyword(Keyword::RESTRICTED) {
11374                FunctionParallel::Restricted
11375            } else if self.parse_keyword(Keyword::SAFE) {
11376                FunctionParallel::Safe
11377            } else {
11378                return self
11379                    .expected_ref("one of UNSAFE | RESTRICTED | SAFE", self.peek_token_ref());
11380            };
11381            Some(AlterFunctionAction::Parallel(parallel))
11382        } else if self.parse_keyword(Keyword::COST) {
11383            Some(AlterFunctionAction::Cost(self.parse_number()?))
11384        } else if self.parse_keyword(Keyword::ROWS) {
11385            Some(AlterFunctionAction::Rows(self.parse_number()?))
11386        } else if self.parse_keyword(Keyword::SUPPORT) {
11387            Some(AlterFunctionAction::Support(self.parse_object_name(false)?))
11388        } else if self.parse_keyword(Keyword::SET) {
11389            let name = self.parse_object_name(false)?;
11390            let value = if self.parse_keywords(&[Keyword::FROM, Keyword::CURRENT]) {
11391                FunctionSetValue::FromCurrent
11392            } else {
11393                if !self.consume_token(&Token::Eq) && !self.parse_keyword(Keyword::TO) {
11394                    return self.expected_ref("= or TO", self.peek_token_ref());
11395                }
11396                if self.parse_keyword(Keyword::DEFAULT) {
11397                    FunctionSetValue::Default
11398                } else {
11399                    FunctionSetValue::Values(self.parse_comma_separated(Parser::parse_expr)?)
11400                }
11401            };
11402            Some(AlterFunctionAction::Set(FunctionDefinitionSetParam {
11403                name,
11404                value,
11405            }))
11406        } else if self.parse_keyword(Keyword::RESET) {
11407            let reset_config = if self.parse_keyword(Keyword::ALL) {
11408                ResetConfig::ALL
11409            } else {
11410                ResetConfig::ConfigName(self.parse_object_name(false)?)
11411            };
11412            Some(AlterFunctionAction::Reset(reset_config))
11413        } else {
11414            None
11415        };
11416
11417        Ok(action)
11418    }
11419
11420    fn parse_alter_function_actions(
11421        &mut self,
11422    ) -> Result<(Vec<AlterFunctionAction>, bool), ParserError> {
11423        let mut actions = vec![];
11424        while let Some(action) = self.parse_alter_function_action()? {
11425            actions.push(action);
11426        }
11427        if actions.is_empty() {
11428            return self.expected_ref("at least one ALTER FUNCTION action", self.peek_token_ref());
11429        }
11430        let restrict = self.parse_keyword(Keyword::RESTRICT);
11431        Ok((actions, restrict))
11432    }
11433
11434    /// Parse an `ALTER FUNCTION` or `ALTER AGGREGATE` statement.
11435    pub fn parse_alter_function(
11436        &mut self,
11437        kind: AlterFunctionKind,
11438    ) -> Result<Statement, ParserError> {
11439        let (function, aggregate_star, aggregate_order_by) = match kind {
11440            AlterFunctionKind::Function => (self.parse_function_desc()?, false, None),
11441            AlterFunctionKind::Aggregate => self.parse_alter_aggregate_signature()?,
11442        };
11443
11444        let operation = if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
11445            let new_name = self.parse_identifier()?;
11446            AlterFunctionOperation::RenameTo { new_name }
11447        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
11448            AlterFunctionOperation::OwnerTo(self.parse_owner()?)
11449        } else if self.parse_keywords(&[Keyword::SET, Keyword::SCHEMA]) {
11450            AlterFunctionOperation::SetSchema {
11451                schema_name: self.parse_object_name(false)?,
11452            }
11453        } else if matches!(kind, AlterFunctionKind::Function) && self.parse_keyword(Keyword::NO) {
11454            if !self.parse_keyword(Keyword::DEPENDS) {
11455                return self.expected_ref("DEPENDS after NO", self.peek_token_ref());
11456            }
11457            self.expect_keywords(&[Keyword::ON, Keyword::EXTENSION])?;
11458            AlterFunctionOperation::DependsOnExtension {
11459                no: true,
11460                extension_name: self.parse_object_name(false)?,
11461            }
11462        } else if matches!(kind, AlterFunctionKind::Function)
11463            && self.parse_keyword(Keyword::DEPENDS)
11464        {
11465            self.expect_keywords(&[Keyword::ON, Keyword::EXTENSION])?;
11466            AlterFunctionOperation::DependsOnExtension {
11467                no: false,
11468                extension_name: self.parse_object_name(false)?,
11469            }
11470        } else if matches!(kind, AlterFunctionKind::Function) {
11471            let (actions, restrict) = self.parse_alter_function_actions()?;
11472            AlterFunctionOperation::Actions { actions, restrict }
11473        } else {
11474            return self.expected_ref(
11475                "RENAME TO, OWNER TO, or SET SCHEMA after ALTER AGGREGATE",
11476                self.peek_token_ref(),
11477            );
11478        };
11479
11480        Ok(Statement::AlterFunction(AlterFunction {
11481            kind,
11482            function,
11483            aggregate_order_by,
11484            aggregate_star,
11485            operation,
11486        }))
11487    }
11488
11489    /// Parse a [Statement::AlterTable]
11490    pub fn parse_alter_table(&mut self, iceberg: bool) -> Result<Statement, ParserError> {
11491        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
11492        let only = self.parse_keyword(Keyword::ONLY); // [ ONLY ]
11493        let table_name = self.parse_object_name(false)?;
11494        let on_cluster = self.parse_optional_on_cluster()?;
11495        let operations = self.parse_comma_separated(Parser::parse_alter_table_operation)?;
11496
11497        let mut location = None;
11498        if self.parse_keyword(Keyword::LOCATION) {
11499            location = Some(HiveSetLocation {
11500                has_set: false,
11501                location: self.parse_identifier()?,
11502            });
11503        } else if self.parse_keywords(&[Keyword::SET, Keyword::LOCATION]) {
11504            location = Some(HiveSetLocation {
11505                has_set: true,
11506                location: self.parse_identifier()?,
11507            });
11508        }
11509
11510        let end_token = if self.peek_token_ref().token == Token::SemiColon {
11511            self.peek_token_ref().clone()
11512        } else {
11513            self.get_current_token().clone()
11514        };
11515
11516        Ok(AlterTable {
11517            name: table_name,
11518            if_exists,
11519            only,
11520            operations,
11521            location,
11522            on_cluster,
11523            table_type: if iceberg {
11524                Some(AlterTableType::Iceberg)
11525            } else {
11526                None
11527            },
11528            end_token: AttachedToken(end_token),
11529        }
11530        .into())
11531    }
11532
11533    /// Parse an `ALTER VIEW` statement.
11534    pub fn parse_alter_view(&mut self) -> Result<Statement, ParserError> {
11535        let name = self.parse_object_name(false)?;
11536        let columns = self.parse_parenthesized_column_list(Optional, false)?;
11537
11538        let with_options = self.parse_options(Keyword::WITH)?;
11539
11540        self.expect_keyword_is(Keyword::AS)?;
11541        let query = self.parse_query()?;
11542
11543        Ok(Statement::AlterView {
11544            name,
11545            columns,
11546            query,
11547            with_options,
11548        })
11549    }
11550
11551    /// Parse a [Statement::AlterType]
11552    pub fn parse_alter_type(&mut self) -> Result<Statement, ParserError> {
11553        let name = self.parse_object_name(false)?;
11554
11555        if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
11556            let new_name = self.parse_identifier()?;
11557            Ok(Statement::AlterType(AlterType {
11558                name,
11559                operation: AlterTypeOperation::Rename(AlterTypeRename { new_name }),
11560            }))
11561        } else if self.parse_keywords(&[Keyword::ADD, Keyword::VALUE]) {
11562            let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
11563            let new_enum_value = self.parse_identifier()?;
11564            let position = if self.parse_keyword(Keyword::BEFORE) {
11565                Some(AlterTypeAddValuePosition::Before(self.parse_identifier()?))
11566            } else if self.parse_keyword(Keyword::AFTER) {
11567                Some(AlterTypeAddValuePosition::After(self.parse_identifier()?))
11568            } else {
11569                None
11570            };
11571
11572            Ok(Statement::AlterType(AlterType {
11573                name,
11574                operation: AlterTypeOperation::AddValue(AlterTypeAddValue {
11575                    if_not_exists,
11576                    value: new_enum_value,
11577                    position,
11578                }),
11579            }))
11580        } else if self.parse_keywords(&[Keyword::RENAME, Keyword::VALUE]) {
11581            let existing_enum_value = self.parse_identifier()?;
11582            self.expect_keyword(Keyword::TO)?;
11583            let new_enum_value = self.parse_identifier()?;
11584
11585            Ok(Statement::AlterType(AlterType {
11586                name,
11587                operation: AlterTypeOperation::RenameValue(AlterTypeRenameValue {
11588                    from: existing_enum_value,
11589                    to: new_enum_value,
11590                }),
11591            }))
11592        } else {
11593            self.expected_ref(
11594                "{RENAME TO | { RENAME | ADD } VALUE}",
11595                self.peek_token_ref(),
11596            )
11597        }
11598    }
11599
11600    /// Parse a [Statement::AlterCollation].
11601    ///
11602    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-altercollation.html)
11603    pub fn parse_alter_collation(&mut self) -> Result<AlterCollation, ParserError> {
11604        let name = self.parse_object_name(false)?;
11605        let operation = if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
11606            AlterCollationOperation::RenameTo {
11607                new_name: self.parse_identifier()?,
11608            }
11609        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
11610            AlterCollationOperation::OwnerTo(self.parse_owner()?)
11611        } else if self.parse_keywords(&[Keyword::SET, Keyword::SCHEMA]) {
11612            AlterCollationOperation::SetSchema {
11613                schema_name: self.parse_object_name(false)?,
11614            }
11615        } else if self.parse_keywords(&[Keyword::REFRESH, Keyword::VERSION]) {
11616            AlterCollationOperation::RefreshVersion
11617        } else {
11618            return self.expected_ref(
11619                "RENAME TO, OWNER TO, SET SCHEMA, or REFRESH VERSION after ALTER COLLATION",
11620                self.peek_token_ref(),
11621            );
11622        };
11623
11624        Ok(AlterCollation { name, operation })
11625    }
11626
11627    /// Parse a [Statement::AlterOperator]
11628    ///
11629    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-alteroperator.html)
11630    pub fn parse_alter_operator(&mut self) -> Result<AlterOperator, ParserError> {
11631        let name = self.parse_operator_name()?;
11632
11633        // Parse (left_type, right_type)
11634        self.expect_token(&Token::LParen)?;
11635
11636        let left_type = if self.parse_keyword(Keyword::NONE) {
11637            None
11638        } else {
11639            Some(self.parse_data_type()?)
11640        };
11641
11642        self.expect_token(&Token::Comma)?;
11643        let right_type = self.parse_data_type()?;
11644        self.expect_token(&Token::RParen)?;
11645
11646        // Parse the operation
11647        let operation = if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
11648            let owner = if self.parse_keyword(Keyword::CURRENT_ROLE) {
11649                Owner::CurrentRole
11650            } else if self.parse_keyword(Keyword::CURRENT_USER) {
11651                Owner::CurrentUser
11652            } else if self.parse_keyword(Keyword::SESSION_USER) {
11653                Owner::SessionUser
11654            } else {
11655                Owner::Ident(self.parse_identifier()?)
11656            };
11657            AlterOperatorOperation::OwnerTo(owner)
11658        } else if self.parse_keywords(&[Keyword::SET, Keyword::SCHEMA]) {
11659            let schema_name = self.parse_object_name(false)?;
11660            AlterOperatorOperation::SetSchema { schema_name }
11661        } else if self.parse_keyword(Keyword::SET) {
11662            self.expect_token(&Token::LParen)?;
11663
11664            let mut options = Vec::new();
11665            loop {
11666                let keyword = self.expect_one_of_keywords(&[
11667                    Keyword::RESTRICT,
11668                    Keyword::JOIN,
11669                    Keyword::COMMUTATOR,
11670                    Keyword::NEGATOR,
11671                    Keyword::HASHES,
11672                    Keyword::MERGES,
11673                ])?;
11674
11675                match keyword {
11676                    Keyword::RESTRICT => {
11677                        self.expect_token(&Token::Eq)?;
11678                        let proc_name = if self.parse_keyword(Keyword::NONE) {
11679                            None
11680                        } else {
11681                            Some(self.parse_object_name(false)?)
11682                        };
11683                        options.push(OperatorOption::Restrict(proc_name));
11684                    }
11685                    Keyword::JOIN => {
11686                        self.expect_token(&Token::Eq)?;
11687                        let proc_name = if self.parse_keyword(Keyword::NONE) {
11688                            None
11689                        } else {
11690                            Some(self.parse_object_name(false)?)
11691                        };
11692                        options.push(OperatorOption::Join(proc_name));
11693                    }
11694                    Keyword::COMMUTATOR => {
11695                        self.expect_token(&Token::Eq)?;
11696                        let op_name = self.parse_operator_name()?;
11697                        options.push(OperatorOption::Commutator(op_name));
11698                    }
11699                    Keyword::NEGATOR => {
11700                        self.expect_token(&Token::Eq)?;
11701                        let op_name = self.parse_operator_name()?;
11702                        options.push(OperatorOption::Negator(op_name));
11703                    }
11704                    Keyword::HASHES => {
11705                        options.push(OperatorOption::Hashes);
11706                    }
11707                    Keyword::MERGES => {
11708                        options.push(OperatorOption::Merges);
11709                    }
11710                    unexpected_keyword => return Err(ParserError::ParserError(
11711                        format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in operator option"),
11712                    )),
11713                }
11714
11715                if !self.consume_token(&Token::Comma) {
11716                    break;
11717                }
11718            }
11719
11720            self.expect_token(&Token::RParen)?;
11721            AlterOperatorOperation::Set { options }
11722        } else {
11723            return self.expected_ref(
11724                "OWNER TO, SET SCHEMA, or SET after ALTER OPERATOR",
11725                self.peek_token_ref(),
11726            );
11727        };
11728
11729        Ok(AlterOperator {
11730            name,
11731            left_type,
11732            right_type,
11733            operation,
11734        })
11735    }
11736
11737    /// Parse an operator item for ALTER OPERATOR FAMILY ADD operations
11738    fn parse_operator_family_add_operator(&mut self) -> Result<OperatorFamilyItem, ParserError> {
11739        let strategy_number = self.parse_literal_uint()?;
11740        let operator_name = self.parse_operator_name()?;
11741
11742        // Operator argument types (required for ALTER OPERATOR FAMILY)
11743        self.expect_token(&Token::LParen)?;
11744        let op_types = self.parse_comma_separated(Parser::parse_data_type)?;
11745        self.expect_token(&Token::RParen)?;
11746
11747        // Optional purpose
11748        let purpose = if self.parse_keyword(Keyword::FOR) {
11749            if self.parse_keyword(Keyword::SEARCH) {
11750                Some(OperatorPurpose::ForSearch)
11751            } else if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
11752                let sort_family = self.parse_object_name(false)?;
11753                Some(OperatorPurpose::ForOrderBy { sort_family })
11754            } else {
11755                return self.expected_ref("SEARCH or ORDER BY after FOR", self.peek_token_ref());
11756            }
11757        } else {
11758            None
11759        };
11760
11761        Ok(OperatorFamilyItem::Operator {
11762            strategy_number,
11763            operator_name,
11764            op_types,
11765            purpose,
11766        })
11767    }
11768
11769    /// Parse a function item for ALTER OPERATOR FAMILY ADD operations
11770    fn parse_operator_family_add_function(&mut self) -> Result<OperatorFamilyItem, ParserError> {
11771        let support_number = self.parse_literal_uint()?;
11772
11773        // Optional operator types
11774        let op_types =
11775            if self.consume_token(&Token::LParen) && self.peek_token_ref().token != Token::RParen {
11776                let types = self.parse_comma_separated(Parser::parse_data_type)?;
11777                self.expect_token(&Token::RParen)?;
11778                Some(types)
11779            } else if self.consume_token(&Token::LParen) {
11780                self.expect_token(&Token::RParen)?;
11781                Some(vec![])
11782            } else {
11783                None
11784            };
11785
11786        let function_name = self.parse_object_name(false)?;
11787
11788        // Function argument types
11789        let argument_types = if self.consume_token(&Token::LParen) {
11790            if self.peek_token_ref().token == Token::RParen {
11791                self.expect_token(&Token::RParen)?;
11792                vec![]
11793            } else {
11794                let types = self.parse_comma_separated(Parser::parse_data_type)?;
11795                self.expect_token(&Token::RParen)?;
11796                types
11797            }
11798        } else {
11799            vec![]
11800        };
11801
11802        Ok(OperatorFamilyItem::Function {
11803            support_number,
11804            op_types,
11805            function_name,
11806            argument_types,
11807        })
11808    }
11809
11810    /// Parse an operator item for ALTER OPERATOR FAMILY DROP operations
11811    fn parse_operator_family_drop_operator(
11812        &mut self,
11813    ) -> Result<OperatorFamilyDropItem, ParserError> {
11814        let strategy_number = self.parse_literal_uint()?;
11815
11816        // Operator argument types (required for DROP)
11817        self.expect_token(&Token::LParen)?;
11818        let op_types = self.parse_comma_separated(Parser::parse_data_type)?;
11819        self.expect_token(&Token::RParen)?;
11820
11821        Ok(OperatorFamilyDropItem::Operator {
11822            strategy_number,
11823            op_types,
11824        })
11825    }
11826
11827    /// Parse a function item for ALTER OPERATOR FAMILY DROP operations
11828    fn parse_operator_family_drop_function(
11829        &mut self,
11830    ) -> Result<OperatorFamilyDropItem, ParserError> {
11831        let support_number = self.parse_literal_uint()?;
11832
11833        // Operator types (required for DROP)
11834        self.expect_token(&Token::LParen)?;
11835        let op_types = self.parse_comma_separated(Parser::parse_data_type)?;
11836        self.expect_token(&Token::RParen)?;
11837
11838        Ok(OperatorFamilyDropItem::Function {
11839            support_number,
11840            op_types,
11841        })
11842    }
11843
11844    /// Parse an operator family item for ADD operations (dispatches to operator or function parsing)
11845    fn parse_operator_family_add_item(&mut self) -> Result<OperatorFamilyItem, ParserError> {
11846        if self.parse_keyword(Keyword::OPERATOR) {
11847            self.parse_operator_family_add_operator()
11848        } else if self.parse_keyword(Keyword::FUNCTION) {
11849            self.parse_operator_family_add_function()
11850        } else {
11851            self.expected_ref("OPERATOR or FUNCTION", self.peek_token_ref())
11852        }
11853    }
11854
11855    /// Parse an operator family item for DROP operations (dispatches to operator or function parsing)
11856    fn parse_operator_family_drop_item(&mut self) -> Result<OperatorFamilyDropItem, ParserError> {
11857        if self.parse_keyword(Keyword::OPERATOR) {
11858            self.parse_operator_family_drop_operator()
11859        } else if self.parse_keyword(Keyword::FUNCTION) {
11860            self.parse_operator_family_drop_function()
11861        } else {
11862            self.expected_ref("OPERATOR or FUNCTION", self.peek_token_ref())
11863        }
11864    }
11865
11866    /// Parse a [Statement::AlterOperatorFamily]
11867    /// See <https://www.postgresql.org/docs/current/sql-alteropfamily.html>
11868    pub fn parse_alter_operator_family(&mut self) -> Result<AlterOperatorFamily, ParserError> {
11869        let name = self.parse_object_name(false)?;
11870        self.expect_keyword(Keyword::USING)?;
11871        let using = self.parse_identifier()?;
11872
11873        let operation = if self.parse_keyword(Keyword::ADD) {
11874            let items = self.parse_comma_separated(Parser::parse_operator_family_add_item)?;
11875            AlterOperatorFamilyOperation::Add { items }
11876        } else if self.parse_keyword(Keyword::DROP) {
11877            let items = self.parse_comma_separated(Parser::parse_operator_family_drop_item)?;
11878            AlterOperatorFamilyOperation::Drop { items }
11879        } else if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
11880            let new_name = self.parse_object_name(false)?;
11881            AlterOperatorFamilyOperation::RenameTo { new_name }
11882        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
11883            let owner = self.parse_owner()?;
11884            AlterOperatorFamilyOperation::OwnerTo(owner)
11885        } else if self.parse_keywords(&[Keyword::SET, Keyword::SCHEMA]) {
11886            let schema_name = self.parse_object_name(false)?;
11887            AlterOperatorFamilyOperation::SetSchema { schema_name }
11888        } else {
11889            return self.expected_ref(
11890                "ADD, DROP, RENAME TO, OWNER TO, or SET SCHEMA after ALTER OPERATOR FAMILY",
11891                self.peek_token_ref(),
11892            );
11893        };
11894
11895        Ok(AlterOperatorFamily {
11896            name,
11897            using,
11898            operation,
11899        })
11900    }
11901
11902    /// Parse an `ALTER OPERATOR CLASS` statement.
11903    ///
11904    /// Handles operations like `RENAME TO`, `OWNER TO`, and `SET SCHEMA`.
11905    pub fn parse_alter_operator_class(&mut self) -> Result<AlterOperatorClass, ParserError> {
11906        let name = self.parse_object_name(false)?;
11907        self.expect_keyword(Keyword::USING)?;
11908        let using = self.parse_identifier()?;
11909
11910        let operation = if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
11911            let new_name = self.parse_object_name(false)?;
11912            AlterOperatorClassOperation::RenameTo { new_name }
11913        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
11914            let owner = self.parse_owner()?;
11915            AlterOperatorClassOperation::OwnerTo(owner)
11916        } else if self.parse_keywords(&[Keyword::SET, Keyword::SCHEMA]) {
11917            let schema_name = self.parse_object_name(false)?;
11918            AlterOperatorClassOperation::SetSchema { schema_name }
11919        } else {
11920            return self.expected_ref(
11921                "RENAME TO, OWNER TO, or SET SCHEMA after ALTER OPERATOR CLASS",
11922                self.peek_token_ref(),
11923            );
11924        };
11925
11926        Ok(AlterOperatorClass {
11927            name,
11928            using,
11929            operation,
11930        })
11931    }
11932
11933    /// Parse an `ALTER SCHEMA` statement.
11934    ///
11935    /// Supports operations such as setting options, renaming, adding/dropping replicas, and changing owner.
11936    pub fn parse_alter_schema(&mut self) -> Result<Statement, ParserError> {
11937        self.expect_keywords(&[Keyword::ALTER, Keyword::SCHEMA])?;
11938        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
11939        let name = self.parse_object_name(false)?;
11940        let operation = if self.parse_keywords(&[Keyword::SET, Keyword::OPTIONS]) {
11941            self.prev_token();
11942            let options = self.parse_options(Keyword::OPTIONS)?;
11943            AlterSchemaOperation::SetOptionsParens { options }
11944        } else if self.parse_keywords(&[Keyword::SET, Keyword::DEFAULT, Keyword::COLLATE]) {
11945            let collate = self.parse_expr()?;
11946            AlterSchemaOperation::SetDefaultCollate { collate }
11947        } else if self.parse_keywords(&[Keyword::ADD, Keyword::REPLICA]) {
11948            let replica = self.parse_identifier()?;
11949            let options = if self.peek_keyword(Keyword::OPTIONS) {
11950                Some(self.parse_options(Keyword::OPTIONS)?)
11951            } else {
11952                None
11953            };
11954            AlterSchemaOperation::AddReplica { replica, options }
11955        } else if self.parse_keywords(&[Keyword::DROP, Keyword::REPLICA]) {
11956            let replica = self.parse_identifier()?;
11957            AlterSchemaOperation::DropReplica { replica }
11958        } else if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
11959            let new_name = self.parse_object_name(false)?;
11960            AlterSchemaOperation::Rename { name: new_name }
11961        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
11962            let owner = self.parse_owner()?;
11963            AlterSchemaOperation::OwnerTo { owner }
11964        } else {
11965            return self.expected_ref("ALTER SCHEMA operation", self.peek_token_ref());
11966        };
11967        Ok(Statement::AlterSchema(AlterSchema {
11968            name,
11969            if_exists,
11970            operations: vec![operation],
11971        }))
11972    }
11973
11974    /// Parse a `CALL procedure_name(arg1, arg2, ...)`
11975    /// or `CALL procedure_name` statement
11976    pub fn parse_call(&mut self) -> Result<Statement, ParserError> {
11977        let object_name = self.parse_object_name(false)?;
11978        if self.peek_token_ref().token == Token::LParen {
11979            match self.parse_function(object_name)? {
11980                Expr::Function(f) => Ok(Statement::Call(f)),
11981                other => parser_err!(
11982                    format!("Expected a simple procedure call but found: {other}"),
11983                    self.peek_token_ref().span.start
11984                ),
11985            }
11986        } else {
11987            Ok(Statement::Call(Function {
11988                name: object_name,
11989                uses_odbc_syntax: false,
11990                parameters: FunctionArguments::None,
11991                args: FunctionArguments::None,
11992                over: None,
11993                filter: None,
11994                null_treatment: None,
11995                within_group: vec![],
11996            }))
11997        }
11998    }
11999
12000    /// Parse a copy statement
12001    pub fn parse_copy(&mut self) -> Result<Statement, ParserError> {
12002        let source;
12003        if self.consume_token(&Token::LParen) {
12004            source = CopySource::Query(self.parse_query()?);
12005            self.expect_token(&Token::RParen)?;
12006        } else {
12007            let table_name = self.parse_object_name(false)?;
12008            let columns = self.parse_parenthesized_column_list(Optional, false)?;
12009            source = CopySource::Table {
12010                table_name,
12011                columns,
12012            };
12013        }
12014        let to = match self.parse_one_of_keywords(&[Keyword::FROM, Keyword::TO]) {
12015            Some(Keyword::FROM) => false,
12016            Some(Keyword::TO) => true,
12017            _ => self.expected_ref("FROM or TO", self.peek_token_ref())?,
12018        };
12019        if !to {
12020            // Use a separate if statement to prevent Rust compiler from complaining about
12021            // "if statement in this position is unstable: https://github.com/rust-lang/rust/issues/53667"
12022            if let CopySource::Query(_) = source {
12023                return Err(ParserError::ParserError(
12024                    "COPY ... FROM does not support query as a source".to_string(),
12025                ));
12026            }
12027        }
12028        let target = if self.parse_keyword(Keyword::STDIN) {
12029            CopyTarget::Stdin
12030        } else if self.parse_keyword(Keyword::STDOUT) {
12031            CopyTarget::Stdout
12032        } else if self.parse_keyword(Keyword::PROGRAM) {
12033            CopyTarget::Program {
12034                command: self.parse_literal_string()?,
12035            }
12036        } else {
12037            CopyTarget::File {
12038                filename: self.parse_literal_string()?,
12039            }
12040        };
12041        let _ = self.parse_keyword(Keyword::WITH); // [ WITH ]
12042        let mut options = vec![];
12043        if self.consume_token(&Token::LParen) {
12044            options = self.parse_comma_separated(Parser::parse_copy_option)?;
12045            self.expect_token(&Token::RParen)?;
12046        }
12047        let mut legacy_options = vec![];
12048        while let Some(opt) = self.maybe_parse(|parser| parser.parse_copy_legacy_option())? {
12049            legacy_options.push(opt);
12050        }
12051        let values =
12052            if matches!(target, CopyTarget::Stdin) && self.peek_token_ref().token != Token::EOF {
12053                self.expect_token(&Token::SemiColon)?;
12054                self.parse_tsv()
12055            } else {
12056                vec![]
12057            };
12058        Ok(Statement::Copy {
12059            source,
12060            to,
12061            target,
12062            options,
12063            legacy_options,
12064            values,
12065        })
12066    }
12067
12068    /// Parse [Statement::Open]
12069    fn parse_open(&mut self) -> Result<Statement, ParserError> {
12070        self.expect_keyword(Keyword::OPEN)?;
12071        Ok(Statement::Open(OpenStatement {
12072            cursor_name: self.parse_identifier()?,
12073        }))
12074    }
12075
12076    /// Parse a `CLOSE` cursor statement.
12077    pub fn parse_close(&mut self) -> Result<Statement, ParserError> {
12078        let cursor = if self.parse_keyword(Keyword::ALL) {
12079            CloseCursor::All
12080        } else {
12081            let name = self.parse_identifier()?;
12082
12083            CloseCursor::Specific { name }
12084        };
12085
12086        Ok(Statement::Close { cursor })
12087    }
12088
12089    fn parse_copy_option(&mut self) -> Result<CopyOption, ParserError> {
12090        let ret = match self.parse_one_of_keywords(&[
12091            Keyword::FORMAT,
12092            Keyword::FREEZE,
12093            Keyword::DELIMITER,
12094            Keyword::NULL,
12095            Keyword::HEADER,
12096            Keyword::QUOTE,
12097            Keyword::ESCAPE,
12098            Keyword::FORCE_QUOTE,
12099            Keyword::FORCE_NOT_NULL,
12100            Keyword::FORCE_NULL,
12101            Keyword::ENCODING,
12102        ]) {
12103            Some(Keyword::FORMAT) => CopyOption::Format(self.parse_identifier()?),
12104            Some(Keyword::FREEZE) => CopyOption::Freeze(!matches!(
12105                self.parse_one_of_keywords(&[Keyword::TRUE, Keyword::FALSE]),
12106                Some(Keyword::FALSE)
12107            )),
12108            Some(Keyword::DELIMITER) => CopyOption::Delimiter(self.parse_literal_char()?),
12109            Some(Keyword::NULL) => CopyOption::Null(self.parse_literal_string()?),
12110            Some(Keyword::HEADER) => CopyOption::Header(!matches!(
12111                self.parse_one_of_keywords(&[Keyword::TRUE, Keyword::FALSE]),
12112                Some(Keyword::FALSE)
12113            )),
12114            Some(Keyword::QUOTE) => CopyOption::Quote(self.parse_literal_char()?),
12115            Some(Keyword::ESCAPE) => CopyOption::Escape(self.parse_literal_char()?),
12116            Some(Keyword::FORCE_QUOTE) => {
12117                CopyOption::ForceQuote(self.parse_parenthesized_column_list(Mandatory, false)?)
12118            }
12119            Some(Keyword::FORCE_NOT_NULL) => {
12120                CopyOption::ForceNotNull(self.parse_parenthesized_column_list(Mandatory, false)?)
12121            }
12122            Some(Keyword::FORCE_NULL) => {
12123                CopyOption::ForceNull(self.parse_parenthesized_column_list(Mandatory, false)?)
12124            }
12125            Some(Keyword::ENCODING) => CopyOption::Encoding(self.parse_literal_string()?),
12126            _ => self.expected_ref("option", self.peek_token_ref())?,
12127        };
12128        Ok(ret)
12129    }
12130
12131    fn parse_copy_legacy_option(&mut self) -> Result<CopyLegacyOption, ParserError> {
12132        // FORMAT \[ AS \] is optional
12133        if self.parse_keyword(Keyword::FORMAT) {
12134            let _ = self.parse_keyword(Keyword::AS);
12135        }
12136
12137        let ret = match self.parse_one_of_keywords(&[
12138            Keyword::ACCEPTANYDATE,
12139            Keyword::ACCEPTINVCHARS,
12140            Keyword::ADDQUOTES,
12141            Keyword::ALLOWOVERWRITE,
12142            Keyword::BINARY,
12143            Keyword::BLANKSASNULL,
12144            Keyword::BZIP2,
12145            Keyword::CLEANPATH,
12146            Keyword::COMPUPDATE,
12147            Keyword::CREDENTIALS,
12148            Keyword::CSV,
12149            Keyword::DATEFORMAT,
12150            Keyword::DELIMITER,
12151            Keyword::EMPTYASNULL,
12152            Keyword::ENCRYPTED,
12153            Keyword::ESCAPE,
12154            Keyword::EXTENSION,
12155            Keyword::FIXEDWIDTH,
12156            Keyword::GZIP,
12157            Keyword::HEADER,
12158            Keyword::IAM_ROLE,
12159            Keyword::IGNOREHEADER,
12160            Keyword::JSON,
12161            Keyword::MANIFEST,
12162            Keyword::MAXFILESIZE,
12163            Keyword::NULL,
12164            Keyword::PARALLEL,
12165            Keyword::PARQUET,
12166            Keyword::PARTITION,
12167            Keyword::REGION,
12168            Keyword::REMOVEQUOTES,
12169            Keyword::ROWGROUPSIZE,
12170            Keyword::STATUPDATE,
12171            Keyword::TIMEFORMAT,
12172            Keyword::TRUNCATECOLUMNS,
12173            Keyword::ZSTD,
12174        ]) {
12175            Some(Keyword::ACCEPTANYDATE) => CopyLegacyOption::AcceptAnyDate,
12176            Some(Keyword::ACCEPTINVCHARS) => {
12177                let _ = self.parse_keyword(Keyword::AS); // [ AS ]
12178                let ch = if matches!(self.peek_token_ref().token, Token::SingleQuotedString(_)) {
12179                    Some(self.parse_literal_string()?)
12180                } else {
12181                    None
12182                };
12183                CopyLegacyOption::AcceptInvChars(ch)
12184            }
12185            Some(Keyword::ADDQUOTES) => CopyLegacyOption::AddQuotes,
12186            Some(Keyword::ALLOWOVERWRITE) => CopyLegacyOption::AllowOverwrite,
12187            Some(Keyword::BINARY) => CopyLegacyOption::Binary,
12188            Some(Keyword::BLANKSASNULL) => CopyLegacyOption::BlankAsNull,
12189            Some(Keyword::BZIP2) => CopyLegacyOption::Bzip2,
12190            Some(Keyword::CLEANPATH) => CopyLegacyOption::CleanPath,
12191            Some(Keyword::COMPUPDATE) => {
12192                let preset = self.parse_keyword(Keyword::PRESET);
12193                let enabled = match self.parse_one_of_keywords(&[
12194                    Keyword::TRUE,
12195                    Keyword::FALSE,
12196                    Keyword::ON,
12197                    Keyword::OFF,
12198                ]) {
12199                    Some(Keyword::TRUE) | Some(Keyword::ON) => Some(true),
12200                    Some(Keyword::FALSE) | Some(Keyword::OFF) => Some(false),
12201                    _ => None,
12202                };
12203                CopyLegacyOption::CompUpdate { preset, enabled }
12204            }
12205            Some(Keyword::CREDENTIALS) => {
12206                CopyLegacyOption::Credentials(self.parse_literal_string()?)
12207            }
12208            Some(Keyword::CSV) => CopyLegacyOption::Csv({
12209                let mut opts = vec![];
12210                while let Some(opt) =
12211                    self.maybe_parse(|parser| parser.parse_copy_legacy_csv_option())?
12212                {
12213                    opts.push(opt);
12214                }
12215                opts
12216            }),
12217            Some(Keyword::DATEFORMAT) => {
12218                let _ = self.parse_keyword(Keyword::AS);
12219                let fmt = if matches!(self.peek_token_ref().token, Token::SingleQuotedString(_)) {
12220                    Some(self.parse_literal_string()?)
12221                } else {
12222                    None
12223                };
12224                CopyLegacyOption::DateFormat(fmt)
12225            }
12226            Some(Keyword::DELIMITER) => {
12227                let _ = self.parse_keyword(Keyword::AS);
12228                CopyLegacyOption::Delimiter(self.parse_literal_char()?)
12229            }
12230            Some(Keyword::EMPTYASNULL) => CopyLegacyOption::EmptyAsNull,
12231            Some(Keyword::ENCRYPTED) => {
12232                let auto = self.parse_keyword(Keyword::AUTO);
12233                CopyLegacyOption::Encrypted { auto }
12234            }
12235            Some(Keyword::ESCAPE) => CopyLegacyOption::Escape,
12236            Some(Keyword::EXTENSION) => {
12237                let ext = self.parse_literal_string()?;
12238                CopyLegacyOption::Extension(ext)
12239            }
12240            Some(Keyword::FIXEDWIDTH) => {
12241                let spec = self.parse_literal_string()?;
12242                CopyLegacyOption::FixedWidth(spec)
12243            }
12244            Some(Keyword::GZIP) => CopyLegacyOption::Gzip,
12245            Some(Keyword::HEADER) => CopyLegacyOption::Header,
12246            Some(Keyword::IAM_ROLE) => CopyLegacyOption::IamRole(self.parse_iam_role_kind()?),
12247            Some(Keyword::IGNOREHEADER) => {
12248                let _ = self.parse_keyword(Keyword::AS);
12249                let num_rows = self.parse_literal_uint()?;
12250                CopyLegacyOption::IgnoreHeader(num_rows)
12251            }
12252            Some(Keyword::JSON) => {
12253                let _ = self.parse_keyword(Keyword::AS);
12254                let fmt = if matches!(self.peek_token_ref().token, Token::SingleQuotedString(_)) {
12255                    Some(self.parse_literal_string()?)
12256                } else {
12257                    None
12258                };
12259                CopyLegacyOption::Json(fmt)
12260            }
12261            Some(Keyword::MANIFEST) => {
12262                let verbose = self.parse_keyword(Keyword::VERBOSE);
12263                CopyLegacyOption::Manifest { verbose }
12264            }
12265            Some(Keyword::MAXFILESIZE) => {
12266                let _ = self.parse_keyword(Keyword::AS);
12267                let size = self.parse_number_value()?;
12268                let unit = match self.parse_one_of_keywords(&[Keyword::MB, Keyword::GB]) {
12269                    Some(Keyword::MB) => Some(FileSizeUnit::MB),
12270                    Some(Keyword::GB) => Some(FileSizeUnit::GB),
12271                    _ => None,
12272                };
12273                CopyLegacyOption::MaxFileSize(FileSize { size, unit })
12274            }
12275            Some(Keyword::NULL) => {
12276                let _ = self.parse_keyword(Keyword::AS);
12277                CopyLegacyOption::Null(self.parse_literal_string()?)
12278            }
12279            Some(Keyword::PARALLEL) => {
12280                let enabled = match self.parse_one_of_keywords(&[
12281                    Keyword::TRUE,
12282                    Keyword::FALSE,
12283                    Keyword::ON,
12284                    Keyword::OFF,
12285                ]) {
12286                    Some(Keyword::TRUE) | Some(Keyword::ON) => Some(true),
12287                    Some(Keyword::FALSE) | Some(Keyword::OFF) => Some(false),
12288                    _ => None,
12289                };
12290                CopyLegacyOption::Parallel(enabled)
12291            }
12292            Some(Keyword::PARQUET) => CopyLegacyOption::Parquet,
12293            Some(Keyword::PARTITION) => {
12294                self.expect_keyword(Keyword::BY)?;
12295                let columns = self.parse_parenthesized_column_list(IsOptional::Mandatory, false)?;
12296                let include = self.parse_keyword(Keyword::INCLUDE);
12297                CopyLegacyOption::PartitionBy(UnloadPartitionBy { columns, include })
12298            }
12299            Some(Keyword::REGION) => {
12300                let _ = self.parse_keyword(Keyword::AS);
12301                let region = self.parse_literal_string()?;
12302                CopyLegacyOption::Region(region)
12303            }
12304            Some(Keyword::REMOVEQUOTES) => CopyLegacyOption::RemoveQuotes,
12305            Some(Keyword::ROWGROUPSIZE) => {
12306                let _ = self.parse_keyword(Keyword::AS);
12307                let file_size = self.parse_file_size()?;
12308                CopyLegacyOption::RowGroupSize(file_size)
12309            }
12310            Some(Keyword::STATUPDATE) => {
12311                let enabled = match self.parse_one_of_keywords(&[
12312                    Keyword::TRUE,
12313                    Keyword::FALSE,
12314                    Keyword::ON,
12315                    Keyword::OFF,
12316                ]) {
12317                    Some(Keyword::TRUE) | Some(Keyword::ON) => Some(true),
12318                    Some(Keyword::FALSE) | Some(Keyword::OFF) => Some(false),
12319                    _ => None,
12320                };
12321                CopyLegacyOption::StatUpdate(enabled)
12322            }
12323            Some(Keyword::TIMEFORMAT) => {
12324                let _ = self.parse_keyword(Keyword::AS);
12325                let fmt = if matches!(self.peek_token_ref().token, Token::SingleQuotedString(_)) {
12326                    Some(self.parse_literal_string()?)
12327                } else {
12328                    None
12329                };
12330                CopyLegacyOption::TimeFormat(fmt)
12331            }
12332            Some(Keyword::TRUNCATECOLUMNS) => CopyLegacyOption::TruncateColumns,
12333            Some(Keyword::ZSTD) => CopyLegacyOption::Zstd,
12334            _ => self.expected_ref("option", self.peek_token_ref())?,
12335        };
12336        Ok(ret)
12337    }
12338
12339    fn parse_file_size(&mut self) -> Result<FileSize, ParserError> {
12340        let size = self.parse_number_value()?;
12341        let unit = self.maybe_parse_file_size_unit();
12342        Ok(FileSize { size, unit })
12343    }
12344
12345    fn maybe_parse_file_size_unit(&mut self) -> Option<FileSizeUnit> {
12346        match self.parse_one_of_keywords(&[Keyword::MB, Keyword::GB]) {
12347            Some(Keyword::MB) => Some(FileSizeUnit::MB),
12348            Some(Keyword::GB) => Some(FileSizeUnit::GB),
12349            _ => None,
12350        }
12351    }
12352
12353    fn parse_iam_role_kind(&mut self) -> Result<IamRoleKind, ParserError> {
12354        if self.parse_keyword(Keyword::DEFAULT) {
12355            Ok(IamRoleKind::Default)
12356        } else {
12357            let arn = self.parse_literal_string()?;
12358            Ok(IamRoleKind::Arn(arn))
12359        }
12360    }
12361
12362    fn parse_copy_legacy_csv_option(&mut self) -> Result<CopyLegacyCsvOption, ParserError> {
12363        let ret = match self.parse_one_of_keywords(&[
12364            Keyword::HEADER,
12365            Keyword::QUOTE,
12366            Keyword::ESCAPE,
12367            Keyword::FORCE,
12368        ]) {
12369            Some(Keyword::HEADER) => CopyLegacyCsvOption::Header,
12370            Some(Keyword::QUOTE) => {
12371                let _ = self.parse_keyword(Keyword::AS); // [ AS ]
12372                CopyLegacyCsvOption::Quote(self.parse_literal_char()?)
12373            }
12374            Some(Keyword::ESCAPE) => {
12375                let _ = self.parse_keyword(Keyword::AS); // [ AS ]
12376                CopyLegacyCsvOption::Escape(self.parse_literal_char()?)
12377            }
12378            Some(Keyword::FORCE) if self.parse_keywords(&[Keyword::NOT, Keyword::NULL]) => {
12379                CopyLegacyCsvOption::ForceNotNull(
12380                    self.parse_comma_separated(|p| p.parse_identifier())?,
12381                )
12382            }
12383            Some(Keyword::FORCE) if self.parse_keywords(&[Keyword::QUOTE]) => {
12384                CopyLegacyCsvOption::ForceQuote(
12385                    self.parse_comma_separated(|p| p.parse_identifier())?,
12386                )
12387            }
12388            _ => self.expected_ref("csv option", self.peek_token_ref())?,
12389        };
12390        Ok(ret)
12391    }
12392
12393    fn parse_literal_char(&mut self) -> Result<char, ParserError> {
12394        let s = self.parse_literal_string()?;
12395        if s.len() != 1 {
12396            let loc = self
12397                .tokens
12398                .get(self.index - 1)
12399                .map_or(Location { line: 0, column: 0 }, |t| t.span.start);
12400            return parser_err!(format!("Expect a char, found {s:?}"), loc);
12401        }
12402        Ok(s.chars().next().unwrap())
12403    }
12404
12405    /// Parse a tab separated values in
12406    /// COPY payload
12407    pub fn parse_tsv(&mut self) -> Vec<Option<String>> {
12408        self.parse_tab_value()
12409    }
12410
12411    /// Parse a single tab-separated value row used by `COPY` payload parsing.
12412    pub fn parse_tab_value(&mut self) -> Vec<Option<String>> {
12413        let mut values = vec![];
12414        let mut content = String::new();
12415        while let Some(t) = self.next_token_no_skip().map(|t| &t.token) {
12416            match t {
12417                Token::Whitespace(Whitespace::Tab) => {
12418                    values.push(Some(core::mem::take(&mut content)));
12419                }
12420                Token::Whitespace(Whitespace::Newline) => {
12421                    values.push(Some(core::mem::take(&mut content)));
12422                }
12423                Token::Backslash => {
12424                    if self.consume_token(&Token::Period) {
12425                        return values;
12426                    }
12427                    if let Token::Word(w) = self.next_token().token {
12428                        if w.value == "N" {
12429                            values.push(None);
12430                        }
12431                    }
12432                }
12433                _ => {
12434                    content.push_str(&t.to_string());
12435                }
12436            }
12437        }
12438        values
12439    }
12440
12441    /// Parse a literal value (numbers, strings, date/time, booleans)
12442    pub fn parse_value(&mut self) -> Result<ValueWithSpan, ParserError> {
12443        let next_token = self.next_token();
12444        let span = next_token.span;
12445        let ok_value = |value: Value| Ok(value.with_span(span));
12446        match next_token.token {
12447            Token::Word(w) => match w.keyword {
12448                Keyword::TRUE if self.dialect.supports_boolean_literals() => {
12449                    ok_value(Value::Boolean(true))
12450                }
12451                Keyword::FALSE if self.dialect.supports_boolean_literals() => {
12452                    ok_value(Value::Boolean(false))
12453                }
12454                Keyword::NULL => ok_value(Value::Null),
12455                Keyword::NoKeyword if w.quote_style.is_some() => match w.quote_style {
12456                    Some('"') => ok_value(Value::DoubleQuotedString(w.value)),
12457                    Some('\'') => ok_value(Value::SingleQuotedString(w.value)),
12458                    _ => self.expected(
12459                        "A value?",
12460                        TokenWithSpan {
12461                            token: Token::Word(w),
12462                            span,
12463                        },
12464                    )?,
12465                },
12466                _ => self.expected(
12467                    "a concrete value",
12468                    TokenWithSpan {
12469                        token: Token::Word(w),
12470                        span,
12471                    },
12472                ),
12473            },
12474            // The call to n.parse() returns a bigdecimal when the
12475            // bigdecimal feature is enabled, and is otherwise a no-op
12476            // (i.e., it returns the input string).
12477            Token::Number(n, l) => ok_value(Value::Number(Self::parse(n, span.start)?, l)),
12478            Token::SingleQuotedString(ref s) => ok_value(Value::SingleQuotedString(
12479                self.maybe_concat_string_literal(s.to_string()),
12480            )),
12481            Token::DoubleQuotedString(ref s) => ok_value(Value::DoubleQuotedString(
12482                self.maybe_concat_string_literal(s.to_string()),
12483            )),
12484            Token::TripleSingleQuotedString(ref s) => {
12485                ok_value(Value::TripleSingleQuotedString(s.to_string()))
12486            }
12487            Token::TripleDoubleQuotedString(ref s) => {
12488                ok_value(Value::TripleDoubleQuotedString(s.to_string()))
12489            }
12490            Token::DollarQuotedString(ref s) => ok_value(Value::DollarQuotedString(s.clone())),
12491            Token::SingleQuotedByteStringLiteral(ref s) => {
12492                ok_value(Value::SingleQuotedByteStringLiteral(s.clone()))
12493            }
12494            Token::DoubleQuotedByteStringLiteral(ref s) => {
12495                ok_value(Value::DoubleQuotedByteStringLiteral(s.clone()))
12496            }
12497            Token::TripleSingleQuotedByteStringLiteral(ref s) => {
12498                ok_value(Value::TripleSingleQuotedByteStringLiteral(s.clone()))
12499            }
12500            Token::TripleDoubleQuotedByteStringLiteral(ref s) => {
12501                ok_value(Value::TripleDoubleQuotedByteStringLiteral(s.clone()))
12502            }
12503            Token::SingleQuotedRawStringLiteral(ref s) => {
12504                ok_value(Value::SingleQuotedRawStringLiteral(s.clone()))
12505            }
12506            Token::DoubleQuotedRawStringLiteral(ref s) => {
12507                ok_value(Value::DoubleQuotedRawStringLiteral(s.clone()))
12508            }
12509            Token::TripleSingleQuotedRawStringLiteral(ref s) => {
12510                ok_value(Value::TripleSingleQuotedRawStringLiteral(s.clone()))
12511            }
12512            Token::TripleDoubleQuotedRawStringLiteral(ref s) => {
12513                ok_value(Value::TripleDoubleQuotedRawStringLiteral(s.clone()))
12514            }
12515            Token::NationalStringLiteral(ref s) => {
12516                ok_value(Value::NationalStringLiteral(s.to_string()))
12517            }
12518            Token::QuoteDelimitedStringLiteral(v) => {
12519                ok_value(Value::QuoteDelimitedStringLiteral(v))
12520            }
12521            Token::NationalQuoteDelimitedStringLiteral(v) => {
12522                ok_value(Value::NationalQuoteDelimitedStringLiteral(v))
12523            }
12524            Token::EscapedStringLiteral(ref s) => {
12525                ok_value(Value::EscapedStringLiteral(s.to_string()))
12526            }
12527            Token::UnicodeStringLiteral(ref s) => {
12528                ok_value(Value::UnicodeStringLiteral(s.to_string()))
12529            }
12530            Token::HexStringLiteral(ref s) => ok_value(Value::HexStringLiteral(s.to_string())),
12531            Token::Placeholder(ref s) => ok_value(Value::Placeholder(s.to_string())),
12532            tok @ Token::Colon | tok @ Token::AtSign => {
12533                // 1. Not calling self.parse_identifier(false)?
12534                //    because only in placeholder we want to check
12535                //    numbers as idfentifies.  This because snowflake
12536                //    allows numbers as placeholders
12537                // 2. Not calling self.next_token() to enforce `tok`
12538                //    be followed immediately by a word/number, ie.
12539                //    without any whitespace in between
12540                let next_token = self.next_token_no_skip().unwrap_or(&EOF_TOKEN).clone();
12541                let ident = match next_token.token {
12542                    Token::Word(w) => Ok(w.into_ident(next_token.span)),
12543                    Token::Number(w, false) => Ok(Ident::with_span(next_token.span, w)),
12544                    _ => self.expected("placeholder", next_token),
12545                }?;
12546                Ok(Value::Placeholder(format!("{tok}{}", ident.value))
12547                    .with_span(Span::new(span.start, ident.span.end)))
12548            }
12549            unexpected => self.expected(
12550                "a value",
12551                TokenWithSpan {
12552                    token: unexpected,
12553                    span,
12554                },
12555            ),
12556        }
12557    }
12558
12559    fn maybe_concat_string_literal(&mut self, mut str: String) -> String {
12560        if self.dialect.supports_string_literal_concatenation() {
12561            while let Token::SingleQuotedString(ref s) | Token::DoubleQuotedString(ref s) =
12562                self.peek_token_ref().token
12563            {
12564                str.push_str(s);
12565                self.advance_token();
12566            }
12567        } else if self
12568            .dialect
12569            .supports_string_literal_concatenation_with_newline()
12570        {
12571            // We are iterating over tokens including whitespaces, to identify
12572            // string literals separated by newlines so we can concatenate them.
12573            let mut after_newline = false;
12574            loop {
12575                match self.peek_token_no_skip().token {
12576                    Token::Whitespace(Whitespace::Newline) => {
12577                        after_newline = true;
12578                        self.next_token_no_skip();
12579                    }
12580                    Token::Whitespace(_) => {
12581                        self.next_token_no_skip();
12582                    }
12583                    Token::SingleQuotedString(ref s) | Token::DoubleQuotedString(ref s)
12584                        if after_newline =>
12585                    {
12586                        str.push_str(s.clone().as_str());
12587                        self.next_token_no_skip();
12588                        after_newline = false;
12589                    }
12590                    _ => break,
12591                }
12592            }
12593        }
12594
12595        str
12596    }
12597
12598    /// Parse an unsigned numeric literal
12599    pub fn parse_number_value(&mut self) -> Result<ValueWithSpan, ParserError> {
12600        let value_wrapper = self.parse_value()?;
12601        match &value_wrapper.value {
12602            Value::Number(_, _) => Ok(value_wrapper),
12603            Value::Placeholder(_) => Ok(value_wrapper),
12604            _ => {
12605                self.prev_token();
12606                self.expected_ref("literal number", self.peek_token_ref())
12607            }
12608        }
12609    }
12610
12611    /// Parse a numeric literal as an expression. Returns a [`Expr::UnaryOp`] if the number is signed,
12612    /// otherwise returns a [`Expr::Value`]
12613    pub fn parse_number(&mut self) -> Result<Expr, ParserError> {
12614        let next_token = self.next_token();
12615        match next_token.token {
12616            Token::Plus => Ok(Expr::UnaryOp {
12617                op: UnaryOperator::Plus,
12618                expr: Box::new(Expr::Value(self.parse_number_value()?)),
12619            }),
12620            Token::Minus => Ok(Expr::UnaryOp {
12621                op: UnaryOperator::Minus,
12622                expr: Box::new(Expr::Value(self.parse_number_value()?)),
12623            }),
12624            _ => {
12625                self.prev_token();
12626                Ok(Expr::Value(self.parse_number_value()?))
12627            }
12628        }
12629    }
12630
12631    fn parse_introduced_string_expr(&mut self) -> Result<Expr, ParserError> {
12632        let next_token = self.next_token();
12633        let span = next_token.span;
12634        match next_token.token {
12635            Token::SingleQuotedString(ref s) => Ok(Expr::Value(
12636                Value::SingleQuotedString(s.to_string()).with_span(span),
12637            )),
12638            Token::DoubleQuotedString(ref s) => Ok(Expr::Value(
12639                Value::DoubleQuotedString(s.to_string()).with_span(span),
12640            )),
12641            Token::HexStringLiteral(ref s) => Ok(Expr::Value(
12642                Value::HexStringLiteral(s.to_string()).with_span(span),
12643            )),
12644            unexpected => self.expected(
12645                "a string value",
12646                TokenWithSpan {
12647                    token: unexpected,
12648                    span,
12649                },
12650            ),
12651        }
12652    }
12653
12654    /// Parse an unsigned literal integer/long
12655    pub fn parse_literal_uint(&mut self) -> Result<u64, ParserError> {
12656        let next_token = self.next_token();
12657        match next_token.token {
12658            Token::Number(s, _) => Self::parse::<u64>(s, next_token.span.start),
12659            _ => self.expected("literal int", next_token),
12660        }
12661    }
12662
12663    /// Parse the body of a `CREATE FUNCTION` specified as a string.
12664    /// e.g. `CREATE FUNCTION ... AS $$ body $$`.
12665    fn parse_create_function_body_string(&mut self) -> Result<CreateFunctionBody, ParserError> {
12666        let parse_string_expr = |parser: &mut Parser| -> Result<Expr, ParserError> {
12667            let peek_token = parser.peek_token();
12668            let span = peek_token.span;
12669            match peek_token.token {
12670                Token::DollarQuotedString(s) if dialect_of!(parser is PostgreSqlDialect | GenericDialect) =>
12671                {
12672                    parser.next_token();
12673                    Ok(Expr::Value(Value::DollarQuotedString(s).with_span(span)))
12674                }
12675                _ => Ok(Expr::Value(
12676                    Value::SingleQuotedString(parser.parse_literal_string()?).with_span(span),
12677                )),
12678            }
12679        };
12680
12681        Ok(CreateFunctionBody::AsBeforeOptions {
12682            body: parse_string_expr(self)?,
12683            link_symbol: if self.consume_token(&Token::Comma) {
12684                Some(parse_string_expr(self)?)
12685            } else {
12686                None
12687            },
12688        })
12689    }
12690
12691    /// Parse a literal string
12692    pub fn parse_literal_string(&mut self) -> Result<String, ParserError> {
12693        let next_token = self.next_token();
12694        match next_token.token {
12695            Token::Word(Word {
12696                value,
12697                keyword: Keyword::NoKeyword,
12698                ..
12699            }) => Ok(value),
12700            Token::SingleQuotedString(s) => Ok(s),
12701            Token::DoubleQuotedString(s) => Ok(s),
12702            Token::EscapedStringLiteral(s) if dialect_of!(self is PostgreSqlDialect | GenericDialect) => {
12703                Ok(s)
12704            }
12705            Token::UnicodeStringLiteral(s) => Ok(s),
12706            _ => self.expected("literal string", next_token),
12707        }
12708    }
12709
12710    /// Parse a boolean string
12711    pub(crate) fn parse_boolean_string(&mut self) -> Result<bool, ParserError> {
12712        match self.parse_one_of_keywords(&[Keyword::TRUE, Keyword::FALSE]) {
12713            Some(Keyword::TRUE) => Ok(true),
12714            Some(Keyword::FALSE) => Ok(false),
12715            _ => self.expected_ref("TRUE or FALSE", self.peek_token_ref()),
12716        }
12717    }
12718
12719    /// Parse a literal unicode normalization clause
12720    pub fn parse_unicode_is_normalized(&mut self, expr: Expr) -> Result<Expr, ParserError> {
12721        let neg = self.parse_keyword(Keyword::NOT);
12722        let normalized_form = self.maybe_parse(|parser| {
12723            match parser.parse_one_of_keywords(&[
12724                Keyword::NFC,
12725                Keyword::NFD,
12726                Keyword::NFKC,
12727                Keyword::NFKD,
12728            ]) {
12729                Some(Keyword::NFC) => Ok(NormalizationForm::NFC),
12730                Some(Keyword::NFD) => Ok(NormalizationForm::NFD),
12731                Some(Keyword::NFKC) => Ok(NormalizationForm::NFKC),
12732                Some(Keyword::NFKD) => Ok(NormalizationForm::NFKD),
12733                _ => parser.expected_ref("unicode normalization form", parser.peek_token_ref()),
12734            }
12735        })?;
12736        if self.parse_keyword(Keyword::NORMALIZED) {
12737            return Ok(Expr::IsNormalized {
12738                expr: Box::new(expr),
12739                form: normalized_form,
12740                negated: neg,
12741            });
12742        }
12743        self.expected_ref("unicode normalization form", self.peek_token_ref())
12744    }
12745
12746    /// Parse parenthesized enum members, used with `ENUM(...)` type definitions.
12747    pub fn parse_enum_values(&mut self) -> Result<Vec<EnumMember>, ParserError> {
12748        self.expect_token(&Token::LParen)?;
12749        let values = self.parse_comma_separated(|parser| {
12750            let name = parser.parse_literal_string()?;
12751            let e = if parser.consume_token(&Token::Eq) {
12752                let value = parser.parse_number()?;
12753                EnumMember::NamedValue(name, value)
12754            } else {
12755                EnumMember::Name(name)
12756            };
12757            Ok(e)
12758        })?;
12759        self.expect_token(&Token::RParen)?;
12760
12761        Ok(values)
12762    }
12763
12764    /// Parse a SQL datatype (in the context of a CREATE TABLE statement for example)
12765    pub fn parse_data_type(&mut self) -> Result<DataType, ParserError> {
12766        let (ty, trailing_bracket) = self.parse_data_type_helper()?;
12767        if trailing_bracket.0 {
12768            return parser_err!(
12769                format!("unmatched > after parsing data type {ty}"),
12770                self.peek_token_ref()
12771            );
12772        }
12773
12774        Ok(ty)
12775    }
12776
12777    fn parse_data_type_helper(
12778        &mut self,
12779    ) -> Result<(DataType, MatchedTrailingBracket), ParserError> {
12780        let dialect = self.dialect;
12781        self.advance_token();
12782        let next_token = self.get_current_token();
12783        let next_token_index = self.get_current_index();
12784
12785        let mut trailing_bracket: MatchedTrailingBracket = false.into();
12786        let mut data = match &next_token.token {
12787            Token::Word(w) => match w.keyword {
12788                Keyword::BOOLEAN => Ok(DataType::Boolean),
12789                Keyword::BOOL => Ok(DataType::Bool),
12790                Keyword::FLOAT => {
12791                    let precision = self.parse_exact_number_optional_precision_scale()?;
12792
12793                    if self.parse_keyword(Keyword::UNSIGNED) {
12794                        Ok(DataType::FloatUnsigned(precision))
12795                    } else {
12796                        Ok(DataType::Float(precision))
12797                    }
12798                }
12799                Keyword::REAL => {
12800                    if self.parse_keyword(Keyword::UNSIGNED) {
12801                        Ok(DataType::RealUnsigned)
12802                    } else {
12803                        Ok(DataType::Real)
12804                    }
12805                }
12806                Keyword::FLOAT4 => Ok(DataType::Float4),
12807                Keyword::FLOAT32 => Ok(DataType::Float32),
12808                Keyword::FLOAT64 => Ok(DataType::Float64),
12809                Keyword::FLOAT8 => Ok(DataType::Float8),
12810                Keyword::DOUBLE => {
12811                    if self.parse_keyword(Keyword::PRECISION) {
12812                        if self.parse_keyword(Keyword::UNSIGNED) {
12813                            Ok(DataType::DoublePrecisionUnsigned)
12814                        } else {
12815                            Ok(DataType::DoublePrecision)
12816                        }
12817                    } else {
12818                        let precision = self.parse_exact_number_optional_precision_scale()?;
12819
12820                        if self.parse_keyword(Keyword::UNSIGNED) {
12821                            Ok(DataType::DoubleUnsigned(precision))
12822                        } else {
12823                            Ok(DataType::Double(precision))
12824                        }
12825                    }
12826                }
12827                Keyword::TINYINT => {
12828                    let optional_precision = self.parse_optional_precision();
12829                    if self.parse_keyword(Keyword::UNSIGNED) {
12830                        Ok(DataType::TinyIntUnsigned(optional_precision?))
12831                    } else {
12832                        if dialect.supports_data_type_signed_suffix() {
12833                            let _ = self.parse_keyword(Keyword::SIGNED);
12834                        }
12835                        Ok(DataType::TinyInt(optional_precision?))
12836                    }
12837                }
12838                Keyword::INT2 => {
12839                    let optional_precision = self.parse_optional_precision();
12840                    if self.parse_keyword(Keyword::UNSIGNED) {
12841                        Ok(DataType::Int2Unsigned(optional_precision?))
12842                    } else {
12843                        Ok(DataType::Int2(optional_precision?))
12844                    }
12845                }
12846                Keyword::SMALLINT => {
12847                    let optional_precision = self.parse_optional_precision();
12848                    if self.parse_keyword(Keyword::UNSIGNED) {
12849                        Ok(DataType::SmallIntUnsigned(optional_precision?))
12850                    } else {
12851                        if dialect.supports_data_type_signed_suffix() {
12852                            let _ = self.parse_keyword(Keyword::SIGNED);
12853                        }
12854                        Ok(DataType::SmallInt(optional_precision?))
12855                    }
12856                }
12857                Keyword::MEDIUMINT => {
12858                    let optional_precision = self.parse_optional_precision();
12859                    if self.parse_keyword(Keyword::UNSIGNED) {
12860                        Ok(DataType::MediumIntUnsigned(optional_precision?))
12861                    } else {
12862                        if dialect.supports_data_type_signed_suffix() {
12863                            let _ = self.parse_keyword(Keyword::SIGNED);
12864                        }
12865                        Ok(DataType::MediumInt(optional_precision?))
12866                    }
12867                }
12868                Keyword::INT => {
12869                    let optional_precision = self.parse_optional_precision();
12870                    if self.parse_keyword(Keyword::UNSIGNED) {
12871                        Ok(DataType::IntUnsigned(optional_precision?))
12872                    } else {
12873                        if dialect.supports_data_type_signed_suffix() {
12874                            let _ = self.parse_keyword(Keyword::SIGNED);
12875                        }
12876                        Ok(DataType::Int(optional_precision?))
12877                    }
12878                }
12879                Keyword::INT4 => {
12880                    let optional_precision = self.parse_optional_precision();
12881                    if self.parse_keyword(Keyword::UNSIGNED) {
12882                        Ok(DataType::Int4Unsigned(optional_precision?))
12883                    } else {
12884                        Ok(DataType::Int4(optional_precision?))
12885                    }
12886                }
12887                Keyword::INT8 => {
12888                    let optional_precision = self.parse_optional_precision();
12889                    if self.parse_keyword(Keyword::UNSIGNED) {
12890                        Ok(DataType::Int8Unsigned(optional_precision?))
12891                    } else {
12892                        Ok(DataType::Int8(optional_precision?))
12893                    }
12894                }
12895                Keyword::INT16 => Ok(DataType::Int16),
12896                Keyword::INT32 => Ok(DataType::Int32),
12897                Keyword::INT64 => Ok(DataType::Int64),
12898                Keyword::INT128 => Ok(DataType::Int128),
12899                Keyword::INT256 => Ok(DataType::Int256),
12900                Keyword::INTEGER => {
12901                    let optional_precision = self.parse_optional_precision();
12902                    if self.parse_keyword(Keyword::UNSIGNED) {
12903                        Ok(DataType::IntegerUnsigned(optional_precision?))
12904                    } else {
12905                        if dialect.supports_data_type_signed_suffix() {
12906                            let _ = self.parse_keyword(Keyword::SIGNED);
12907                        }
12908                        Ok(DataType::Integer(optional_precision?))
12909                    }
12910                }
12911                Keyword::BIGINT => {
12912                    let optional_precision = self.parse_optional_precision();
12913                    if self.parse_keyword(Keyword::UNSIGNED) {
12914                        Ok(DataType::BigIntUnsigned(optional_precision?))
12915                    } else {
12916                        if dialect.supports_data_type_signed_suffix() {
12917                            let _ = self.parse_keyword(Keyword::SIGNED);
12918                        }
12919                        Ok(DataType::BigInt(optional_precision?))
12920                    }
12921                }
12922                Keyword::HUGEINT => Ok(DataType::HugeInt),
12923                Keyword::UBIGINT => Ok(DataType::UBigInt),
12924                Keyword::UHUGEINT => Ok(DataType::UHugeInt),
12925                Keyword::USMALLINT => Ok(DataType::USmallInt),
12926                Keyword::UTINYINT => Ok(DataType::UTinyInt),
12927                Keyword::UINT8 => Ok(DataType::UInt8),
12928                Keyword::UINT16 => Ok(DataType::UInt16),
12929                Keyword::UINT32 => Ok(DataType::UInt32),
12930                Keyword::UINT64 => Ok(DataType::UInt64),
12931                Keyword::UINT128 => Ok(DataType::UInt128),
12932                Keyword::UINT256 => Ok(DataType::UInt256),
12933                Keyword::VARCHAR => Ok(DataType::Varchar(self.parse_optional_character_length()?)),
12934                Keyword::NVARCHAR => {
12935                    Ok(DataType::Nvarchar(self.parse_optional_character_length()?))
12936                }
12937                Keyword::CHARACTER => {
12938                    if self.parse_keyword(Keyword::VARYING) {
12939                        Ok(DataType::CharacterVarying(
12940                            self.parse_optional_character_length()?,
12941                        ))
12942                    } else if self.parse_keywords(&[Keyword::LARGE, Keyword::OBJECT]) {
12943                        Ok(DataType::CharacterLargeObject(
12944                            self.parse_optional_precision()?,
12945                        ))
12946                    } else {
12947                        Ok(DataType::Character(self.parse_optional_character_length()?))
12948                    }
12949                }
12950                Keyword::CHAR => {
12951                    if self.parse_keyword(Keyword::VARYING) {
12952                        Ok(DataType::CharVarying(
12953                            self.parse_optional_character_length()?,
12954                        ))
12955                    } else if self.parse_keywords(&[Keyword::LARGE, Keyword::OBJECT]) {
12956                        Ok(DataType::CharLargeObject(self.parse_optional_precision()?))
12957                    } else {
12958                        Ok(DataType::Char(self.parse_optional_character_length()?))
12959                    }
12960                }
12961                Keyword::CLOB => Ok(DataType::Clob(self.parse_optional_precision()?)),
12962                Keyword::BINARY => Ok(DataType::Binary(self.parse_optional_precision()?)),
12963                Keyword::VARBINARY => Ok(DataType::Varbinary(self.parse_optional_binary_length()?)),
12964                Keyword::BLOB => Ok(DataType::Blob(self.parse_optional_precision()?)),
12965                Keyword::TINYBLOB => Ok(DataType::TinyBlob),
12966                Keyword::MEDIUMBLOB => Ok(DataType::MediumBlob),
12967                Keyword::LONGBLOB => Ok(DataType::LongBlob),
12968                Keyword::LONG if self.dialect.supports_long_type_as_bigint() => {
12969                    Ok(DataType::BigInt(None))
12970                }
12971                Keyword::BYTES => Ok(DataType::Bytes(self.parse_optional_precision()?)),
12972                Keyword::BIT => {
12973                    if self.parse_keyword(Keyword::VARYING) {
12974                        Ok(DataType::BitVarying(self.parse_optional_precision()?))
12975                    } else {
12976                        Ok(DataType::Bit(self.parse_optional_precision()?))
12977                    }
12978                }
12979                Keyword::VARBIT => Ok(DataType::VarBit(self.parse_optional_precision()?)),
12980                Keyword::UUID => Ok(DataType::Uuid),
12981                Keyword::DATE => Ok(DataType::Date),
12982                Keyword::DATE32 => Ok(DataType::Date32),
12983                Keyword::DATETIME => Ok(DataType::Datetime(self.parse_optional_precision()?)),
12984                Keyword::DATETIME64 => {
12985                    self.prev_token();
12986                    let (precision, time_zone) = self.parse_datetime_64()?;
12987                    Ok(DataType::Datetime64(precision, time_zone))
12988                }
12989                Keyword::TIMESTAMP => {
12990                    let precision = self.parse_optional_precision()?;
12991                    let tz = if self.parse_keyword(Keyword::WITH) {
12992                        self.expect_keywords(&[Keyword::TIME, Keyword::ZONE])?;
12993                        TimezoneInfo::WithTimeZone
12994                    } else if self.parse_keyword(Keyword::WITHOUT) {
12995                        self.expect_keywords(&[Keyword::TIME, Keyword::ZONE])?;
12996                        TimezoneInfo::WithoutTimeZone
12997                    } else {
12998                        TimezoneInfo::None
12999                    };
13000                    Ok(DataType::Timestamp(precision, tz))
13001                }
13002                Keyword::TIMESTAMPTZ => Ok(DataType::Timestamp(
13003                    self.parse_optional_precision()?,
13004                    TimezoneInfo::Tz,
13005                )),
13006                Keyword::TIMESTAMP_NTZ => {
13007                    Ok(DataType::TimestampNtz(self.parse_optional_precision()?))
13008                }
13009                Keyword::TIME => {
13010                    let precision = self.parse_optional_precision()?;
13011                    let tz = if self.parse_keyword(Keyword::WITH) {
13012                        self.expect_keywords(&[Keyword::TIME, Keyword::ZONE])?;
13013                        TimezoneInfo::WithTimeZone
13014                    } else if self.parse_keyword(Keyword::WITHOUT) {
13015                        self.expect_keywords(&[Keyword::TIME, Keyword::ZONE])?;
13016                        TimezoneInfo::WithoutTimeZone
13017                    } else {
13018                        TimezoneInfo::None
13019                    };
13020                    Ok(DataType::Time(precision, tz))
13021                }
13022                Keyword::TIMETZ => Ok(DataType::Time(
13023                    self.parse_optional_precision()?,
13024                    TimezoneInfo::Tz,
13025                )),
13026                Keyword::INTERVAL => {
13027                    if self.dialect.supports_interval_options() {
13028                        let fields = self.maybe_parse_optional_interval_fields()?;
13029                        let precision = self.parse_optional_precision()?;
13030                        Ok(DataType::Interval { fields, precision })
13031                    } else {
13032                        Ok(DataType::Interval {
13033                            fields: None,
13034                            precision: None,
13035                        })
13036                    }
13037                }
13038                Keyword::JSON => Ok(DataType::JSON),
13039                Keyword::JSONB => Ok(DataType::JSONB),
13040                Keyword::REGCLASS => Ok(DataType::Regclass),
13041                Keyword::STRING => Ok(DataType::String(self.parse_optional_precision()?)),
13042                Keyword::FIXEDSTRING => {
13043                    self.expect_token(&Token::LParen)?;
13044                    let character_length = self.parse_literal_uint()?;
13045                    self.expect_token(&Token::RParen)?;
13046                    Ok(DataType::FixedString(character_length))
13047                }
13048                Keyword::TEXT => {
13049                    if let Some(modifiers) = self.parse_optional_type_modifiers()? {
13050                        Ok(DataType::Custom(
13051                            ObjectName::from(vec![Ident::new("TEXT")]),
13052                            modifiers,
13053                        ))
13054                    } else {
13055                        Ok(DataType::Text)
13056                    }
13057                }
13058                Keyword::TINYTEXT => Ok(DataType::TinyText),
13059                Keyword::MEDIUMTEXT => Ok(DataType::MediumText),
13060                Keyword::LONGTEXT => Ok(DataType::LongText),
13061                Keyword::BYTEA => Ok(DataType::Bytea),
13062                Keyword::NUMERIC => Ok(DataType::Numeric(
13063                    self.parse_exact_number_optional_precision_scale()?,
13064                )),
13065                Keyword::DECIMAL => {
13066                    let precision = self.parse_exact_number_optional_precision_scale()?;
13067
13068                    if self.parse_keyword(Keyword::UNSIGNED) {
13069                        Ok(DataType::DecimalUnsigned(precision))
13070                    } else {
13071                        Ok(DataType::Decimal(precision))
13072                    }
13073                }
13074                Keyword::DEC => {
13075                    let precision = self.parse_exact_number_optional_precision_scale()?;
13076
13077                    if self.parse_keyword(Keyword::UNSIGNED) {
13078                        Ok(DataType::DecUnsigned(precision))
13079                    } else {
13080                        Ok(DataType::Dec(precision))
13081                    }
13082                }
13083                Keyword::BIGNUMERIC => Ok(DataType::BigNumeric(
13084                    self.parse_exact_number_optional_precision_scale()?,
13085                )),
13086                Keyword::BIGDECIMAL => Ok(DataType::BigDecimal(
13087                    self.parse_exact_number_optional_precision_scale()?,
13088                )),
13089                Keyword::ENUM => Ok(DataType::Enum(self.parse_enum_values()?, None)),
13090                Keyword::ENUM8 => Ok(DataType::Enum(self.parse_enum_values()?, Some(8))),
13091                Keyword::ENUM16 => Ok(DataType::Enum(self.parse_enum_values()?, Some(16))),
13092                Keyword::SET => Ok(DataType::Set(self.parse_string_values()?)),
13093                Keyword::ARRAY => {
13094                    if self.dialect.supports_array_typedef_without_element_type() {
13095                        Ok(DataType::Array(ArrayElemTypeDef::None))
13096                    } else if dialect_of!(self is ClickHouseDialect) {
13097                        Ok(self.parse_sub_type(|internal_type| {
13098                            DataType::Array(ArrayElemTypeDef::Parenthesis(internal_type))
13099                        })?)
13100                    } else {
13101                        self.expect_token(&Token::Lt)?;
13102                        let (inside_type, _trailing_bracket) = self.parse_data_type_helper()?;
13103                        trailing_bracket = self.expect_closing_angle_bracket(_trailing_bracket)?;
13104                        Ok(DataType::Array(ArrayElemTypeDef::AngleBracket(Box::new(
13105                            inside_type,
13106                        ))))
13107                    }
13108                }
13109                Keyword::STRUCT if dialect_is!(dialect is DuckDbDialect) => {
13110                    self.prev_token();
13111                    let field_defs = self.parse_duckdb_struct_type_def()?;
13112                    Ok(DataType::Struct(field_defs, StructBracketKind::Parentheses))
13113                }
13114                Keyword::STRUCT if self.dialect.supports_struct_literal() => {
13115                    self.prev_token();
13116                    let (field_defs, _trailing_bracket) =
13117                        self.parse_struct_type_def(Self::parse_struct_field_def)?;
13118                    trailing_bracket = _trailing_bracket;
13119                    Ok(DataType::Struct(
13120                        field_defs,
13121                        StructBracketKind::AngleBrackets,
13122                    ))
13123                }
13124                Keyword::UNION if dialect_is!(dialect is DuckDbDialect | GenericDialect) => {
13125                    self.prev_token();
13126                    let fields = self.parse_union_type_def()?;
13127                    Ok(DataType::Union(fields))
13128                }
13129                Keyword::NULLABLE if dialect_is!(dialect is ClickHouseDialect | GenericDialect) => {
13130                    Ok(self.parse_sub_type(DataType::Nullable)?)
13131                }
13132                Keyword::LOWCARDINALITY if dialect_is!(dialect is ClickHouseDialect | GenericDialect) => {
13133                    Ok(self.parse_sub_type(DataType::LowCardinality)?)
13134                }
13135                Keyword::MAP if self.dialect.supports_map_literal_with_angle_brackets() => {
13136                    self.expect_token(&Token::Lt)?;
13137                    let key_data_type = self.parse_data_type()?;
13138                    self.expect_token(&Token::Comma)?;
13139                    let (value_data_type, _trailing_bracket) = self.parse_data_type_helper()?;
13140                    trailing_bracket = self.expect_closing_angle_bracket(_trailing_bracket)?;
13141                    Ok(DataType::Map(
13142                        Box::new(key_data_type),
13143                        Box::new(value_data_type),
13144                        MapBracketKind::AngleBrackets,
13145                    ))
13146                }
13147                Keyword::MAP if dialect_is!(dialect is ClickHouseDialect | GenericDialect) => {
13148                    self.prev_token();
13149                    let (key_data_type, value_data_type) = self.parse_click_house_map_def()?;
13150                    Ok(DataType::Map(
13151                        Box::new(key_data_type),
13152                        Box::new(value_data_type),
13153                        MapBracketKind::Parentheses,
13154                    ))
13155                }
13156                Keyword::NESTED if dialect_is!(dialect is ClickHouseDialect | GenericDialect) => {
13157                    self.expect_token(&Token::LParen)?;
13158                    let field_defs = self.parse_comma_separated(Parser::parse_column_def)?;
13159                    self.expect_token(&Token::RParen)?;
13160                    Ok(DataType::Nested(field_defs))
13161                }
13162                Keyword::TUPLE if dialect_is!(dialect is ClickHouseDialect | GenericDialect) => {
13163                    self.prev_token();
13164                    let field_defs = self.parse_click_house_tuple_def()?;
13165                    Ok(DataType::Tuple(field_defs))
13166                }
13167                Keyword::TRIGGER => Ok(DataType::Trigger),
13168                Keyword::ANY if self.peek_keyword(Keyword::TYPE) => {
13169                    let _ = self.parse_keyword(Keyword::TYPE);
13170                    Ok(DataType::AnyType)
13171                }
13172                Keyword::TABLE => {
13173                    // an LParen after the TABLE keyword indicates that table columns are being defined
13174                    // whereas no LParen indicates an anonymous table expression will be returned
13175                    if self.peek_token_ref().token == Token::LParen {
13176                        let columns = self.parse_returns_table_columns()?;
13177                        Ok(DataType::Table(Some(columns)))
13178                    } else {
13179                        Ok(DataType::Table(None))
13180                    }
13181                }
13182                Keyword::SIGNED => {
13183                    if self.parse_keyword(Keyword::INTEGER) {
13184                        Ok(DataType::SignedInteger)
13185                    } else {
13186                        Ok(DataType::Signed)
13187                    }
13188                }
13189                Keyword::UNSIGNED => {
13190                    if self.parse_keyword(Keyword::INTEGER) {
13191                        Ok(DataType::UnsignedInteger)
13192                    } else {
13193                        Ok(DataType::Unsigned)
13194                    }
13195                }
13196                Keyword::TSVECTOR if dialect_is!(dialect is PostgreSqlDialect | GenericDialect) => {
13197                    Ok(DataType::TsVector)
13198                }
13199                Keyword::TSQUERY if dialect_is!(dialect is PostgreSqlDialect | GenericDialect) => {
13200                    Ok(DataType::TsQuery)
13201                }
13202                _ => {
13203                    self.prev_token();
13204                    let type_name = self.parse_object_name(false)?;
13205                    if let Some(modifiers) = self.parse_optional_type_modifiers()? {
13206                        Ok(DataType::Custom(type_name, modifiers))
13207                    } else {
13208                        Ok(DataType::Custom(type_name, vec![]))
13209                    }
13210                }
13211            },
13212            _ => self.expected_at("a data type name", next_token_index),
13213        }?;
13214
13215        if self.dialect.supports_array_typedef_with_brackets() {
13216            while self.consume_token(&Token::LBracket) {
13217                // Parse optional array data type size
13218                let size = self.maybe_parse(|p| p.parse_literal_uint())?;
13219                self.expect_token(&Token::RBracket)?;
13220                data = DataType::Array(ArrayElemTypeDef::SquareBracket(Box::new(data), size))
13221            }
13222        }
13223        Ok((data, trailing_bracket))
13224    }
13225
13226    fn parse_returns_table_column(&mut self) -> Result<ColumnDef, ParserError> {
13227        self.parse_column_def()
13228    }
13229
13230    fn parse_returns_table_columns(&mut self) -> Result<Vec<ColumnDef>, ParserError> {
13231        self.expect_token(&Token::LParen)?;
13232        let columns = self.parse_comma_separated(Parser::parse_returns_table_column)?;
13233        self.expect_token(&Token::RParen)?;
13234        Ok(columns)
13235    }
13236
13237    /// Parse a parenthesized, comma-separated list of single-quoted strings.
13238    pub fn parse_string_values(&mut self) -> Result<Vec<String>, ParserError> {
13239        self.expect_token(&Token::LParen)?;
13240        let mut values = Vec::new();
13241        loop {
13242            let next_token = self.next_token();
13243            match next_token.token {
13244                Token::SingleQuotedString(value) => values.push(value),
13245                _ => self.expected("a string", next_token)?,
13246            }
13247            let next_token = self.next_token();
13248            match next_token.token {
13249                Token::Comma => (),
13250                Token::RParen => break,
13251                _ => self.expected(", or }", next_token)?,
13252            }
13253        }
13254        Ok(values)
13255    }
13256
13257    /// Strictly parse `identifier AS identifier`
13258    pub fn parse_identifier_with_alias(&mut self) -> Result<IdentWithAlias, ParserError> {
13259        let ident = self.parse_identifier()?;
13260        self.expect_keyword_is(Keyword::AS)?;
13261        let alias = self.parse_identifier()?;
13262        Ok(IdentWithAlias { ident, alias })
13263    }
13264
13265    /// Parse `identifier [AS] identifier` where the AS keyword is optional
13266    fn parse_identifier_with_optional_alias(&mut self) -> Result<IdentWithAlias, ParserError> {
13267        let ident = self.parse_identifier()?;
13268        let _after_as = self.parse_keyword(Keyword::AS);
13269        let alias = self.parse_identifier()?;
13270        Ok(IdentWithAlias { ident, alias })
13271    }
13272
13273    /// Parse comma-separated list of parenthesized queries for pipe operators
13274    fn parse_pipe_operator_queries(&mut self) -> Result<Vec<Query>, ParserError> {
13275        self.parse_comma_separated(|parser| {
13276            parser.expect_token(&Token::LParen)?;
13277            let query = parser.parse_query()?;
13278            parser.expect_token(&Token::RParen)?;
13279            Ok(*query)
13280        })
13281    }
13282
13283    /// Parse set quantifier for pipe operators that require DISTINCT. E.g. INTERSECT and EXCEPT
13284    fn parse_distinct_required_set_quantifier(
13285        &mut self,
13286        operator_name: &str,
13287    ) -> Result<SetQuantifier, ParserError> {
13288        let quantifier = self.parse_set_quantifier(&Some(SetOperator::Intersect));
13289        match quantifier {
13290            SetQuantifier::Distinct | SetQuantifier::DistinctByName => Ok(quantifier),
13291            _ => Err(ParserError::ParserError(format!(
13292                "{operator_name} pipe operator requires DISTINCT modifier",
13293            ))),
13294        }
13295    }
13296
13297    /// Parse optional identifier alias (with or without AS keyword)
13298    fn parse_identifier_optional_alias(&mut self) -> Result<Option<Ident>, ParserError> {
13299        if self.parse_keyword(Keyword::AS) {
13300            Ok(Some(self.parse_identifier()?))
13301        } else {
13302            // Check if the next token is an identifier (implicit alias)
13303            self.maybe_parse(|parser| parser.parse_identifier())
13304        }
13305    }
13306
13307    /// Optionally parses an alias for a select list item
13308    fn maybe_parse_select_item_alias(&mut self) -> Result<Option<Ident>, ParserError> {
13309        fn validator(explicit: bool, kw: &Keyword, parser: &mut Parser) -> bool {
13310            parser.dialect.is_select_item_alias(explicit, kw, parser)
13311        }
13312        self.parse_optional_alias_inner(None, validator)
13313    }
13314
13315    /// Optionally parses an alias for a table like in `... FROM generate_series(1, 10) AS t (col)`.
13316    /// In this case, the alias is allowed to optionally name the columns in the table, in
13317    /// addition to the table itself.
13318    pub fn maybe_parse_table_alias(&mut self) -> Result<Option<TableAlias>, ParserError> {
13319        fn validator(explicit: bool, kw: &Keyword, parser: &mut Parser) -> bool {
13320            parser.dialect.is_table_factor_alias(explicit, kw, parser)
13321        }
13322        let explicit = self.peek_keyword(Keyword::AS);
13323        match self.parse_optional_alias_inner(None, validator)? {
13324            Some(name) => {
13325                let columns = self.parse_table_alias_column_defs()?;
13326                let at = if self.dialect.supports_partiql() && self.parse_keyword(Keyword::AT) {
13327                    Some(self.parse_identifier()?)
13328                } else {
13329                    None
13330                };
13331                Ok(Some(TableAlias {
13332                    explicit,
13333                    name,
13334                    columns,
13335                    at,
13336                }))
13337            }
13338            None => Ok(None),
13339        }
13340    }
13341
13342    fn parse_table_index_hints(&mut self) -> Result<Vec<TableIndexHints>, ParserError> {
13343        let mut hints = vec![];
13344        while let Some(hint_type) =
13345            self.parse_one_of_keywords(&[Keyword::USE, Keyword::IGNORE, Keyword::FORCE])
13346        {
13347            let hint_type = match hint_type {
13348                Keyword::USE => TableIndexHintType::Use,
13349                Keyword::IGNORE => TableIndexHintType::Ignore,
13350                Keyword::FORCE => TableIndexHintType::Force,
13351                _ => {
13352                    return self.expected_ref(
13353                        "expected to match USE/IGNORE/FORCE keyword",
13354                        self.peek_token_ref(),
13355                    )
13356                }
13357            };
13358            let index_type = match self.parse_one_of_keywords(&[Keyword::INDEX, Keyword::KEY]) {
13359                Some(Keyword::INDEX) => TableIndexType::Index,
13360                Some(Keyword::KEY) => TableIndexType::Key,
13361                _ => {
13362                    return self
13363                        .expected_ref("expected to match INDEX/KEY keyword", self.peek_token_ref())
13364                }
13365            };
13366            let for_clause = if self.parse_keyword(Keyword::FOR) {
13367                let clause = if self.parse_keyword(Keyword::JOIN) {
13368                    TableIndexHintForClause::Join
13369                } else if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
13370                    TableIndexHintForClause::OrderBy
13371                } else if self.parse_keywords(&[Keyword::GROUP, Keyword::BY]) {
13372                    TableIndexHintForClause::GroupBy
13373                } else {
13374                    return self.expected_ref(
13375                        "expected to match FOR/ORDER BY/GROUP BY table hint in for clause",
13376                        self.peek_token_ref(),
13377                    );
13378                };
13379                Some(clause)
13380            } else {
13381                None
13382            };
13383
13384            self.expect_token(&Token::LParen)?;
13385            let index_names = if self.peek_token_ref().token != Token::RParen {
13386                self.parse_comma_separated(Parser::parse_identifier)?
13387            } else {
13388                vec![]
13389            };
13390            self.expect_token(&Token::RParen)?;
13391            hints.push(TableIndexHints {
13392                hint_type,
13393                index_type,
13394                for_clause,
13395                index_names,
13396            });
13397        }
13398        Ok(hints)
13399    }
13400
13401    /// Wrapper for parse_optional_alias_inner, left for backwards-compatibility
13402    /// but new flows should use the context-specific methods such as `maybe_parse_select_item_alias`
13403    /// and `maybe_parse_table_alias`.
13404    pub fn parse_optional_alias(
13405        &mut self,
13406        reserved_kwds: &[Keyword],
13407    ) -> Result<Option<Ident>, ParserError> {
13408        fn validator(_explicit: bool, _kw: &Keyword, _parser: &mut Parser) -> bool {
13409            false
13410        }
13411        self.parse_optional_alias_inner(Some(reserved_kwds), validator)
13412    }
13413
13414    /// Parses an optional alias after a SQL element such as a select list item
13415    /// or a table name.
13416    ///
13417    /// This method accepts an optional list of reserved keywords or a function
13418    /// to call to validate if a keyword should be parsed as an alias, to allow
13419    /// callers to customize the parsing logic based on their context.
13420    fn parse_optional_alias_inner<F>(
13421        &mut self,
13422        reserved_kwds: Option<&[Keyword]>,
13423        validator: F,
13424    ) -> Result<Option<Ident>, ParserError>
13425    where
13426        F: Fn(bool, &Keyword, &mut Parser) -> bool,
13427    {
13428        let after_as = self.parse_keyword(Keyword::AS);
13429
13430        let next_token = self.next_token();
13431        match next_token.token {
13432            // Accepts a keyword as an alias if the AS keyword explicitly indicate an alias or if the
13433            // caller provided a list of reserved keywords and the keyword is not on that list.
13434            Token::Word(w)
13435                if reserved_kwds.is_some()
13436                    && (after_as || reserved_kwds.is_some_and(|x| !x.contains(&w.keyword))) =>
13437            {
13438                Ok(Some(w.into_ident(next_token.span)))
13439            }
13440            // Accepts a keyword as alias based on the caller's context, such as to what SQL element
13441            // this word is a potential alias of using the validator call-back. This allows for
13442            // dialect-specific logic.
13443            Token::Word(w) if validator(after_as, &w.keyword, self) => {
13444                Ok(Some(w.into_ident(next_token.span)))
13445            }
13446            // For backwards-compatibility, we accept quoted strings as aliases regardless of the context.
13447            Token::SingleQuotedString(s) => Ok(Some(Ident::with_quote('\'', s))),
13448            Token::DoubleQuotedString(s) => Ok(Some(Ident::with_quote('\"', s))),
13449            _ => {
13450                if after_as {
13451                    return self.expected("an identifier after AS", next_token);
13452                }
13453                self.prev_token();
13454                Ok(None) // no alias found
13455            }
13456        }
13457    }
13458
13459    /// Parse an optional `GROUP BY` clause, returning `Some(GroupByExpr)` when present.
13460    pub fn parse_optional_group_by(&mut self) -> Result<Option<GroupByExpr>, ParserError> {
13461        if self.parse_keywords(&[Keyword::GROUP, Keyword::BY]) {
13462            let expressions = if self.parse_keyword(Keyword::ALL) {
13463                None
13464            } else {
13465                Some(self.parse_comma_separated(Parser::parse_group_by_expr)?)
13466            };
13467
13468            let mut modifiers = vec![];
13469            if self.dialect.supports_group_by_with_modifier() {
13470                loop {
13471                    if !self.parse_keyword(Keyword::WITH) {
13472                        break;
13473                    }
13474                    let keyword = self.expect_one_of_keywords(&[
13475                        Keyword::ROLLUP,
13476                        Keyword::CUBE,
13477                        Keyword::TOTALS,
13478                    ])?;
13479                    modifiers.push(match keyword {
13480                        Keyword::ROLLUP => GroupByWithModifier::Rollup,
13481                        Keyword::CUBE => GroupByWithModifier::Cube,
13482                        Keyword::TOTALS => GroupByWithModifier::Totals,
13483                        _ => {
13484                            return parser_err!(
13485                                "BUG: expected to match GroupBy modifier keyword",
13486                                self.peek_token_ref().span.start
13487                            )
13488                        }
13489                    });
13490                }
13491            }
13492            if self.parse_keywords(&[Keyword::GROUPING, Keyword::SETS]) {
13493                self.expect_token(&Token::LParen)?;
13494                let result = self.parse_comma_separated(|p| {
13495                    if p.peek_token_ref().token == Token::LParen {
13496                        p.parse_tuple(true, true)
13497                    } else {
13498                        Ok(vec![p.parse_expr()?])
13499                    }
13500                })?;
13501                self.expect_token(&Token::RParen)?;
13502                modifiers.push(GroupByWithModifier::GroupingSets(Expr::GroupingSets(
13503                    result,
13504                )));
13505            };
13506            let group_by = match expressions {
13507                None => GroupByExpr::All(modifiers),
13508                Some(exprs) => GroupByExpr::Expressions(exprs, modifiers),
13509            };
13510            Ok(Some(group_by))
13511        } else {
13512            Ok(None)
13513        }
13514    }
13515
13516    /// Parse an optional `ORDER BY` clause, returning `Some(OrderBy)` when present.
13517    pub fn parse_optional_order_by(&mut self) -> Result<Option<OrderBy>, ParserError> {
13518        if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
13519            let order_by =
13520                if self.dialect.supports_order_by_all() && self.parse_keyword(Keyword::ALL) {
13521                    let order_by_options = self.parse_order_by_options()?;
13522                    OrderBy {
13523                        kind: OrderByKind::All(order_by_options),
13524                        interpolate: None,
13525                    }
13526                } else {
13527                    let exprs = self.parse_comma_separated(Parser::parse_order_by_expr)?;
13528                    let interpolate = if self.dialect.supports_interpolate() {
13529                        self.parse_interpolations()?
13530                    } else {
13531                        None
13532                    };
13533                    OrderBy {
13534                        kind: OrderByKind::Expressions(exprs),
13535                        interpolate,
13536                    }
13537                };
13538            Ok(Some(order_by))
13539        } else {
13540            Ok(None)
13541        }
13542    }
13543
13544    fn parse_optional_limit_clause(&mut self) -> Result<Option<LimitClause>, ParserError> {
13545        let mut offset = if self.parse_keyword(Keyword::OFFSET) {
13546            Some(self.parse_offset()?)
13547        } else {
13548            None
13549        };
13550
13551        let (limit, limit_by) = if self.parse_keyword(Keyword::LIMIT) {
13552            let expr = self.parse_limit()?;
13553
13554            if self.dialect.supports_limit_comma()
13555                && offset.is_none()
13556                && expr.is_some() // ALL not supported with comma
13557                && self.consume_token(&Token::Comma)
13558            {
13559                let offset = expr.ok_or_else(|| {
13560                    ParserError::ParserError(
13561                        "Missing offset for LIMIT <offset>, <limit>".to_string(),
13562                    )
13563                })?;
13564                return Ok(Some(LimitClause::OffsetCommaLimit {
13565                    offset,
13566                    limit: self.parse_expr()?,
13567                }));
13568            }
13569
13570            let limit_by = if self.dialect.supports_limit_by() && self.parse_keyword(Keyword::BY) {
13571                Some(self.parse_comma_separated(Parser::parse_expr)?)
13572            } else {
13573                None
13574            };
13575
13576            (Some(expr), limit_by)
13577        } else {
13578            (None, None)
13579        };
13580
13581        if offset.is_none() && limit.is_some() && self.parse_keyword(Keyword::OFFSET) {
13582            offset = Some(self.parse_offset()?);
13583        }
13584
13585        if offset.is_some() || (limit.is_some() && limit != Some(None)) || limit_by.is_some() {
13586            Ok(Some(LimitClause::LimitOffset {
13587                limit: limit.unwrap_or_default(),
13588                offset,
13589                limit_by: limit_by.unwrap_or_default(),
13590            }))
13591        } else {
13592            Ok(None)
13593        }
13594    }
13595
13596    /// Parse a table object for insertion
13597    /// e.g. `some_database.some_table` or `FUNCTION some_table_func(...)`
13598    pub fn parse_table_object(&mut self) -> Result<TableObject, ParserError> {
13599        if self.dialect.supports_insert_table_function() && self.parse_keyword(Keyword::FUNCTION) {
13600            let fn_name = self.parse_object_name(false)?;
13601            self.parse_function_call(fn_name)
13602                .map(TableObject::TableFunction)
13603        } else if self.dialect.supports_insert_table_query() && self.peek_subquery_or_cte_start() {
13604            self.parse_parenthesized(|p| p.parse_query())
13605                .map(TableObject::TableQuery)
13606        } else {
13607            self.parse_object_name(false).map(TableObject::TableName)
13608        }
13609    }
13610
13611    /// Parse a possibly qualified, possibly quoted identifier, e.g.
13612    /// `foo` or `myschema."table"
13613    ///
13614    /// The `in_table_clause` parameter indicates whether the object name is a table in a FROM, JOIN,
13615    /// or similar table clause. Currently, this is used only to support unquoted hyphenated identifiers
13616    /// in this context on BigQuery.
13617    pub fn parse_object_name(&mut self, in_table_clause: bool) -> Result<ObjectName, ParserError> {
13618        self.parse_object_name_inner(in_table_clause, false)
13619    }
13620
13621    /// Parse a possibly qualified, possibly quoted identifier, e.g.
13622    /// `foo` or `myschema."table"
13623    ///
13624    /// The `in_table_clause` parameter indicates whether the object name is a table in a FROM, JOIN,
13625    /// or similar table clause. Currently, this is used only to support unquoted hyphenated identifiers
13626    /// in this context on BigQuery.
13627    ///
13628    /// The `allow_wildcards` parameter indicates whether to allow for wildcards in the object name
13629    /// e.g. *, *.*, `foo`.*, or "foo"."bar"
13630    fn parse_object_name_inner(
13631        &mut self,
13632        in_table_clause: bool,
13633        allow_wildcards: bool,
13634    ) -> Result<ObjectName, ParserError> {
13635        let mut parts = vec![];
13636        if dialect_of!(self is BigQueryDialect) && in_table_clause {
13637            loop {
13638                let (ident, end_with_period) = self.parse_unquoted_hyphenated_identifier()?;
13639                parts.push(ObjectNamePart::Identifier(ident));
13640                if !self.consume_token(&Token::Period) && !end_with_period {
13641                    break;
13642                }
13643            }
13644        } else {
13645            loop {
13646                if allow_wildcards && self.peek_token_ref().token == Token::Mul {
13647                    let span = self.next_token().span;
13648                    parts.push(ObjectNamePart::Identifier(Ident {
13649                        value: Token::Mul.to_string(),
13650                        quote_style: None,
13651                        span,
13652                    }));
13653                } else if dialect_of!(self is BigQueryDialect) && in_table_clause {
13654                    let (ident, end_with_period) = self.parse_unquoted_hyphenated_identifier()?;
13655                    parts.push(ObjectNamePart::Identifier(ident));
13656                    if !self.consume_token(&Token::Period) && !end_with_period {
13657                        break;
13658                    }
13659                } else if self.dialect.supports_object_name_double_dot_notation()
13660                    && parts.len() == 1
13661                    && matches!(self.peek_token_ref().token, Token::Period)
13662                {
13663                    // Empty string here means default schema
13664                    parts.push(ObjectNamePart::Identifier(Ident::new("")));
13665                } else {
13666                    let ident = self.parse_identifier()?;
13667                    let part = if self
13668                        .dialect
13669                        .is_identifier_generating_function_name(&ident, &parts)
13670                    {
13671                        self.expect_token(&Token::LParen)?;
13672                        let args: Vec<FunctionArg> =
13673                            self.parse_comma_separated0(Self::parse_function_args, Token::RParen)?;
13674                        self.expect_token(&Token::RParen)?;
13675                        ObjectNamePart::Function(ObjectNamePartFunction { name: ident, args })
13676                    } else {
13677                        ObjectNamePart::Identifier(ident)
13678                    };
13679                    parts.push(part);
13680                }
13681
13682                if !self.consume_token(&Token::Period) {
13683                    break;
13684                }
13685            }
13686        }
13687
13688        // BigQuery accepts any number of quoted identifiers of a table name.
13689        // https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#quoted_identifiers
13690        if dialect_of!(self is BigQueryDialect)
13691            && parts.iter().any(|part| {
13692                part.as_ident()
13693                    .is_some_and(|ident| ident.value.contains('.'))
13694            })
13695        {
13696            parts = parts
13697                .into_iter()
13698                .flat_map(|part| match part.as_ident() {
13699                    Some(ident) => ident
13700                        .value
13701                        .split('.')
13702                        .map(|value| {
13703                            ObjectNamePart::Identifier(Ident {
13704                                value: value.into(),
13705                                quote_style: ident.quote_style,
13706                                span: ident.span,
13707                            })
13708                        })
13709                        .collect::<Vec<_>>(),
13710                    None => vec![part],
13711                })
13712                .collect()
13713        }
13714
13715        Ok(ObjectName(parts))
13716    }
13717
13718    /// Parse identifiers
13719    pub fn parse_identifiers(&mut self) -> Result<Vec<Ident>, ParserError> {
13720        let mut idents = vec![];
13721        loop {
13722            let token = self.peek_token_ref();
13723            match &token.token {
13724                Token::Word(w) => {
13725                    idents.push(w.to_ident(token.span));
13726                }
13727                Token::EOF | Token::Eq | Token::SemiColon | Token::VerticalBarRightAngleBracket => {
13728                    break
13729                }
13730                _ => {}
13731            }
13732            self.advance_token();
13733        }
13734        Ok(idents)
13735    }
13736
13737    /// Parse identifiers of form ident1[.identN]*
13738    ///
13739    /// Similar in functionality to [parse_identifiers], with difference
13740    /// being this function is much more strict about parsing a valid multipart identifier, not
13741    /// allowing extraneous tokens to be parsed, otherwise it fails.
13742    ///
13743    /// For example:
13744    ///
13745    /// ```rust
13746    /// use sqlparser::ast::Ident;
13747    /// use sqlparser::dialect::GenericDialect;
13748    /// use sqlparser::parser::Parser;
13749    ///
13750    /// let dialect = GenericDialect {};
13751    /// let expected = vec![Ident::new("one"), Ident::new("two")];
13752    ///
13753    /// // expected usage
13754    /// let sql = "one.two";
13755    /// let mut parser = Parser::new(&dialect).try_with_sql(sql).unwrap();
13756    /// let actual = parser.parse_multipart_identifier().unwrap();
13757    /// assert_eq!(&actual, &expected);
13758    ///
13759    /// // parse_identifiers is more loose on what it allows, parsing successfully
13760    /// let sql = "one + two";
13761    /// let mut parser = Parser::new(&dialect).try_with_sql(sql).unwrap();
13762    /// let actual = parser.parse_identifiers().unwrap();
13763    /// assert_eq!(&actual, &expected);
13764    ///
13765    /// // expected to strictly fail due to + separator
13766    /// let sql = "one + two";
13767    /// let mut parser = Parser::new(&dialect).try_with_sql(sql).unwrap();
13768    /// let actual = parser.parse_multipart_identifier().unwrap_err();
13769    /// assert_eq!(
13770    ///     actual.to_string(),
13771    ///     "sql parser error: Unexpected token in identifier: +"
13772    /// );
13773    /// ```
13774    ///
13775    /// [parse_identifiers]: Parser::parse_identifiers
13776    pub fn parse_multipart_identifier(&mut self) -> Result<Vec<Ident>, ParserError> {
13777        let mut idents = vec![];
13778
13779        // expecting at least one word for identifier
13780        let next_token = self.next_token();
13781        match next_token.token {
13782            Token::Word(w) => idents.push(w.into_ident(next_token.span)),
13783            Token::EOF => {
13784                return Err(ParserError::ParserError(
13785                    "Empty input when parsing identifier".to_string(),
13786                ))?
13787            }
13788            token => {
13789                return Err(ParserError::ParserError(format!(
13790                    "Unexpected token in identifier: {token}"
13791                )))?
13792            }
13793        };
13794
13795        // parse optional next parts if exist
13796        loop {
13797            match self.next_token().token {
13798                // ensure that optional period is succeeded by another identifier
13799                Token::Period => {
13800                    let next_token = self.next_token();
13801                    match next_token.token {
13802                        Token::Word(w) => idents.push(w.into_ident(next_token.span)),
13803                        Token::EOF => {
13804                            return Err(ParserError::ParserError(
13805                                "Trailing period in identifier".to_string(),
13806                            ))?
13807                        }
13808                        token => {
13809                            return Err(ParserError::ParserError(format!(
13810                                "Unexpected token following period in identifier: {token}"
13811                            )))?
13812                        }
13813                    }
13814                }
13815                Token::EOF => break,
13816                token => {
13817                    return Err(ParserError::ParserError(format!(
13818                        "Unexpected token in identifier: {token}"
13819                    )))?;
13820                }
13821            }
13822        }
13823
13824        Ok(idents)
13825    }
13826
13827    /// Parse a simple one-word identifier (possibly quoted, possibly a keyword)
13828    pub fn parse_identifier(&mut self) -> Result<Ident, ParserError> {
13829        let next_token = self.next_token();
13830        match next_token.token {
13831            Token::Word(w) => Ok(w.into_ident(next_token.span)),
13832            Token::SingleQuotedString(s) => Ok(Ident::with_quote('\'', s)),
13833            Token::DoubleQuotedString(s) => Ok(Ident::with_quote('\"', s)),
13834            _ => self.expected("identifier", next_token),
13835        }
13836    }
13837
13838    /// On BigQuery, hyphens are permitted in unquoted identifiers inside of a FROM or
13839    /// TABLE clause.
13840    ///
13841    /// The first segment must be an ordinary unquoted identifier, e.g. it must not start
13842    /// with a digit. Subsequent segments are either must either be valid identifiers or
13843    /// integers, e.g. foo-123 is allowed, but foo-123a is not.
13844    ///
13845    /// [BigQuery-lexical](https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical)
13846    ///
13847    /// Return a tuple of the identifier and a boolean indicating it ends with a period.
13848    fn parse_unquoted_hyphenated_identifier(&mut self) -> Result<(Ident, bool), ParserError> {
13849        match self.peek_token().token {
13850            Token::Word(w) => {
13851                let quote_style_is_none = w.quote_style.is_none();
13852                let mut requires_whitespace = false;
13853                let mut ident = w.into_ident(self.next_token().span);
13854                if quote_style_is_none {
13855                    while matches!(self.peek_token_no_skip().token, Token::Minus) {
13856                        self.next_token();
13857                        ident.value.push('-');
13858
13859                        let token = self
13860                            .next_token_no_skip()
13861                            .cloned()
13862                            .unwrap_or(TokenWithSpan::wrap(Token::EOF));
13863                        requires_whitespace = match token.token {
13864                            Token::Word(next_word) if next_word.quote_style.is_none() => {
13865                                ident.value.push_str(&next_word.value);
13866                                false
13867                            }
13868                            Token::Number(s, false) => {
13869                                // A number token can represent a decimal value ending with a period, e.g., `Number('123.')`.
13870                                // However, for an [ObjectName], it is part of a hyphenated identifier, e.g., `foo-123.bar`.
13871                                //
13872                                // If a number token is followed by a period, it is part of an [ObjectName].
13873                                // Return the identifier with `true` if the number token is followed by a period, indicating that
13874                                // parsing should continue for the next part of the hyphenated identifier.
13875                                if s.ends_with('.') {
13876                                    let Some(s) = s.split('.').next().filter(|s| {
13877                                        !s.is_empty() && s.chars().all(|c| c.is_ascii_digit())
13878                                    }) else {
13879                                        return self.expected(
13880                                            "continuation of hyphenated identifier",
13881                                            TokenWithSpan::new(Token::Number(s, false), token.span),
13882                                        );
13883                                    };
13884                                    ident.value.push_str(s);
13885                                    return Ok((ident, true));
13886                                } else {
13887                                    ident.value.push_str(&s);
13888                                }
13889                                // If next token is period, then it is part of an ObjectName and we don't expect whitespace
13890                                // after the number.
13891                                !matches!(self.peek_token_ref().token, Token::Period)
13892                            }
13893                            _ => {
13894                                return self
13895                                    .expected("continuation of hyphenated identifier", token);
13896                            }
13897                        }
13898                    }
13899
13900                    // If the last segment was a number, we must check that it's followed by whitespace,
13901                    // otherwise foo-123a will be parsed as `foo-123` with the alias `a`.
13902                    if requires_whitespace {
13903                        let token = self.next_token();
13904                        if !matches!(token.token, Token::EOF | Token::Whitespace(_)) {
13905                            return self
13906                                .expected("whitespace following hyphenated identifier", token);
13907                        }
13908                    }
13909                }
13910                Ok((ident, false))
13911            }
13912            _ => Ok((self.parse_identifier()?, false)),
13913        }
13914    }
13915
13916    /// Parses a parenthesized, comma-separated list of column definitions within a view.
13917    fn parse_view_columns(&mut self) -> Result<Vec<ViewColumnDef>, ParserError> {
13918        if self.consume_token(&Token::LParen) {
13919            if self.peek_token_ref().token == Token::RParen {
13920                self.next_token();
13921                Ok(vec![])
13922            } else {
13923                let cols = self.parse_comma_separated_with_trailing_commas(
13924                    Parser::parse_view_column,
13925                    self.dialect.supports_column_definition_trailing_commas(),
13926                    Self::is_reserved_for_column_alias,
13927                )?;
13928                self.expect_token(&Token::RParen)?;
13929                Ok(cols)
13930            }
13931        } else {
13932            Ok(vec![])
13933        }
13934    }
13935
13936    /// Parses a column definition within a view.
13937    fn parse_view_column(&mut self) -> Result<ViewColumnDef, ParserError> {
13938        let name = self.parse_identifier()?;
13939        let options = self.parse_view_column_options()?;
13940        let data_type = if dialect_of!(self is ClickHouseDialect) {
13941            Some(self.parse_data_type()?)
13942        } else {
13943            None
13944        };
13945        Ok(ViewColumnDef {
13946            name,
13947            data_type,
13948            options,
13949        })
13950    }
13951
13952    fn parse_view_column_options(&mut self) -> Result<Option<ColumnOptions>, ParserError> {
13953        let mut options = Vec::new();
13954        loop {
13955            let option = self.parse_optional_column_option()?;
13956            if let Some(option) = option {
13957                options.push(option);
13958            } else {
13959                break;
13960            }
13961        }
13962        if options.is_empty() {
13963            Ok(None)
13964        } else if self.dialect.supports_space_separated_column_options() {
13965            Ok(Some(ColumnOptions::SpaceSeparated(options)))
13966        } else {
13967            Ok(Some(ColumnOptions::CommaSeparated(options)))
13968        }
13969    }
13970
13971    /// Parses a parenthesized comma-separated list of unqualified, possibly quoted identifiers.
13972    /// For example: `(col1, "col 2", ...)`
13973    pub fn parse_parenthesized_column_list(
13974        &mut self,
13975        optional: IsOptional,
13976        allow_empty: bool,
13977    ) -> Result<Vec<Ident>, ParserError> {
13978        self.parse_parenthesized_column_list_inner(optional, allow_empty, |p| p.parse_identifier())
13979    }
13980
13981    /// Parse a parenthesized list of compound identifiers as expressions.
13982    pub fn parse_parenthesized_compound_identifier_list(
13983        &mut self,
13984        optional: IsOptional,
13985        allow_empty: bool,
13986    ) -> Result<Vec<Expr>, ParserError> {
13987        self.parse_parenthesized_column_list_inner(optional, allow_empty, |p| {
13988            Ok(Expr::CompoundIdentifier(
13989                p.parse_period_separated(|p| p.parse_identifier())?,
13990            ))
13991        })
13992    }
13993
13994    /// Parses a parenthesized comma-separated list of index columns, which can be arbitrary
13995    /// expressions with ordering information (and an opclass in some dialects).
13996    fn parse_parenthesized_index_column_list(&mut self) -> Result<Vec<IndexColumn>, ParserError> {
13997        self.parse_parenthesized_column_list_inner(Mandatory, false, |p| {
13998            p.parse_create_index_expr()
13999        })
14000    }
14001
14002    /// Parses a parenthesized comma-separated list of qualified, possibly quoted identifiers.
14003    /// For example: `(db1.sc1.tbl1.col1, db1.sc1.tbl1."col 2", ...)`
14004    pub fn parse_parenthesized_qualified_column_list(
14005        &mut self,
14006        optional: IsOptional,
14007        allow_empty: bool,
14008    ) -> Result<Vec<ObjectName>, ParserError> {
14009        self.parse_parenthesized_column_list_inner(optional, allow_empty, |p| {
14010            p.parse_object_name(true)
14011        })
14012    }
14013
14014    /// Parses a parenthesized comma-separated list of columns using
14015    /// the provided function to parse each element.
14016    fn parse_parenthesized_column_list_inner<F, T>(
14017        &mut self,
14018        optional: IsOptional,
14019        allow_empty: bool,
14020        mut f: F,
14021    ) -> Result<Vec<T>, ParserError>
14022    where
14023        F: FnMut(&mut Parser) -> Result<T, ParserError>,
14024    {
14025        if self.consume_token(&Token::LParen) {
14026            if allow_empty && self.peek_token_ref().token == Token::RParen {
14027                self.next_token();
14028                Ok(vec![])
14029            } else {
14030                let cols = self.parse_comma_separated(|p| f(p))?;
14031                self.expect_token(&Token::RParen)?;
14032                Ok(cols)
14033            }
14034        } else if optional == Optional {
14035            Ok(vec![])
14036        } else {
14037            self.expected_ref("a list of columns in parentheses", self.peek_token_ref())
14038        }
14039    }
14040
14041    /// Parses a parenthesized comma-separated list of table alias column definitions.
14042    fn parse_table_alias_column_defs(&mut self) -> Result<Vec<TableAliasColumnDef>, ParserError> {
14043        if self.consume_token(&Token::LParen) {
14044            let cols = self.parse_comma_separated(|p| {
14045                let name = p.parse_identifier()?;
14046                let data_type = p.maybe_parse(|p| p.parse_data_type())?;
14047                Ok(TableAliasColumnDef { name, data_type })
14048            })?;
14049            self.expect_token(&Token::RParen)?;
14050            Ok(cols)
14051        } else {
14052            Ok(vec![])
14053        }
14054    }
14055
14056    /// Parse an unsigned precision value enclosed in parentheses, e.g. `(10)`.
14057    pub fn parse_precision(&mut self) -> Result<u64, ParserError> {
14058        self.expect_token(&Token::LParen)?;
14059        let n = self.parse_literal_uint()?;
14060        self.expect_token(&Token::RParen)?;
14061        Ok(n)
14062    }
14063
14064    /// Parse an optional precision `(n)` and return it as `Some(n)` when present.
14065    pub fn parse_optional_precision(&mut self) -> Result<Option<u64>, ParserError> {
14066        if self.consume_token(&Token::LParen) {
14067            let n = self.parse_literal_uint()?;
14068            self.expect_token(&Token::RParen)?;
14069            Ok(Some(n))
14070        } else {
14071            Ok(None)
14072        }
14073    }
14074
14075    fn maybe_parse_optional_interval_fields(
14076        &mut self,
14077    ) -> Result<Option<IntervalFields>, ParserError> {
14078        match self.parse_one_of_keywords(&[
14079            // Can be followed by `TO` option
14080            Keyword::YEAR,
14081            Keyword::DAY,
14082            Keyword::HOUR,
14083            Keyword::MINUTE,
14084            // No `TO` option
14085            Keyword::MONTH,
14086            Keyword::SECOND,
14087        ]) {
14088            Some(Keyword::YEAR) => {
14089                if self.peek_keyword(Keyword::TO) {
14090                    self.expect_keyword(Keyword::TO)?;
14091                    self.expect_keyword(Keyword::MONTH)?;
14092                    Ok(Some(IntervalFields::YearToMonth))
14093                } else {
14094                    Ok(Some(IntervalFields::Year))
14095                }
14096            }
14097            Some(Keyword::DAY) => {
14098                if self.peek_keyword(Keyword::TO) {
14099                    self.expect_keyword(Keyword::TO)?;
14100                    match self.expect_one_of_keywords(&[
14101                        Keyword::HOUR,
14102                        Keyword::MINUTE,
14103                        Keyword::SECOND,
14104                    ])? {
14105                        Keyword::HOUR => Ok(Some(IntervalFields::DayToHour)),
14106                        Keyword::MINUTE => Ok(Some(IntervalFields::DayToMinute)),
14107                        Keyword::SECOND => Ok(Some(IntervalFields::DayToSecond)),
14108                        _ => {
14109                            self.prev_token();
14110                            self.expected_ref("HOUR, MINUTE, or SECOND", self.peek_token_ref())
14111                        }
14112                    }
14113                } else {
14114                    Ok(Some(IntervalFields::Day))
14115                }
14116            }
14117            Some(Keyword::HOUR) => {
14118                if self.peek_keyword(Keyword::TO) {
14119                    self.expect_keyword(Keyword::TO)?;
14120                    match self.expect_one_of_keywords(&[Keyword::MINUTE, Keyword::SECOND])? {
14121                        Keyword::MINUTE => Ok(Some(IntervalFields::HourToMinute)),
14122                        Keyword::SECOND => Ok(Some(IntervalFields::HourToSecond)),
14123                        _ => {
14124                            self.prev_token();
14125                            self.expected_ref("MINUTE or SECOND", self.peek_token_ref())
14126                        }
14127                    }
14128                } else {
14129                    Ok(Some(IntervalFields::Hour))
14130                }
14131            }
14132            Some(Keyword::MINUTE) => {
14133                if self.peek_keyword(Keyword::TO) {
14134                    self.expect_keyword(Keyword::TO)?;
14135                    self.expect_keyword(Keyword::SECOND)?;
14136                    Ok(Some(IntervalFields::MinuteToSecond))
14137                } else {
14138                    Ok(Some(IntervalFields::Minute))
14139                }
14140            }
14141            Some(Keyword::MONTH) => Ok(Some(IntervalFields::Month)),
14142            Some(Keyword::SECOND) => Ok(Some(IntervalFields::Second)),
14143            Some(_) => {
14144                self.prev_token();
14145                self.expected_ref(
14146                    "YEAR, MONTH, DAY, HOUR, MINUTE, or SECOND",
14147                    self.peek_token_ref(),
14148                )
14149            }
14150            None => Ok(None),
14151        }
14152    }
14153
14154    /// Parse datetime64 [1]
14155    /// Syntax
14156    /// ```sql
14157    /// DateTime64(precision[, timezone])
14158    /// ```
14159    ///
14160    /// [1]: https://clickhouse.com/docs/en/sql-reference/data-types/datetime64
14161    pub fn parse_datetime_64(&mut self) -> Result<(u64, Option<String>), ParserError> {
14162        self.expect_keyword_is(Keyword::DATETIME64)?;
14163        self.expect_token(&Token::LParen)?;
14164        let precision = self.parse_literal_uint()?;
14165        let time_zone = if self.consume_token(&Token::Comma) {
14166            Some(self.parse_literal_string()?)
14167        } else {
14168            None
14169        };
14170        self.expect_token(&Token::RParen)?;
14171        Ok((precision, time_zone))
14172    }
14173
14174    /// Parse an optional character length specification `(n | MAX [CHARACTERS|OCTETS])`.
14175    pub fn parse_optional_character_length(
14176        &mut self,
14177    ) -> Result<Option<CharacterLength>, ParserError> {
14178        if self.consume_token(&Token::LParen) {
14179            let character_length = self.parse_character_length()?;
14180            self.expect_token(&Token::RParen)?;
14181            Ok(Some(character_length))
14182        } else {
14183            Ok(None)
14184        }
14185    }
14186
14187    /// Parse an optional binary length specification like `(n)`.
14188    pub fn parse_optional_binary_length(&mut self) -> Result<Option<BinaryLength>, ParserError> {
14189        if self.consume_token(&Token::LParen) {
14190            let binary_length = self.parse_binary_length()?;
14191            self.expect_token(&Token::RParen)?;
14192            Ok(Some(binary_length))
14193        } else {
14194            Ok(None)
14195        }
14196    }
14197
14198    /// Parse a character length, handling `MAX` or integer lengths with optional units.
14199    pub fn parse_character_length(&mut self) -> Result<CharacterLength, ParserError> {
14200        if self.parse_keyword(Keyword::MAX) {
14201            return Ok(CharacterLength::Max);
14202        }
14203        let length = self.parse_literal_uint()?;
14204        let unit = if self.parse_keyword(Keyword::CHARACTERS) {
14205            Some(CharLengthUnits::Characters)
14206        } else if self.parse_keyword(Keyword::OCTETS) {
14207            Some(CharLengthUnits::Octets)
14208        } else {
14209            None
14210        };
14211        Ok(CharacterLength::IntegerLength { length, unit })
14212    }
14213
14214    /// Parse a binary length specification, returning `BinaryLength`.
14215    pub fn parse_binary_length(&mut self) -> Result<BinaryLength, ParserError> {
14216        if self.parse_keyword(Keyword::MAX) {
14217            return Ok(BinaryLength::Max);
14218        }
14219        let length = self.parse_literal_uint()?;
14220        Ok(BinaryLength::IntegerLength { length })
14221    }
14222
14223    /// Parse an optional `(precision[, scale])` and return `(Option<precision>, Option<scale>)`.
14224    pub fn parse_optional_precision_scale(
14225        &mut self,
14226    ) -> Result<(Option<u64>, Option<u64>), ParserError> {
14227        if self.consume_token(&Token::LParen) {
14228            let n = self.parse_literal_uint()?;
14229            let scale = if self.consume_token(&Token::Comma) {
14230                Some(self.parse_literal_uint()?)
14231            } else {
14232                None
14233            };
14234            self.expect_token(&Token::RParen)?;
14235            Ok((Some(n), scale))
14236        } else {
14237            Ok((None, None))
14238        }
14239    }
14240
14241    /// Parse exact-number precision/scale info like `(precision[, scale])` for decimal types.
14242    pub fn parse_exact_number_optional_precision_scale(
14243        &mut self,
14244    ) -> Result<ExactNumberInfo, ParserError> {
14245        if self.consume_token(&Token::LParen) {
14246            let precision = self.parse_literal_uint()?;
14247            let scale = if self.consume_token(&Token::Comma) {
14248                Some(self.parse_signed_integer()?)
14249            } else {
14250                None
14251            };
14252
14253            self.expect_token(&Token::RParen)?;
14254
14255            match scale {
14256                None => Ok(ExactNumberInfo::Precision(precision)),
14257                Some(scale) => Ok(ExactNumberInfo::PrecisionAndScale(precision, scale)),
14258            }
14259        } else {
14260            Ok(ExactNumberInfo::None)
14261        }
14262    }
14263
14264    /// Parse an optionally signed integer literal.
14265    fn parse_signed_integer(&mut self) -> Result<i64, ParserError> {
14266        let is_negative = self.consume_token(&Token::Minus);
14267
14268        if !is_negative {
14269            let _ = self.consume_token(&Token::Plus);
14270        }
14271
14272        let current_token = self.peek_token_ref();
14273        match &current_token.token {
14274            Token::Number(s, _) => {
14275                let s = s.clone();
14276                let span_start = current_token.span.start;
14277                self.advance_token();
14278                let value = Self::parse::<i64>(s, span_start)?;
14279                Ok(if is_negative { -value } else { value })
14280            }
14281            _ => self.expected_ref("number", current_token),
14282        }
14283    }
14284
14285    /// Parse optional type modifiers appearing in parentheses e.g. `(UNSIGNED, ZEROFILL)`.
14286    pub fn parse_optional_type_modifiers(&mut self) -> Result<Option<Vec<String>>, ParserError> {
14287        if self.consume_token(&Token::LParen) {
14288            let mut modifiers = Vec::new();
14289            loop {
14290                let next_token = self.next_token();
14291                match next_token.token {
14292                    Token::Word(w) => modifiers.push(w.to_string()),
14293                    Token::Number(n, _) => modifiers.push(n),
14294                    Token::SingleQuotedString(s) => modifiers.push(s),
14295
14296                    Token::Comma => {
14297                        continue;
14298                    }
14299                    Token::RParen => {
14300                        break;
14301                    }
14302                    _ => self.expected("type modifiers", next_token)?,
14303                }
14304            }
14305
14306            Ok(Some(modifiers))
14307        } else {
14308            Ok(None)
14309        }
14310    }
14311
14312    /// Parse a parenthesized sub data type
14313    fn parse_sub_type<F>(&mut self, parent_type: F) -> Result<DataType, ParserError>
14314    where
14315        F: FnOnce(Box<DataType>) -> DataType,
14316    {
14317        self.expect_token(&Token::LParen)?;
14318        let inside_type = self.parse_data_type()?;
14319        self.expect_token(&Token::RParen)?;
14320        Ok(parent_type(inside_type.into()))
14321    }
14322
14323    /// Parse a DELETE statement, returning a `Box`ed SetExpr
14324    ///
14325    /// This is used to reduce the size of the stack frames in debug builds
14326    fn parse_delete_setexpr_boxed(
14327        &mut self,
14328        delete_token: TokenWithSpan,
14329    ) -> Result<Box<SetExpr>, ParserError> {
14330        Ok(Box::new(SetExpr::Delete(self.parse_delete(delete_token)?)))
14331    }
14332
14333    /// Parse a `DELETE` statement and return `Statement::Delete`.
14334    pub fn parse_delete(&mut self, delete_token: TokenWithSpan) -> Result<Statement, ParserError> {
14335        let optimizer_hints = self.maybe_parse_optimizer_hints()?;
14336        let (tables, with_from_keyword) = if !self.parse_keyword(Keyword::FROM) {
14337            // `FROM` keyword is optional in BigQuery SQL.
14338            // https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#delete_statement
14339            if dialect_of!(self is BigQueryDialect | OracleDialect | GenericDialect) {
14340                (vec![], false)
14341            } else {
14342                let tables = self.parse_comma_separated(|p| p.parse_object_name(false))?;
14343                self.expect_keyword_is(Keyword::FROM)?;
14344                (tables, true)
14345            }
14346        } else {
14347            (vec![], true)
14348        };
14349
14350        let from = self.parse_comma_separated(Parser::parse_table_and_joins)?;
14351
14352        let output = self.maybe_parse_output_clause()?;
14353
14354        let using = if self.parse_keyword(Keyword::USING) {
14355            Some(self.parse_comma_separated(Parser::parse_table_and_joins)?)
14356        } else {
14357            None
14358        };
14359        let selection = if self.parse_keyword(Keyword::WHERE) {
14360            Some(self.parse_expr()?)
14361        } else {
14362            None
14363        };
14364        let returning = if self.parse_keyword(Keyword::RETURNING) {
14365            Some(self.parse_comma_separated(Parser::parse_select_item)?)
14366        } else {
14367            None
14368        };
14369        let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
14370            self.parse_comma_separated(Parser::parse_order_by_expr)?
14371        } else {
14372            vec![]
14373        };
14374        let limit = if self.parse_keyword(Keyword::LIMIT) {
14375            self.parse_limit()?
14376        } else {
14377            None
14378        };
14379
14380        Ok(Statement::Delete(Delete {
14381            delete_token: delete_token.into(),
14382            optimizer_hints,
14383            tables,
14384            from: if with_from_keyword {
14385                FromTable::WithFromKeyword(from)
14386            } else {
14387                FromTable::WithoutKeyword(from)
14388            },
14389            using,
14390            selection,
14391            returning,
14392            output,
14393            order_by,
14394            limit,
14395        }))
14396    }
14397
14398    /// Parse a `KILL` statement, optionally specifying `CONNECTION`, `QUERY`, or `MUTATION`.
14399    /// KILL [CONNECTION | QUERY | MUTATION] processlist_id
14400    pub fn parse_kill(&mut self) -> Result<Statement, ParserError> {
14401        let modifier_keyword =
14402            self.parse_one_of_keywords(&[Keyword::CONNECTION, Keyword::QUERY, Keyword::MUTATION]);
14403
14404        let id = self.parse_literal_uint()?;
14405
14406        let modifier = match modifier_keyword {
14407            Some(Keyword::CONNECTION) => Some(KillType::Connection),
14408            Some(Keyword::QUERY) => Some(KillType::Query),
14409            Some(Keyword::MUTATION) => {
14410                if dialect_of!(self is ClickHouseDialect | GenericDialect) {
14411                    Some(KillType::Mutation)
14412                } else {
14413                    self.expected_ref(
14414                        "Unsupported type for KILL, allowed: CONNECTION | QUERY",
14415                        self.peek_token_ref(),
14416                    )?
14417                }
14418            }
14419            _ => None,
14420        };
14421
14422        Ok(Statement::Kill { modifier, id })
14423    }
14424
14425    /// Parse an `EXPLAIN` statement, handling dialect-specific options and modifiers.
14426    pub fn parse_explain(
14427        &mut self,
14428        describe_alias: DescribeAlias,
14429    ) -> Result<Statement, ParserError> {
14430        let mut analyze = false;
14431        let mut verbose = false;
14432        let mut query_plan = false;
14433        let mut estimate = false;
14434        let mut format = None;
14435        let mut options = None;
14436
14437        // Note: DuckDB is compatible with PostgreSQL syntax for this statement,
14438        // although not all features may be implemented.
14439        if describe_alias == DescribeAlias::Explain
14440            && self.dialect.supports_explain_with_utility_options()
14441            && self.peek_token_ref().token == Token::LParen
14442        {
14443            options = Some(self.parse_utility_options()?)
14444        } else if self.parse_keywords(&[Keyword::QUERY, Keyword::PLAN]) {
14445            query_plan = true;
14446        } else if self.parse_keyword(Keyword::ESTIMATE) {
14447            estimate = true;
14448        } else {
14449            analyze = self.parse_keyword(Keyword::ANALYZE);
14450            verbose = self.parse_keyword(Keyword::VERBOSE);
14451            if self.parse_keyword(Keyword::FORMAT) {
14452                format = Some(self.parse_analyze_format_kind()?);
14453            }
14454        }
14455
14456        match self.maybe_parse(|parser| parser.parse_statement())? {
14457            Some(Statement::Explain { .. }) | Some(Statement::ExplainTable { .. }) => Err(
14458                ParserError::ParserError("Explain must be root of the plan".to_string()),
14459            ),
14460            Some(statement) => Ok(Statement::Explain {
14461                describe_alias,
14462                analyze,
14463                verbose,
14464                query_plan,
14465                estimate,
14466                statement: Box::new(statement),
14467                format,
14468                options,
14469            }),
14470            _ => {
14471                let hive_format =
14472                    match self.parse_one_of_keywords(&[Keyword::EXTENDED, Keyword::FORMATTED]) {
14473                        Some(Keyword::EXTENDED) => Some(HiveDescribeFormat::Extended),
14474                        Some(Keyword::FORMATTED) => Some(HiveDescribeFormat::Formatted),
14475                        _ => None,
14476                    };
14477
14478                let has_table_keyword = if self.dialect.describe_requires_table_keyword() {
14479                    // only allow to use TABLE keyword for DESC|DESCRIBE statement
14480                    self.parse_keyword(Keyword::TABLE)
14481                } else {
14482                    false
14483                };
14484
14485                let table_name = self.parse_object_name(false)?;
14486                Ok(Statement::ExplainTable {
14487                    describe_alias,
14488                    hive_format,
14489                    has_table_keyword,
14490                    table_name,
14491                })
14492            }
14493        }
14494    }
14495
14496    /// Parse a query expression, i.e. a `SELECT` statement optionally
14497    /// preceded with some `WITH` CTE declarations and optionally followed
14498    /// by `ORDER BY`. Unlike some other parse_... methods, this one doesn't
14499    /// expect the initial keyword to be already consumed
14500    #[cfg_attr(feature = "recursive-protection", recursive::recursive)]
14501    pub fn parse_query(&mut self) -> Result<Box<Query>, ParserError> {
14502        let _guard = self.recursion_counter.try_decrease()?;
14503        let with = if self.parse_keyword(Keyword::WITH) {
14504            let with_token = self.get_current_token();
14505            Some(With {
14506                with_token: with_token.clone().into(),
14507                recursive: self.parse_keyword(Keyword::RECURSIVE),
14508                cte_tables: self.parse_comma_separated(Parser::parse_cte)?,
14509            })
14510        } else {
14511            None
14512        };
14513        if self.parse_keyword(Keyword::INSERT) {
14514            Ok(Query {
14515                with,
14516                body: self.parse_insert_setexpr_boxed(self.get_current_token().clone())?,
14517                order_by: None,
14518                limit_clause: None,
14519                fetch: None,
14520                locks: vec![],
14521                for_clause: None,
14522                settings: None,
14523                format_clause: None,
14524                pipe_operators: vec![],
14525            }
14526            .into())
14527        } else if self.parse_keyword(Keyword::UPDATE) {
14528            Ok(Query {
14529                with,
14530                body: self.parse_update_setexpr_boxed(self.get_current_token().clone())?,
14531                order_by: None,
14532                limit_clause: None,
14533                fetch: None,
14534                locks: vec![],
14535                for_clause: None,
14536                settings: None,
14537                format_clause: None,
14538                pipe_operators: vec![],
14539            }
14540            .into())
14541        } else if self.parse_keyword(Keyword::DELETE) {
14542            Ok(Query {
14543                with,
14544                body: self.parse_delete_setexpr_boxed(self.get_current_token().clone())?,
14545                limit_clause: None,
14546                order_by: None,
14547                fetch: None,
14548                locks: vec![],
14549                for_clause: None,
14550                settings: None,
14551                format_clause: None,
14552                pipe_operators: vec![],
14553            }
14554            .into())
14555        } else if self.parse_keyword(Keyword::MERGE) {
14556            Ok(Query {
14557                with,
14558                body: self.parse_merge_setexpr_boxed(self.get_current_token().clone())?,
14559                limit_clause: None,
14560                order_by: None,
14561                fetch: None,
14562                locks: vec![],
14563                for_clause: None,
14564                settings: None,
14565                format_clause: None,
14566                pipe_operators: vec![],
14567            }
14568            .into())
14569        } else {
14570            let body = self.parse_query_body(self.dialect.prec_unknown())?;
14571
14572            let order_by = self.parse_optional_order_by()?;
14573
14574            let limit_clause = self.parse_optional_limit_clause()?;
14575
14576            let settings = self.parse_settings()?;
14577
14578            let fetch = if self.parse_keyword(Keyword::FETCH) {
14579                Some(self.parse_fetch()?)
14580            } else {
14581                None
14582            };
14583
14584            let mut for_clause = None;
14585            let mut locks = Vec::new();
14586            while self.parse_keyword(Keyword::FOR) {
14587                if let Some(parsed_for_clause) = self.parse_for_clause()? {
14588                    for_clause = Some(parsed_for_clause);
14589                    break;
14590                } else {
14591                    locks.push(self.parse_lock()?);
14592                }
14593            }
14594            let format_clause =
14595                if self.dialect.supports_select_format() && self.parse_keyword(Keyword::FORMAT) {
14596                    if self.parse_keyword(Keyword::NULL) {
14597                        Some(FormatClause::Null)
14598                    } else {
14599                        let ident = self.parse_identifier()?;
14600                        Some(FormatClause::Identifier(ident))
14601                    }
14602                } else {
14603                    None
14604                };
14605
14606            let pipe_operators = if self.dialect.supports_pipe_operator() {
14607                self.parse_pipe_operators()?
14608            } else {
14609                Vec::new()
14610            };
14611
14612            Ok(Query {
14613                with,
14614                body,
14615                order_by,
14616                limit_clause,
14617                fetch,
14618                locks,
14619                for_clause,
14620                settings,
14621                format_clause,
14622                pipe_operators,
14623            }
14624            .into())
14625        }
14626    }
14627
14628    fn parse_pipe_operators(&mut self) -> Result<Vec<PipeOperator>, ParserError> {
14629        let mut pipe_operators = Vec::new();
14630
14631        while self.consume_token(&Token::VerticalBarRightAngleBracket) {
14632            let kw = self.expect_one_of_keywords(&[
14633                Keyword::SELECT,
14634                Keyword::EXTEND,
14635                Keyword::SET,
14636                Keyword::DROP,
14637                Keyword::AS,
14638                Keyword::WHERE,
14639                Keyword::LIMIT,
14640                Keyword::AGGREGATE,
14641                Keyword::ORDER,
14642                Keyword::TABLESAMPLE,
14643                Keyword::RENAME,
14644                Keyword::UNION,
14645                Keyword::INTERSECT,
14646                Keyword::EXCEPT,
14647                Keyword::CALL,
14648                Keyword::PIVOT,
14649                Keyword::UNPIVOT,
14650                Keyword::JOIN,
14651                Keyword::INNER,
14652                Keyword::LEFT,
14653                Keyword::RIGHT,
14654                Keyword::FULL,
14655                Keyword::CROSS,
14656            ])?;
14657            match kw {
14658                Keyword::SELECT => {
14659                    let exprs = self.parse_comma_separated(Parser::parse_select_item)?;
14660                    pipe_operators.push(PipeOperator::Select { exprs })
14661                }
14662                Keyword::EXTEND => {
14663                    let exprs = self.parse_comma_separated(Parser::parse_select_item)?;
14664                    pipe_operators.push(PipeOperator::Extend { exprs })
14665                }
14666                Keyword::SET => {
14667                    let assignments = self.parse_comma_separated(Parser::parse_assignment)?;
14668                    pipe_operators.push(PipeOperator::Set { assignments })
14669                }
14670                Keyword::DROP => {
14671                    let columns = self.parse_identifiers()?;
14672                    pipe_operators.push(PipeOperator::Drop { columns })
14673                }
14674                Keyword::AS => {
14675                    let alias = self.parse_identifier()?;
14676                    pipe_operators.push(PipeOperator::As { alias })
14677                }
14678                Keyword::WHERE => {
14679                    let expr = self.parse_expr()?;
14680                    pipe_operators.push(PipeOperator::Where { expr })
14681                }
14682                Keyword::LIMIT => {
14683                    let expr = self.parse_expr()?;
14684                    let offset = if self.parse_keyword(Keyword::OFFSET) {
14685                        Some(self.parse_expr()?)
14686                    } else {
14687                        None
14688                    };
14689                    pipe_operators.push(PipeOperator::Limit { expr, offset })
14690                }
14691                Keyword::AGGREGATE => {
14692                    let full_table_exprs = if self.peek_keyword(Keyword::GROUP) {
14693                        vec![]
14694                    } else {
14695                        self.parse_comma_separated(|parser| {
14696                            parser.parse_expr_with_alias_and_order_by()
14697                        })?
14698                    };
14699
14700                    let group_by_expr = if self.parse_keywords(&[Keyword::GROUP, Keyword::BY]) {
14701                        self.parse_comma_separated(|parser| {
14702                            parser.parse_expr_with_alias_and_order_by()
14703                        })?
14704                    } else {
14705                        vec![]
14706                    };
14707
14708                    pipe_operators.push(PipeOperator::Aggregate {
14709                        full_table_exprs,
14710                        group_by_expr,
14711                    })
14712                }
14713                Keyword::ORDER => {
14714                    self.expect_one_of_keywords(&[Keyword::BY])?;
14715                    let exprs = self.parse_comma_separated(Parser::parse_order_by_expr)?;
14716                    pipe_operators.push(PipeOperator::OrderBy { exprs })
14717                }
14718                Keyword::TABLESAMPLE => {
14719                    let sample = self.parse_table_sample(TableSampleModifier::TableSample)?;
14720                    pipe_operators.push(PipeOperator::TableSample { sample });
14721                }
14722                Keyword::RENAME => {
14723                    let mappings =
14724                        self.parse_comma_separated(Parser::parse_identifier_with_optional_alias)?;
14725                    pipe_operators.push(PipeOperator::Rename { mappings });
14726                }
14727                Keyword::UNION => {
14728                    let set_quantifier = self.parse_set_quantifier(&Some(SetOperator::Union));
14729                    let queries = self.parse_pipe_operator_queries()?;
14730                    pipe_operators.push(PipeOperator::Union {
14731                        set_quantifier,
14732                        queries,
14733                    });
14734                }
14735                Keyword::INTERSECT => {
14736                    let set_quantifier =
14737                        self.parse_distinct_required_set_quantifier("INTERSECT")?;
14738                    let queries = self.parse_pipe_operator_queries()?;
14739                    pipe_operators.push(PipeOperator::Intersect {
14740                        set_quantifier,
14741                        queries,
14742                    });
14743                }
14744                Keyword::EXCEPT => {
14745                    let set_quantifier = self.parse_distinct_required_set_quantifier("EXCEPT")?;
14746                    let queries = self.parse_pipe_operator_queries()?;
14747                    pipe_operators.push(PipeOperator::Except {
14748                        set_quantifier,
14749                        queries,
14750                    });
14751                }
14752                Keyword::CALL => {
14753                    let function_name = self.parse_object_name(false)?;
14754                    let function_expr = self.parse_function(function_name)?;
14755                    if let Expr::Function(function) = function_expr {
14756                        let alias = self.parse_identifier_optional_alias()?;
14757                        pipe_operators.push(PipeOperator::Call { function, alias });
14758                    } else {
14759                        return Err(ParserError::ParserError(
14760                            "Expected function call after CALL".to_string(),
14761                        ));
14762                    }
14763                }
14764                Keyword::PIVOT => {
14765                    self.expect_token(&Token::LParen)?;
14766                    let aggregate_functions =
14767                        self.parse_comma_separated(Self::parse_pivot_aggregate_function)?;
14768                    self.expect_keyword_is(Keyword::FOR)?;
14769                    let value_column = self.parse_period_separated(|p| p.parse_identifier())?;
14770                    self.expect_keyword_is(Keyword::IN)?;
14771
14772                    self.expect_token(&Token::LParen)?;
14773                    let value_source = if self.parse_keyword(Keyword::ANY) {
14774                        let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
14775                            self.parse_comma_separated(Parser::parse_order_by_expr)?
14776                        } else {
14777                            vec![]
14778                        };
14779                        PivotValueSource::Any(order_by)
14780                    } else if self.peek_sub_query() {
14781                        PivotValueSource::Subquery(self.parse_query()?)
14782                    } else {
14783                        PivotValueSource::List(
14784                            self.parse_comma_separated(Self::parse_expr_with_alias)?,
14785                        )
14786                    };
14787                    self.expect_token(&Token::RParen)?;
14788                    self.expect_token(&Token::RParen)?;
14789
14790                    let alias = self.parse_identifier_optional_alias()?;
14791
14792                    pipe_operators.push(PipeOperator::Pivot {
14793                        aggregate_functions,
14794                        value_column,
14795                        value_source,
14796                        alias,
14797                    });
14798                }
14799                Keyword::UNPIVOT => {
14800                    self.expect_token(&Token::LParen)?;
14801                    let value_column = self.parse_identifier()?;
14802                    self.expect_keyword(Keyword::FOR)?;
14803                    let name_column = self.parse_identifier()?;
14804                    self.expect_keyword(Keyword::IN)?;
14805
14806                    self.expect_token(&Token::LParen)?;
14807                    let unpivot_columns = self.parse_comma_separated(Parser::parse_identifier)?;
14808                    self.expect_token(&Token::RParen)?;
14809
14810                    self.expect_token(&Token::RParen)?;
14811
14812                    let alias = self.parse_identifier_optional_alias()?;
14813
14814                    pipe_operators.push(PipeOperator::Unpivot {
14815                        value_column,
14816                        name_column,
14817                        unpivot_columns,
14818                        alias,
14819                    });
14820                }
14821                Keyword::JOIN
14822                | Keyword::INNER
14823                | Keyword::LEFT
14824                | Keyword::RIGHT
14825                | Keyword::FULL
14826                | Keyword::CROSS => {
14827                    self.prev_token();
14828                    let mut joins = self.parse_joins()?;
14829                    if joins.len() != 1 {
14830                        return Err(ParserError::ParserError(
14831                            "Join pipe operator must have a single join".to_string(),
14832                        ));
14833                    }
14834                    let join = joins.swap_remove(0);
14835                    pipe_operators.push(PipeOperator::Join(join))
14836                }
14837                unhandled => {
14838                    return Err(ParserError::ParserError(format!(
14839                    "`expect_one_of_keywords` further up allowed unhandled keyword: {unhandled:?}"
14840                )))
14841                }
14842            }
14843        }
14844        Ok(pipe_operators)
14845    }
14846
14847    fn parse_settings(&mut self) -> Result<Option<Vec<Setting>>, ParserError> {
14848        let settings = if self.dialect.supports_settings() && self.parse_keyword(Keyword::SETTINGS)
14849        {
14850            let key_values = self.parse_comma_separated(|p| {
14851                let key = p.parse_identifier()?;
14852                p.expect_token(&Token::Eq)?;
14853                let value = p.parse_expr()?;
14854                Ok(Setting { key, value })
14855            })?;
14856            Some(key_values)
14857        } else {
14858            None
14859        };
14860        Ok(settings)
14861    }
14862
14863    /// Parse a mssql `FOR [XML | JSON | BROWSE]` clause
14864    pub fn parse_for_clause(&mut self) -> Result<Option<ForClause>, ParserError> {
14865        if self.parse_keyword(Keyword::XML) {
14866            Ok(Some(self.parse_for_xml()?))
14867        } else if self.parse_keyword(Keyword::JSON) {
14868            Ok(Some(self.parse_for_json()?))
14869        } else if self.parse_keyword(Keyword::BROWSE) {
14870            Ok(Some(ForClause::Browse))
14871        } else {
14872            Ok(None)
14873        }
14874    }
14875
14876    /// Parse a mssql `FOR XML` clause
14877    pub fn parse_for_xml(&mut self) -> Result<ForClause, ParserError> {
14878        let for_xml = if self.parse_keyword(Keyword::RAW) {
14879            let mut element_name = None;
14880            if self.peek_token_ref().token == Token::LParen {
14881                self.expect_token(&Token::LParen)?;
14882                element_name = Some(self.parse_literal_string()?);
14883                self.expect_token(&Token::RParen)?;
14884            }
14885            ForXml::Raw(element_name)
14886        } else if self.parse_keyword(Keyword::AUTO) {
14887            ForXml::Auto
14888        } else if self.parse_keyword(Keyword::EXPLICIT) {
14889            ForXml::Explicit
14890        } else if self.parse_keyword(Keyword::PATH) {
14891            let mut element_name = None;
14892            if self.peek_token_ref().token == Token::LParen {
14893                self.expect_token(&Token::LParen)?;
14894                element_name = Some(self.parse_literal_string()?);
14895                self.expect_token(&Token::RParen)?;
14896            }
14897            ForXml::Path(element_name)
14898        } else {
14899            return Err(ParserError::ParserError(
14900                "Expected FOR XML [RAW | AUTO | EXPLICIT | PATH ]".to_string(),
14901            ));
14902        };
14903        let mut elements = false;
14904        let mut binary_base64 = false;
14905        let mut root = None;
14906        let mut r#type = false;
14907        while self.peek_token_ref().token == Token::Comma {
14908            self.next_token();
14909            if self.parse_keyword(Keyword::ELEMENTS) {
14910                elements = true;
14911            } else if self.parse_keyword(Keyword::BINARY) {
14912                self.expect_keyword_is(Keyword::BASE64)?;
14913                binary_base64 = true;
14914            } else if self.parse_keyword(Keyword::ROOT) {
14915                self.expect_token(&Token::LParen)?;
14916                root = Some(self.parse_literal_string()?);
14917                self.expect_token(&Token::RParen)?;
14918            } else if self.parse_keyword(Keyword::TYPE) {
14919                r#type = true;
14920            }
14921        }
14922        Ok(ForClause::Xml {
14923            for_xml,
14924            elements,
14925            binary_base64,
14926            root,
14927            r#type,
14928        })
14929    }
14930
14931    /// Parse a mssql `FOR JSON` clause
14932    pub fn parse_for_json(&mut self) -> Result<ForClause, ParserError> {
14933        let for_json = if self.parse_keyword(Keyword::AUTO) {
14934            ForJson::Auto
14935        } else if self.parse_keyword(Keyword::PATH) {
14936            ForJson::Path
14937        } else {
14938            return Err(ParserError::ParserError(
14939                "Expected FOR JSON [AUTO | PATH ]".to_string(),
14940            ));
14941        };
14942        let mut root = None;
14943        let mut include_null_values = false;
14944        let mut without_array_wrapper = false;
14945        while self.peek_token_ref().token == Token::Comma {
14946            self.next_token();
14947            if self.parse_keyword(Keyword::ROOT) {
14948                self.expect_token(&Token::LParen)?;
14949                root = Some(self.parse_literal_string()?);
14950                self.expect_token(&Token::RParen)?;
14951            } else if self.parse_keyword(Keyword::INCLUDE_NULL_VALUES) {
14952                include_null_values = true;
14953            } else if self.parse_keyword(Keyword::WITHOUT_ARRAY_WRAPPER) {
14954                without_array_wrapper = true;
14955            }
14956        }
14957        Ok(ForClause::Json {
14958            for_json,
14959            root,
14960            include_null_values,
14961            without_array_wrapper,
14962        })
14963    }
14964
14965    /// Parse a CTE (`alias [( col1, col2, ... )] [AS] (subquery)`)
14966    pub fn parse_cte(&mut self) -> Result<Cte, ParserError> {
14967        let name = self.parse_identifier()?;
14968
14969        let as_optional = self.dialect.supports_cte_without_as();
14970
14971        // If AS is optional, first try to parse `name (query)` directly
14972        if as_optional && !self.peek_keyword(Keyword::AS) {
14973            if let Some((query, closing_paren_token)) = self.maybe_parse(|p| {
14974                p.expect_token(&Token::LParen)?;
14975                let query = p.parse_query()?;
14976                let closing_paren_token = p.expect_token(&Token::RParen)?;
14977                Ok((query, closing_paren_token))
14978            })? {
14979                let mut cte = Cte {
14980                    alias: TableAlias {
14981                        explicit: false,
14982                        name,
14983                        columns: vec![],
14984                        at: None,
14985                    },
14986                    query,
14987                    from: None,
14988                    materialized: None,
14989                    closing_paren_token: closing_paren_token.into(),
14990                };
14991                if self.parse_keyword(Keyword::FROM) {
14992                    cte.from = Some(self.parse_identifier()?);
14993                }
14994                return Ok(cte);
14995            }
14996        }
14997
14998        // Determine column definitions and consume AS
14999        let columns = if self.parse_keyword(Keyword::AS) {
15000            vec![]
15001        } else {
15002            let columns = self.parse_table_alias_column_defs()?;
15003            if as_optional {
15004                let _ = self.parse_keyword(Keyword::AS);
15005            } else {
15006                self.expect_keyword_is(Keyword::AS)?;
15007            }
15008            columns
15009        };
15010
15011        let mut is_materialized = None;
15012        if dialect_of!(self is PostgreSqlDialect) {
15013            if self.parse_keyword(Keyword::MATERIALIZED) {
15014                is_materialized = Some(CteAsMaterialized::Materialized);
15015            } else if self.parse_keywords(&[Keyword::NOT, Keyword::MATERIALIZED]) {
15016                is_materialized = Some(CteAsMaterialized::NotMaterialized);
15017            }
15018        }
15019
15020        self.expect_token(&Token::LParen)?;
15021        let query = self.parse_query()?;
15022        let closing_paren_token = self.expect_token(&Token::RParen)?;
15023
15024        let mut cte = Cte {
15025            alias: TableAlias {
15026                explicit: false,
15027                name,
15028                columns,
15029                at: None,
15030            },
15031            query,
15032            from: None,
15033            materialized: is_materialized,
15034            closing_paren_token: closing_paren_token.into(),
15035        };
15036        if self.dialect.supports_from_first_insert() && self.parse_keyword(Keyword::FROM) {
15037            cte.from = Some(self.parse_identifier()?);
15038        }
15039        Ok(cte)
15040    }
15041
15042    /// Parse a "query body", which is an expression with roughly the
15043    /// following grammar:
15044    /// ```sql
15045    ///   query_body ::= restricted_select | '(' subquery ')' | set_operation
15046    ///   restricted_select ::= 'SELECT' [expr_list] [ from ] [ where ] [ groupby_having ]
15047    ///   subquery ::= query_body [ order_by_limit ]
15048    ///   set_operation ::= query_body { 'UNION' | 'EXCEPT' | 'INTERSECT' } [ 'ALL' ] query_body
15049    /// ```
15050    pub fn parse_query_body(&mut self, precedence: u8) -> Result<Box<SetExpr>, ParserError> {
15051        // We parse the expression using a Pratt parser, as in `parse_expr()`.
15052        // Start by parsing a restricted SELECT or a `(subquery)`:
15053        let expr = if self.peek_keyword(Keyword::SELECT)
15054            || (self.peek_keyword(Keyword::FROM) && self.dialect.supports_from_first_select())
15055        {
15056            SetExpr::Select(self.parse_select().map(Box::new)?)
15057        } else if self.consume_token(&Token::LParen) {
15058            // CTEs are not allowed here, but the parser currently accepts them
15059            let subquery = self.parse_query()?;
15060            self.expect_token(&Token::RParen)?;
15061            SetExpr::Query(subquery)
15062        } else if self.parse_keyword(Keyword::VALUES) {
15063            let is_mysql = dialect_of!(self is MySqlDialect);
15064            SetExpr::Values(self.parse_values(is_mysql, false)?)
15065        } else if self.parse_keyword(Keyword::VALUE) {
15066            let is_mysql = dialect_of!(self is MySqlDialect);
15067            SetExpr::Values(self.parse_values(is_mysql, true)?)
15068        } else if self.parse_keyword(Keyword::TABLE) {
15069            SetExpr::Table(Box::new(self.parse_as_table()?))
15070        } else {
15071            return self.expected_ref(
15072                "SELECT, VALUES, or a subquery in the query body",
15073                self.peek_token_ref(),
15074            );
15075        };
15076
15077        self.parse_remaining_set_exprs(expr, precedence)
15078    }
15079
15080    /// Parse any extra set expressions that may be present in a query body
15081    ///
15082    /// (this is its own function to reduce required stack size in debug builds)
15083    fn parse_remaining_set_exprs(
15084        &mut self,
15085        mut expr: SetExpr,
15086        precedence: u8,
15087    ) -> Result<Box<SetExpr>, ParserError> {
15088        loop {
15089            // The query can be optionally followed by a set operator:
15090            let op = self.parse_set_operator(&self.peek_token().token);
15091            let next_precedence = match op {
15092                // UNION and EXCEPT have the same binding power and evaluate left-to-right
15093                Some(SetOperator::Union) | Some(SetOperator::Except) | Some(SetOperator::Minus) => {
15094                    10
15095                }
15096                // INTERSECT has higher precedence than UNION/EXCEPT
15097                Some(SetOperator::Intersect) => 20,
15098                // Unexpected token or EOF => stop parsing the query body
15099                None => break,
15100            };
15101            if precedence >= next_precedence {
15102                break;
15103            }
15104            self.next_token(); // skip past the set operator
15105            let set_quantifier = self.parse_set_quantifier(&op);
15106            expr = SetExpr::SetOperation {
15107                left: Box::new(expr),
15108                op: op.unwrap(),
15109                set_quantifier,
15110                right: self.parse_query_body(next_precedence)?,
15111            };
15112        }
15113
15114        Ok(expr.into())
15115    }
15116
15117    /// Parse a set operator token into its `SetOperator` variant.
15118    pub fn parse_set_operator(&mut self, token: &Token) -> Option<SetOperator> {
15119        match token {
15120            Token::Word(w) if w.keyword == Keyword::UNION => Some(SetOperator::Union),
15121            Token::Word(w) if w.keyword == Keyword::EXCEPT => Some(SetOperator::Except),
15122            Token::Word(w) if w.keyword == Keyword::INTERSECT => Some(SetOperator::Intersect),
15123            Token::Word(w) if w.keyword == Keyword::MINUS => Some(SetOperator::Minus),
15124            _ => None,
15125        }
15126    }
15127
15128    /// Parse a set quantifier (e.g., `ALL`, `DISTINCT BY NAME`) for the given set operator.
15129    pub fn parse_set_quantifier(&mut self, op: &Option<SetOperator>) -> SetQuantifier {
15130        match op {
15131            Some(
15132                SetOperator::Except
15133                | SetOperator::Intersect
15134                | SetOperator::Union
15135                | SetOperator::Minus,
15136            ) => {
15137                if self.parse_keywords(&[Keyword::DISTINCT, Keyword::BY, Keyword::NAME]) {
15138                    SetQuantifier::DistinctByName
15139                } else if self.parse_keywords(&[Keyword::BY, Keyword::NAME]) {
15140                    SetQuantifier::ByName
15141                } else if self.parse_keyword(Keyword::ALL) {
15142                    if self.parse_keywords(&[Keyword::BY, Keyword::NAME]) {
15143                        SetQuantifier::AllByName
15144                    } else {
15145                        SetQuantifier::All
15146                    }
15147                } else if self.parse_keyword(Keyword::DISTINCT) {
15148                    SetQuantifier::Distinct
15149                } else {
15150                    SetQuantifier::None
15151                }
15152            }
15153            _ => SetQuantifier::None,
15154        }
15155    }
15156
15157    /// Parse a restricted `SELECT` statement (no CTEs / `UNION` / `ORDER BY`)
15158    pub fn parse_select(&mut self) -> Result<Select, ParserError> {
15159        let mut from_first = None;
15160
15161        if self.dialect.supports_from_first_select() && self.peek_keyword(Keyword::FROM) {
15162            let from_token = self.expect_keyword(Keyword::FROM)?;
15163            let from = self.parse_table_with_joins()?;
15164            if !self.peek_keyword(Keyword::SELECT) {
15165                return Ok(Select {
15166                    select_token: AttachedToken(from_token),
15167                    optimizer_hints: vec![],
15168                    distinct: None,
15169                    select_modifiers: None,
15170                    top: None,
15171                    top_before_distinct: false,
15172                    projection: vec![],
15173                    exclude: None,
15174                    into: None,
15175                    from,
15176                    lateral_views: vec![],
15177                    prewhere: None,
15178                    selection: None,
15179                    group_by: GroupByExpr::Expressions(vec![], vec![]),
15180                    cluster_by: vec![],
15181                    distribute_by: vec![],
15182                    sort_by: vec![],
15183                    having: None,
15184                    named_window: vec![],
15185                    window_before_qualify: false,
15186                    qualify: None,
15187                    value_table_mode: None,
15188                    connect_by: vec![],
15189                    flavor: SelectFlavor::FromFirstNoSelect,
15190                });
15191            }
15192            from_first = Some(from);
15193        }
15194
15195        let select_token = self.expect_keyword(Keyword::SELECT)?;
15196        let optimizer_hints = self.maybe_parse_optimizer_hints()?;
15197        let value_table_mode = self.parse_value_table_mode()?;
15198
15199        let (select_modifiers, distinct_select_modifier) =
15200            if self.dialect.supports_select_modifiers() {
15201                self.parse_select_modifiers()?
15202            } else {
15203                (None, None)
15204            };
15205
15206        let mut top_before_distinct = false;
15207        let mut top = None;
15208        if self.dialect.supports_top_before_distinct() && self.parse_keyword(Keyword::TOP) {
15209            top = Some(self.parse_top()?);
15210            top_before_distinct = true;
15211        }
15212
15213        let distinct = if distinct_select_modifier.is_some() {
15214            distinct_select_modifier
15215        } else {
15216            self.parse_all_or_distinct()?
15217        };
15218
15219        if !self.dialect.supports_top_before_distinct() && self.parse_keyword(Keyword::TOP) {
15220            top = Some(self.parse_top()?);
15221        }
15222
15223        let projection =
15224            if self.dialect.supports_empty_projections() && self.peek_keyword(Keyword::FROM) {
15225                vec![]
15226            } else {
15227                self.parse_projection()?
15228            };
15229
15230        let exclude = if self.dialect.supports_select_exclude() {
15231            self.parse_optional_select_item_exclude()?
15232        } else {
15233            None
15234        };
15235
15236        let into = if self.parse_keyword(Keyword::INTO) {
15237            Some(self.parse_select_into()?)
15238        } else {
15239            None
15240        };
15241
15242        // Note that for keywords to be properly handled here, they need to be
15243        // added to `RESERVED_FOR_COLUMN_ALIAS` / `RESERVED_FOR_TABLE_ALIAS`,
15244        // otherwise they may be parsed as an alias as part of the `projection`
15245        // or `from`.
15246
15247        let (from, from_first) = if let Some(from) = from_first.take() {
15248            (from, true)
15249        } else if self.parse_keyword(Keyword::FROM) {
15250            (self.parse_table_with_joins()?, false)
15251        } else {
15252            (vec![], false)
15253        };
15254
15255        let mut lateral_views = vec![];
15256        loop {
15257            if self.parse_keywords(&[Keyword::LATERAL, Keyword::VIEW]) {
15258                let outer = self.parse_keyword(Keyword::OUTER);
15259                let lateral_view = self.parse_expr()?;
15260                let lateral_view_name = self.parse_object_name(false)?;
15261                let lateral_col_alias = self
15262                    .parse_comma_separated(|parser| {
15263                        parser.parse_optional_alias(&[
15264                            Keyword::WHERE,
15265                            Keyword::GROUP,
15266                            Keyword::CLUSTER,
15267                            Keyword::HAVING,
15268                            Keyword::LATERAL,
15269                        ]) // This couldn't possibly be a bad idea
15270                    })?
15271                    .into_iter()
15272                    .flatten()
15273                    .collect();
15274
15275                lateral_views.push(LateralView {
15276                    lateral_view,
15277                    lateral_view_name,
15278                    lateral_col_alias,
15279                    outer,
15280                });
15281            } else {
15282                break;
15283            }
15284        }
15285
15286        let prewhere = if self.dialect.supports_prewhere() && self.parse_keyword(Keyword::PREWHERE)
15287        {
15288            Some(self.parse_expr()?)
15289        } else {
15290            None
15291        };
15292
15293        let selection = if self.parse_keyword(Keyword::WHERE) {
15294            Some(self.parse_expr()?)
15295        } else {
15296            None
15297        };
15298
15299        let connect_by = self.maybe_parse_connect_by()?;
15300
15301        let group_by = self
15302            .parse_optional_group_by()?
15303            .unwrap_or_else(|| GroupByExpr::Expressions(vec![], vec![]));
15304
15305        let cluster_by = if self.parse_keywords(&[Keyword::CLUSTER, Keyword::BY]) {
15306            self.parse_comma_separated(Parser::parse_expr)?
15307        } else {
15308            vec![]
15309        };
15310
15311        let distribute_by = if self.parse_keywords(&[Keyword::DISTRIBUTE, Keyword::BY]) {
15312            self.parse_comma_separated(Parser::parse_expr)?
15313        } else {
15314            vec![]
15315        };
15316
15317        let sort_by = if self.parse_keywords(&[Keyword::SORT, Keyword::BY]) {
15318            self.parse_comma_separated(Parser::parse_order_by_expr)?
15319        } else {
15320            vec![]
15321        };
15322
15323        let having = if self.parse_keyword(Keyword::HAVING) {
15324            Some(self.parse_expr()?)
15325        } else {
15326            None
15327        };
15328
15329        // Accept QUALIFY and WINDOW in any order and flag accordingly.
15330        let (named_windows, qualify, window_before_qualify) = if self.parse_keyword(Keyword::WINDOW)
15331        {
15332            let named_windows = self.parse_comma_separated(Parser::parse_named_window)?;
15333            if self.parse_keyword(Keyword::QUALIFY) {
15334                (named_windows, Some(self.parse_expr()?), true)
15335            } else {
15336                (named_windows, None, true)
15337            }
15338        } else if self.parse_keyword(Keyword::QUALIFY) {
15339            let qualify = Some(self.parse_expr()?);
15340            if self.parse_keyword(Keyword::WINDOW) {
15341                (
15342                    self.parse_comma_separated(Parser::parse_named_window)?,
15343                    qualify,
15344                    false,
15345                )
15346            } else {
15347                (Default::default(), qualify, false)
15348            }
15349        } else {
15350            Default::default()
15351        };
15352
15353        Ok(Select {
15354            select_token: AttachedToken(select_token),
15355            optimizer_hints,
15356            distinct,
15357            select_modifiers,
15358            top,
15359            top_before_distinct,
15360            projection,
15361            exclude,
15362            into,
15363            from,
15364            lateral_views,
15365            prewhere,
15366            selection,
15367            group_by,
15368            cluster_by,
15369            distribute_by,
15370            sort_by,
15371            having,
15372            named_window: named_windows,
15373            window_before_qualify,
15374            qualify,
15375            value_table_mode,
15376            connect_by,
15377            flavor: if from_first {
15378                SelectFlavor::FromFirst
15379            } else {
15380                SelectFlavor::Standard
15381            },
15382        })
15383    }
15384
15385    /// Parses optimizer hints at the current token position.
15386    ///
15387    /// Collects all `/*prefix+...*/` and `--prefix+...` patterns.
15388    /// The `prefix` is any run of ASCII alphanumeric characters between the
15389    /// comment marker and `+` (e.g. `""` for `/*+...*/`, `"abc"` for `/*abc+...*/`).
15390    ///
15391    /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/optimizer-hints.html#optimizer-hints-overview)
15392    /// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Comments.html#GUID-D316D545-89E2-4D54-977F-FC97815CD62E)
15393    fn maybe_parse_optimizer_hints(&mut self) -> Result<Vec<OptimizerHint>, ParserError> {
15394        let supports_hints = self.dialect.supports_comment_optimizer_hint();
15395        if !supports_hints {
15396            return Ok(vec![]);
15397        }
15398        let mut hints = vec![];
15399        loop {
15400            let t = self.peek_nth_token_no_skip_ref(0);
15401            let Token::Whitespace(ws) = &t.token else {
15402                break;
15403            };
15404            match ws {
15405                Whitespace::SingleLineComment { comment, prefix } => {
15406                    if let Some((hint_prefix, text)) = Self::extract_hint_prefix_and_text(comment) {
15407                        hints.push(OptimizerHint {
15408                            prefix: hint_prefix,
15409                            text,
15410                            style: OptimizerHintStyle::SingleLine {
15411                                prefix: prefix.clone(),
15412                            },
15413                        });
15414                    }
15415                    self.next_token_no_skip();
15416                }
15417                Whitespace::MultiLineComment(comment) => {
15418                    if let Some((hint_prefix, text)) = Self::extract_hint_prefix_and_text(comment) {
15419                        hints.push(OptimizerHint {
15420                            prefix: hint_prefix,
15421                            text,
15422                            style: OptimizerHintStyle::MultiLine,
15423                        });
15424                    }
15425                    self.next_token_no_skip();
15426                }
15427                Whitespace::Space | Whitespace::Tab | Whitespace::Newline => {
15428                    self.next_token_no_skip();
15429                }
15430            }
15431        }
15432        Ok(hints)
15433    }
15434
15435    /// Checks if a comment's content starts with `[ASCII-alphanumeric]*+`
15436    /// and returns `(prefix, text_after_plus)` if so.
15437    fn extract_hint_prefix_and_text(comment: &str) -> Option<(String, String)> {
15438        let (before_plus, text) = comment.split_once('+')?;
15439        if before_plus.chars().all(|c| c.is_ascii_alphanumeric()) {
15440            Some((before_plus.to_string(), text.to_string()))
15441        } else {
15442            None
15443        }
15444    }
15445
15446    /// Parses MySQL SELECT modifiers and DISTINCT/ALL in any order.
15447    ///
15448    /// Manual testing shows odifiers can appear in any order, and modifiers other than DISTINCT/ALL
15449    /// can be repeated.
15450    ///
15451    /// <https://dev.mysql.com/doc/refman/8.4/en/select.html>
15452    fn parse_select_modifiers(
15453        &mut self,
15454    ) -> Result<(Option<SelectModifiers>, Option<Distinct>), ParserError> {
15455        let mut modifiers = SelectModifiers::default();
15456        let mut distinct = None;
15457
15458        let keywords = &[
15459            Keyword::ALL,
15460            Keyword::DISTINCT,
15461            Keyword::DISTINCTROW,
15462            Keyword::HIGH_PRIORITY,
15463            Keyword::STRAIGHT_JOIN,
15464            Keyword::SQL_SMALL_RESULT,
15465            Keyword::SQL_BIG_RESULT,
15466            Keyword::SQL_BUFFER_RESULT,
15467            Keyword::SQL_NO_CACHE,
15468            Keyword::SQL_CALC_FOUND_ROWS,
15469        ];
15470
15471        while let Some(keyword) = self.parse_one_of_keywords(keywords) {
15472            match keyword {
15473                Keyword::ALL | Keyword::DISTINCT if distinct.is_none() => {
15474                    self.prev_token();
15475                    distinct = self.parse_all_or_distinct()?;
15476                }
15477                // DISTINCTROW is a MySQL-specific legacy (but not deprecated) alias for DISTINCT
15478                Keyword::DISTINCTROW if distinct.is_none() => {
15479                    distinct = Some(Distinct::Distinct);
15480                }
15481                Keyword::HIGH_PRIORITY => modifiers.high_priority = true,
15482                Keyword::STRAIGHT_JOIN => modifiers.straight_join = true,
15483                Keyword::SQL_SMALL_RESULT => modifiers.sql_small_result = true,
15484                Keyword::SQL_BIG_RESULT => modifiers.sql_big_result = true,
15485                Keyword::SQL_BUFFER_RESULT => modifiers.sql_buffer_result = true,
15486                Keyword::SQL_NO_CACHE => modifiers.sql_no_cache = true,
15487                Keyword::SQL_CALC_FOUND_ROWS => modifiers.sql_calc_found_rows = true,
15488                _ => {
15489                    self.prev_token();
15490                    return self.expected_ref(
15491                        "HIGH_PRIORITY, STRAIGHT_JOIN, or other MySQL select modifier",
15492                        self.peek_token_ref(),
15493                    );
15494                }
15495            }
15496        }
15497
15498        // Avoid polluting the AST with `Some(SelectModifiers::default())` empty value unless there
15499        // actually were some modifiers set.
15500        let select_modifiers = if modifiers.is_any_set() {
15501            Some(modifiers)
15502        } else {
15503            None
15504        };
15505        Ok((select_modifiers, distinct))
15506    }
15507
15508    fn parse_value_table_mode(&mut self) -> Result<Option<ValueTableMode>, ParserError> {
15509        if !dialect_of!(self is BigQueryDialect) {
15510            return Ok(None);
15511        }
15512
15513        let mode = if self.parse_keywords(&[Keyword::DISTINCT, Keyword::AS, Keyword::VALUE]) {
15514            Some(ValueTableMode::DistinctAsValue)
15515        } else if self.parse_keywords(&[Keyword::DISTINCT, Keyword::AS, Keyword::STRUCT]) {
15516            Some(ValueTableMode::DistinctAsStruct)
15517        } else if self.parse_keywords(&[Keyword::AS, Keyword::VALUE])
15518            || self.parse_keywords(&[Keyword::ALL, Keyword::AS, Keyword::VALUE])
15519        {
15520            Some(ValueTableMode::AsValue)
15521        } else if self.parse_keywords(&[Keyword::AS, Keyword::STRUCT])
15522            || self.parse_keywords(&[Keyword::ALL, Keyword::AS, Keyword::STRUCT])
15523        {
15524            Some(ValueTableMode::AsStruct)
15525        } else if self.parse_keyword(Keyword::AS) {
15526            self.expected_ref("VALUE or STRUCT", self.peek_token_ref())?
15527        } else {
15528            None
15529        };
15530
15531        Ok(mode)
15532    }
15533
15534    /// Invoke `f` after first setting the parser's `ParserState` to `state`.
15535    ///
15536    /// Upon return, restores the parser's state to what it started at.
15537    fn with_state<T, F>(&mut self, state: ParserState, mut f: F) -> Result<T, ParserError>
15538    where
15539        F: FnMut(&mut Parser) -> Result<T, ParserError>,
15540    {
15541        let current_state = self.state;
15542        self.state = state;
15543        let res = f(self);
15544        self.state = current_state;
15545        res
15546    }
15547
15548    /// Parse a `CONNECT BY` clause (Oracle-style hierarchical query support).
15549    pub fn maybe_parse_connect_by(&mut self) -> Result<Vec<ConnectByKind>, ParserError> {
15550        let mut clauses = Vec::with_capacity(2);
15551        loop {
15552            if let Some(idx) = self.parse_keywords_indexed(&[Keyword::START, Keyword::WITH]) {
15553                clauses.push(ConnectByKind::StartWith {
15554                    start_token: self.token_at(idx).clone().into(),
15555                    condition: self.parse_expr()?.into(),
15556                });
15557            } else if let Some(idx) = self.parse_keywords_indexed(&[Keyword::CONNECT, Keyword::BY])
15558            {
15559                clauses.push(ConnectByKind::ConnectBy {
15560                    connect_token: self.token_at(idx).clone().into(),
15561                    nocycle: self.parse_keyword(Keyword::NOCYCLE),
15562                    relationships: self.with_state(ParserState::ConnectBy, |parser| {
15563                        parser.parse_comma_separated(Parser::parse_expr)
15564                    })?,
15565                });
15566            } else {
15567                break;
15568            }
15569        }
15570        Ok(clauses)
15571    }
15572
15573    /// Parse `CREATE TABLE x AS TABLE y`
15574    pub fn parse_as_table(&mut self) -> Result<Table, ParserError> {
15575        let token1 = self.next_token();
15576        let token2 = self.next_token();
15577        let token3 = self.next_token();
15578
15579        let table_name;
15580        let schema_name;
15581        if token2 == Token::Period {
15582            match token1.token {
15583                Token::Word(w) => {
15584                    schema_name = w.value;
15585                }
15586                _ => {
15587                    return self.expected("Schema name", token1);
15588                }
15589            }
15590            match token3.token {
15591                Token::Word(w) => {
15592                    table_name = w.value;
15593                }
15594                _ => {
15595                    return self.expected("Table name", token3);
15596                }
15597            }
15598            Ok(Table {
15599                table_name: Some(table_name),
15600                schema_name: Some(schema_name),
15601            })
15602        } else {
15603            match token1.token {
15604                Token::Word(w) => {
15605                    table_name = w.value;
15606                }
15607                _ => {
15608                    return self.expected("Table name", token1);
15609                }
15610            }
15611            Ok(Table {
15612                table_name: Some(table_name),
15613                schema_name: None,
15614            })
15615        }
15616    }
15617
15618    /// Parse a `SET ROLE` statement. Expects SET to be consumed already.
15619    fn parse_set_role(
15620        &mut self,
15621        modifier: Option<ContextModifier>,
15622    ) -> Result<Statement, ParserError> {
15623        self.expect_keyword_is(Keyword::ROLE)?;
15624
15625        let role_name = if self.parse_keyword(Keyword::NONE) {
15626            None
15627        } else {
15628            Some(self.parse_identifier()?)
15629        };
15630        Ok(Statement::Set(Set::SetRole {
15631            context_modifier: modifier,
15632            role_name,
15633        }))
15634    }
15635
15636    fn parse_set_values(
15637        &mut self,
15638        parenthesized_assignment: bool,
15639    ) -> Result<Vec<Expr>, ParserError> {
15640        let mut values = vec![];
15641
15642        if parenthesized_assignment {
15643            self.expect_token(&Token::LParen)?;
15644        }
15645
15646        loop {
15647            let value = if let Some(expr) = self.try_parse_expr_sub_query()? {
15648                expr
15649            } else if let Ok(expr) = self.parse_expr() {
15650                expr
15651            } else {
15652                self.expected_ref("variable value", self.peek_token_ref())?
15653            };
15654
15655            values.push(value);
15656            if self.consume_token(&Token::Comma) {
15657                continue;
15658            }
15659
15660            if parenthesized_assignment {
15661                self.expect_token(&Token::RParen)?;
15662            }
15663            return Ok(values);
15664        }
15665    }
15666
15667    fn parse_context_modifier(&mut self) -> Option<ContextModifier> {
15668        let modifier =
15669            self.parse_one_of_keywords(&[Keyword::SESSION, Keyword::LOCAL, Keyword::GLOBAL])?;
15670
15671        Self::keyword_to_modifier(modifier)
15672    }
15673
15674    /// Parse a single SET statement assignment `var = expr`.
15675    fn parse_set_assignment(&mut self) -> Result<SetAssignment, ParserError> {
15676        let scope = self.parse_context_modifier();
15677
15678        let name = if self.dialect.supports_parenthesized_set_variables()
15679            && self.consume_token(&Token::LParen)
15680        {
15681            // Parenthesized assignments are handled in the `parse_set` function after
15682            // trying to parse list of assignments using this function.
15683            // If a dialect supports both, and we find a LParen, we early exit from this function.
15684            self.expected_ref("Unparenthesized assignment", self.peek_token_ref())?
15685        } else {
15686            self.parse_object_name(false)?
15687        };
15688
15689        if !(self.consume_token(&Token::Eq) || self.parse_keyword(Keyword::TO)) {
15690            return self.expected_ref("assignment operator", self.peek_token_ref());
15691        }
15692
15693        let value = self.parse_expr()?;
15694
15695        Ok(SetAssignment { scope, name, value })
15696    }
15697
15698    fn parse_set(&mut self) -> Result<Statement, ParserError> {
15699        let hivevar = self.parse_keyword(Keyword::HIVEVAR);
15700
15701        // Modifier is either HIVEVAR: or a ContextModifier (LOCAL, SESSION, etc), not both
15702        let scope = if !hivevar {
15703            self.parse_context_modifier()
15704        } else {
15705            None
15706        };
15707
15708        if hivevar {
15709            self.expect_token(&Token::Colon)?;
15710        }
15711
15712        if let Some(set_role_stmt) = self.maybe_parse(|parser| parser.parse_set_role(scope))? {
15713            return Ok(set_role_stmt);
15714        }
15715
15716        // Handle special cases first
15717        if self.parse_keywords(&[Keyword::TIME, Keyword::ZONE])
15718            || self.parse_keyword(Keyword::TIMEZONE)
15719        {
15720            if self.consume_token(&Token::Eq) || self.parse_keyword(Keyword::TO) {
15721                return Ok(Set::SingleAssignment {
15722                    scope,
15723                    hivevar,
15724                    variable: ObjectName::from(vec!["TIMEZONE".into()]),
15725                    values: self.parse_set_values(false)?,
15726                }
15727                .into());
15728            } else {
15729                // A shorthand alias for SET TIME ZONE that doesn't require
15730                // the assignment operator. It's originally PostgreSQL specific,
15731                // but we allow it for all the dialects
15732                return Ok(Set::SetTimeZone {
15733                    local: scope == Some(ContextModifier::Local),
15734                    value: self.parse_expr()?,
15735                }
15736                .into());
15737            }
15738        } else if self.dialect.supports_set_names() && self.parse_keyword(Keyword::NAMES) {
15739            if self.parse_keyword(Keyword::DEFAULT) {
15740                return Ok(Set::SetNamesDefault {}.into());
15741            }
15742            let charset_name = self.parse_identifier()?;
15743            let collation_name = if self.parse_one_of_keywords(&[Keyword::COLLATE]).is_some() {
15744                Some(self.parse_literal_string()?)
15745            } else {
15746                None
15747            };
15748
15749            return Ok(Set::SetNames {
15750                charset_name,
15751                collation_name,
15752            }
15753            .into());
15754        } else if self.parse_keyword(Keyword::CHARACTERISTICS) {
15755            self.expect_keywords(&[Keyword::AS, Keyword::TRANSACTION])?;
15756            return Ok(Set::SetTransaction {
15757                modes: self.parse_transaction_modes()?,
15758                snapshot: None,
15759                session: true,
15760            }
15761            .into());
15762        } else if self.parse_keyword(Keyword::TRANSACTION) {
15763            if self.parse_keyword(Keyword::SNAPSHOT) {
15764                let snapshot_id = self.parse_value()?;
15765                return Ok(Set::SetTransaction {
15766                    modes: vec![],
15767                    snapshot: Some(snapshot_id),
15768                    session: false,
15769                }
15770                .into());
15771            }
15772            return Ok(Set::SetTransaction {
15773                modes: self.parse_transaction_modes()?,
15774                snapshot: None,
15775                session: false,
15776            }
15777            .into());
15778        } else if self.parse_keyword(Keyword::AUTHORIZATION) {
15779            let scope = match scope {
15780                Some(s) => s,
15781                None => {
15782                    return self.expected_at(
15783                        "SESSION, LOCAL, or other scope modifier before AUTHORIZATION",
15784                        self.get_current_index(),
15785                    )
15786                }
15787            };
15788            let auth_value = if self.parse_keyword(Keyword::DEFAULT) {
15789                SetSessionAuthorizationParamKind::Default
15790            } else {
15791                let value = self.parse_identifier()?;
15792                SetSessionAuthorizationParamKind::User(value)
15793            };
15794            return Ok(Set::SetSessionAuthorization(SetSessionAuthorizationParam {
15795                scope,
15796                kind: auth_value,
15797            })
15798            .into());
15799        }
15800
15801        if self.dialect.supports_comma_separated_set_assignments() {
15802            if scope.is_some() {
15803                self.prev_token();
15804            }
15805
15806            if let Some(assignments) = self
15807                .maybe_parse(|parser| parser.parse_comma_separated(Parser::parse_set_assignment))?
15808            {
15809                return if assignments.len() > 1 {
15810                    Ok(Set::MultipleAssignments { assignments }.into())
15811                } else {
15812                    let SetAssignment { scope, name, value } =
15813                        assignments.into_iter().next().ok_or_else(|| {
15814                            ParserError::ParserError("Expected at least one assignment".to_string())
15815                        })?;
15816
15817                    Ok(Set::SingleAssignment {
15818                        scope,
15819                        hivevar,
15820                        variable: name,
15821                        values: vec![value],
15822                    }
15823                    .into())
15824                };
15825            }
15826        }
15827
15828        let variables = if self.dialect.supports_parenthesized_set_variables()
15829            && self.consume_token(&Token::LParen)
15830        {
15831            let vars = OneOrManyWithParens::Many(
15832                self.parse_comma_separated(|parser: &mut Parser<'a>| parser.parse_identifier())?
15833                    .into_iter()
15834                    .map(|ident| ObjectName::from(vec![ident]))
15835                    .collect(),
15836            );
15837            self.expect_token(&Token::RParen)?;
15838            vars
15839        } else {
15840            OneOrManyWithParens::One(self.parse_object_name(false)?)
15841        };
15842
15843        if self.consume_token(&Token::Eq) || self.parse_keyword(Keyword::TO) {
15844            let stmt = match variables {
15845                OneOrManyWithParens::One(var) => Set::SingleAssignment {
15846                    scope,
15847                    hivevar,
15848                    variable: var,
15849                    values: self.parse_set_values(false)?,
15850                },
15851                OneOrManyWithParens::Many(vars) => Set::ParenthesizedAssignments {
15852                    variables: vars,
15853                    values: self.parse_set_values(true)?,
15854                },
15855            };
15856
15857            return Ok(stmt.into());
15858        }
15859
15860        if self.dialect.supports_set_stmt_without_operator() {
15861            self.prev_token();
15862            return self.parse_set_session_params();
15863        };
15864
15865        self.expected_ref("equals sign or TO", self.peek_token_ref())
15866    }
15867
15868    /// Parse session parameter assignments after `SET` when no `=` or `TO` is present.
15869    pub fn parse_set_session_params(&mut self) -> Result<Statement, ParserError> {
15870        if self.parse_keyword(Keyword::STATISTICS) {
15871            let topic = match self.parse_one_of_keywords(&[
15872                Keyword::IO,
15873                Keyword::PROFILE,
15874                Keyword::TIME,
15875                Keyword::XML,
15876            ]) {
15877                Some(Keyword::IO) => SessionParamStatsTopic::IO,
15878                Some(Keyword::PROFILE) => SessionParamStatsTopic::Profile,
15879                Some(Keyword::TIME) => SessionParamStatsTopic::Time,
15880                Some(Keyword::XML) => SessionParamStatsTopic::Xml,
15881                _ => return self.expected_ref("IO, PROFILE, TIME or XML", self.peek_token_ref()),
15882            };
15883            let value = self.parse_session_param_value()?;
15884            Ok(
15885                Set::SetSessionParam(SetSessionParamKind::Statistics(SetSessionParamStatistics {
15886                    topic,
15887                    value,
15888                }))
15889                .into(),
15890            )
15891        } else if self.parse_keyword(Keyword::IDENTITY_INSERT) {
15892            let obj = self.parse_object_name(false)?;
15893            let value = self.parse_session_param_value()?;
15894            Ok(Set::SetSessionParam(SetSessionParamKind::IdentityInsert(
15895                SetSessionParamIdentityInsert { obj, value },
15896            ))
15897            .into())
15898        } else if self.parse_keyword(Keyword::OFFSETS) {
15899            let keywords = self.parse_comma_separated(|parser| {
15900                let next_token = parser.next_token();
15901                match &next_token.token {
15902                    Token::Word(w) => Ok(w.to_string()),
15903                    _ => parser.expected("SQL keyword", next_token),
15904                }
15905            })?;
15906            let value = self.parse_session_param_value()?;
15907            Ok(
15908                Set::SetSessionParam(SetSessionParamKind::Offsets(SetSessionParamOffsets {
15909                    keywords,
15910                    value,
15911                }))
15912                .into(),
15913            )
15914        } else {
15915            let names = self.parse_comma_separated(|parser| {
15916                let next_token = parser.next_token();
15917                match next_token.token {
15918                    Token::Word(w) => Ok(w.to_string()),
15919                    _ => parser.expected("Session param name", next_token),
15920                }
15921            })?;
15922            let value = self.parse_expr()?.to_string();
15923            Ok(
15924                Set::SetSessionParam(SetSessionParamKind::Generic(SetSessionParamGeneric {
15925                    names,
15926                    value,
15927                }))
15928                .into(),
15929            )
15930        }
15931    }
15932
15933    fn parse_session_param_value(&mut self) -> Result<SessionParamValue, ParserError> {
15934        if self.parse_keyword(Keyword::ON) {
15935            Ok(SessionParamValue::On)
15936        } else if self.parse_keyword(Keyword::OFF) {
15937            Ok(SessionParamValue::Off)
15938        } else {
15939            self.expected_ref("ON or OFF", self.peek_token_ref())
15940        }
15941    }
15942
15943    /// Parse a `SHOW` statement and dispatch to specific SHOW handlers.
15944    pub fn parse_show(&mut self) -> Result<Statement, ParserError> {
15945        let terse = self.parse_keyword(Keyword::TERSE);
15946        let extended = self.parse_keyword(Keyword::EXTENDED);
15947        let full = self.parse_keyword(Keyword::FULL);
15948        let session = self.parse_keyword(Keyword::SESSION);
15949        let global = self.parse_keyword(Keyword::GLOBAL);
15950        let external = self.parse_keyword(Keyword::EXTERNAL);
15951        if self
15952            .parse_one_of_keywords(&[Keyword::COLUMNS, Keyword::FIELDS])
15953            .is_some()
15954        {
15955            Ok(self.parse_show_columns(extended, full)?)
15956        } else if self.parse_keyword(Keyword::TABLES) {
15957            Ok(self.parse_show_tables(terse, extended, full, external)?)
15958        } else if self.parse_keywords(&[Keyword::MATERIALIZED, Keyword::VIEWS]) {
15959            Ok(self.parse_show_views(terse, true)?)
15960        } else if self.parse_keyword(Keyword::VIEWS) {
15961            Ok(self.parse_show_views(terse, false)?)
15962        } else if self.parse_keyword(Keyword::FUNCTIONS) {
15963            Ok(self.parse_show_functions()?)
15964        } else if self.parse_keyword(Keyword::PROCESSLIST) {
15965            Ok(Statement::ShowProcessList { full })
15966        } else if extended || full {
15967            Err(ParserError::ParserError(
15968                "EXTENDED/FULL are not supported with this type of SHOW query".to_string(),
15969            ))
15970        } else if self.parse_one_of_keywords(&[Keyword::CREATE]).is_some() {
15971            Ok(self.parse_show_create()?)
15972        } else if self.parse_keyword(Keyword::COLLATION) {
15973            Ok(self.parse_show_collation()?)
15974        } else if self.parse_keyword(Keyword::VARIABLES)
15975            && dialect_of!(self is MySqlDialect | GenericDialect)
15976        {
15977            Ok(Statement::ShowVariables {
15978                filter: self.parse_show_statement_filter()?,
15979                session,
15980                global,
15981            })
15982        } else if self.parse_keyword(Keyword::STATUS)
15983            && dialect_of!(self is MySqlDialect | GenericDialect)
15984        {
15985            Ok(Statement::ShowStatus {
15986                filter: self.parse_show_statement_filter()?,
15987                session,
15988                global,
15989            })
15990        } else if self.parse_keyword(Keyword::CATALOGS) {
15991            self.parse_show_catalogs(terse)
15992        } else if self.parse_keyword(Keyword::DATABASES) {
15993            self.parse_show_databases(terse)
15994        } else if self.parse_keyword(Keyword::SCHEMAS) {
15995            self.parse_show_schemas(terse)
15996        } else if self.parse_keywords(&[Keyword::CHARACTER, Keyword::SET]) {
15997            self.parse_show_charset(false)
15998        } else if self.parse_keyword(Keyword::CHARSET) {
15999            self.parse_show_charset(true)
16000        } else {
16001            Ok(Statement::ShowVariable {
16002                variable: self.parse_identifiers()?,
16003            })
16004        }
16005    }
16006
16007    fn parse_show_charset(&mut self, is_shorthand: bool) -> Result<Statement, ParserError> {
16008        // parse one of keywords
16009        Ok(Statement::ShowCharset(ShowCharset {
16010            is_shorthand,
16011            filter: self.parse_show_statement_filter()?,
16012        }))
16013    }
16014
16015    fn parse_show_catalogs(&mut self, terse: bool) -> Result<Statement, ParserError> {
16016        let history = self.parse_keyword(Keyword::HISTORY);
16017        let show_options = self.parse_show_stmt_options()?;
16018        Ok(Statement::ShowCatalogs {
16019            terse,
16020            history,
16021            show_options,
16022        })
16023    }
16024
16025    fn parse_show_databases(&mut self, terse: bool) -> Result<Statement, ParserError> {
16026        let history = self.parse_keyword(Keyword::HISTORY);
16027        let show_options = self.parse_show_stmt_options()?;
16028        Ok(Statement::ShowDatabases {
16029            terse,
16030            history,
16031            show_options,
16032        })
16033    }
16034
16035    fn parse_show_schemas(&mut self, terse: bool) -> Result<Statement, ParserError> {
16036        let history = self.parse_keyword(Keyword::HISTORY);
16037        let show_options = self.parse_show_stmt_options()?;
16038        Ok(Statement::ShowSchemas {
16039            terse,
16040            history,
16041            show_options,
16042        })
16043    }
16044
16045    /// Parse `SHOW CREATE <object>` returning the corresponding `ShowCreate` statement.
16046    pub fn parse_show_create(&mut self) -> Result<Statement, ParserError> {
16047        let obj_type = match self.expect_one_of_keywords(&[
16048            Keyword::TABLE,
16049            Keyword::TRIGGER,
16050            Keyword::FUNCTION,
16051            Keyword::PROCEDURE,
16052            Keyword::EVENT,
16053            Keyword::VIEW,
16054        ])? {
16055            Keyword::TABLE => Ok(ShowCreateObject::Table),
16056            Keyword::TRIGGER => Ok(ShowCreateObject::Trigger),
16057            Keyword::FUNCTION => Ok(ShowCreateObject::Function),
16058            Keyword::PROCEDURE => Ok(ShowCreateObject::Procedure),
16059            Keyword::EVENT => Ok(ShowCreateObject::Event),
16060            Keyword::VIEW => Ok(ShowCreateObject::View),
16061            keyword => Err(ParserError::ParserError(format!(
16062                "Unable to map keyword to ShowCreateObject: {keyword:?}"
16063            ))),
16064        }?;
16065
16066        let obj_name = self.parse_object_name(false)?;
16067
16068        Ok(Statement::ShowCreate { obj_type, obj_name })
16069    }
16070
16071    /// Parse `SHOW COLUMNS`/`SHOW FIELDS` and return a `ShowColumns` statement.
16072    pub fn parse_show_columns(
16073        &mut self,
16074        extended: bool,
16075        full: bool,
16076    ) -> Result<Statement, ParserError> {
16077        let show_options = self.parse_show_stmt_options()?;
16078        Ok(Statement::ShowColumns {
16079            extended,
16080            full,
16081            show_options,
16082        })
16083    }
16084
16085    fn parse_show_tables(
16086        &mut self,
16087        terse: bool,
16088        extended: bool,
16089        full: bool,
16090        external: bool,
16091    ) -> Result<Statement, ParserError> {
16092        let history = !external && self.parse_keyword(Keyword::HISTORY);
16093        let show_options = self.parse_show_stmt_options()?;
16094        Ok(Statement::ShowTables {
16095            terse,
16096            history,
16097            extended,
16098            full,
16099            external,
16100            show_options,
16101        })
16102    }
16103
16104    fn parse_show_views(
16105        &mut self,
16106        terse: bool,
16107        materialized: bool,
16108    ) -> Result<Statement, ParserError> {
16109        let show_options = self.parse_show_stmt_options()?;
16110        Ok(Statement::ShowViews {
16111            materialized,
16112            terse,
16113            show_options,
16114        })
16115    }
16116
16117    /// Parse `SHOW FUNCTIONS` and optional filter.
16118    pub fn parse_show_functions(&mut self) -> Result<Statement, ParserError> {
16119        let filter = self.parse_show_statement_filter()?;
16120        Ok(Statement::ShowFunctions { filter })
16121    }
16122
16123    /// Parse `SHOW COLLATION` and optional filter.
16124    pub fn parse_show_collation(&mut self) -> Result<Statement, ParserError> {
16125        let filter = self.parse_show_statement_filter()?;
16126        Ok(Statement::ShowCollation { filter })
16127    }
16128
16129    /// Parse an optional filter used by `SHOW` statements (LIKE, ILIKE, WHERE, or literal).
16130    pub fn parse_show_statement_filter(
16131        &mut self,
16132    ) -> Result<Option<ShowStatementFilter>, ParserError> {
16133        if self.parse_keyword(Keyword::LIKE) {
16134            Ok(Some(ShowStatementFilter::Like(
16135                self.parse_literal_string()?,
16136            )))
16137        } else if self.parse_keyword(Keyword::ILIKE) {
16138            Ok(Some(ShowStatementFilter::ILike(
16139                self.parse_literal_string()?,
16140            )))
16141        } else if self.parse_keyword(Keyword::WHERE) {
16142            Ok(Some(ShowStatementFilter::Where(self.parse_expr()?)))
16143        } else {
16144            self.maybe_parse(|parser| -> Result<String, ParserError> {
16145                parser.parse_literal_string()
16146            })?
16147            .map_or(Ok(None), |filter| {
16148                Ok(Some(ShowStatementFilter::NoKeyword(filter)))
16149            })
16150        }
16151    }
16152
16153    /// Parse a `USE` statement (database/catalog/schema/warehouse/role selection).
16154    pub fn parse_use(&mut self) -> Result<Statement, ParserError> {
16155        // Determine which keywords are recognized by the current dialect
16156        let parsed_keyword = if dialect_of!(self is HiveDialect) {
16157            // HiveDialect accepts USE DEFAULT; statement without any db specified
16158            if self.parse_keyword(Keyword::DEFAULT) {
16159                return Ok(Statement::Use(Use::Default));
16160            }
16161            None // HiveDialect doesn't expect any other specific keyword after `USE`
16162        } else if dialect_of!(self is DatabricksDialect) {
16163            self.parse_one_of_keywords(&[Keyword::CATALOG, Keyword::DATABASE, Keyword::SCHEMA])
16164        } else if dialect_of!(self is SnowflakeDialect) {
16165            self.parse_one_of_keywords(&[
16166                Keyword::DATABASE,
16167                Keyword::SCHEMA,
16168                Keyword::WAREHOUSE,
16169                Keyword::ROLE,
16170                Keyword::SECONDARY,
16171            ])
16172        } else {
16173            None // No specific keywords for other dialects, including GenericDialect
16174        };
16175
16176        let result = if matches!(parsed_keyword, Some(Keyword::SECONDARY)) {
16177            self.parse_secondary_roles()?
16178        } else {
16179            let obj_name = self.parse_object_name(false)?;
16180            match parsed_keyword {
16181                Some(Keyword::CATALOG) => Use::Catalog(obj_name),
16182                Some(Keyword::DATABASE) => Use::Database(obj_name),
16183                Some(Keyword::SCHEMA) => Use::Schema(obj_name),
16184                Some(Keyword::WAREHOUSE) => Use::Warehouse(obj_name),
16185                Some(Keyword::ROLE) => Use::Role(obj_name),
16186                _ => Use::Object(obj_name),
16187            }
16188        };
16189
16190        Ok(Statement::Use(result))
16191    }
16192
16193    fn parse_secondary_roles(&mut self) -> Result<Use, ParserError> {
16194        self.expect_one_of_keywords(&[Keyword::ROLES, Keyword::ROLE])?;
16195        if self.parse_keyword(Keyword::NONE) {
16196            Ok(Use::SecondaryRoles(SecondaryRoles::None))
16197        } else if self.parse_keyword(Keyword::ALL) {
16198            Ok(Use::SecondaryRoles(SecondaryRoles::All))
16199        } else {
16200            let roles = self.parse_comma_separated(|parser| parser.parse_identifier())?;
16201            Ok(Use::SecondaryRoles(SecondaryRoles::List(roles)))
16202        }
16203    }
16204
16205    /// Parse a table factor followed by any join clauses, returning `TableWithJoins`.
16206    pub fn parse_table_and_joins(&mut self) -> Result<TableWithJoins, ParserError> {
16207        let relation = self.parse_table_factor()?;
16208        // Note that for keywords to be properly handled here, they need to be
16209        // added to `RESERVED_FOR_TABLE_ALIAS`, otherwise they may be parsed as
16210        // a table alias.
16211        let joins = self.parse_joins()?;
16212        Ok(TableWithJoins { relation, joins })
16213    }
16214
16215    fn parse_joins(&mut self) -> Result<Vec<Join>, ParserError> {
16216        let mut joins = vec![];
16217        loop {
16218            let global = self.parse_keyword(Keyword::GLOBAL);
16219            let join = if self.parse_keyword(Keyword::CROSS) {
16220                let join_operator = if self.parse_keyword(Keyword::JOIN) {
16221                    JoinOperator::CrossJoin(JoinConstraint::None)
16222                } else if self.parse_keyword(Keyword::APPLY) {
16223                    // MSSQL extension, similar to CROSS JOIN LATERAL
16224                    JoinOperator::CrossApply
16225                } else {
16226                    return self.expected_ref("JOIN or APPLY after CROSS", self.peek_token_ref());
16227                };
16228                let relation = self.parse_table_factor()?;
16229                let join_operator = if matches!(join_operator, JoinOperator::CrossJoin(_))
16230                    && self.dialect.supports_cross_join_constraint()
16231                {
16232                    let constraint = self.parse_join_constraint(false)?;
16233                    JoinOperator::CrossJoin(constraint)
16234                } else {
16235                    join_operator
16236                };
16237                Join {
16238                    relation,
16239                    global,
16240                    join_operator,
16241                }
16242            } else if self.parse_keyword(Keyword::OUTER) {
16243                // MSSQL extension, similar to LEFT JOIN LATERAL .. ON 1=1
16244                self.expect_keyword_is(Keyword::APPLY)?;
16245                Join {
16246                    relation: self.parse_table_factor()?,
16247                    global,
16248                    join_operator: JoinOperator::OuterApply,
16249                }
16250            } else if self.parse_keyword(Keyword::ASOF) {
16251                self.expect_keyword_is(Keyword::JOIN)?;
16252                let relation = self.parse_table_factor()?;
16253                self.expect_keyword_is(Keyword::MATCH_CONDITION)?;
16254                let match_condition = self.parse_parenthesized(Self::parse_expr)?;
16255                Join {
16256                    relation,
16257                    global,
16258                    join_operator: JoinOperator::AsOf {
16259                        match_condition,
16260                        constraint: self.parse_join_constraint(false)?,
16261                    },
16262                }
16263            } else if self.dialect.supports_array_join_syntax()
16264                && self.parse_keywords(&[Keyword::INNER, Keyword::ARRAY, Keyword::JOIN])
16265            {
16266                // ClickHouse: INNER ARRAY JOIN
16267                Join {
16268                    relation: self.parse_table_factor()?,
16269                    global,
16270                    join_operator: JoinOperator::InnerArrayJoin,
16271                }
16272            } else if self.dialect.supports_array_join_syntax()
16273                && self.parse_keywords(&[Keyword::LEFT, Keyword::ARRAY, Keyword::JOIN])
16274            {
16275                // ClickHouse: LEFT ARRAY JOIN
16276                Join {
16277                    relation: self.parse_table_factor()?,
16278                    global,
16279                    join_operator: JoinOperator::LeftArrayJoin,
16280                }
16281            } else if self.dialect.supports_array_join_syntax()
16282                && self.parse_keywords(&[Keyword::ARRAY, Keyword::JOIN])
16283            {
16284                // ClickHouse: ARRAY JOIN
16285                Join {
16286                    relation: self.parse_table_factor()?,
16287                    global,
16288                    join_operator: JoinOperator::ArrayJoin,
16289                }
16290            } else {
16291                let natural = self.parse_keyword(Keyword::NATURAL);
16292                let peek_keyword = if let Token::Word(w) = &self.peek_token_ref().token {
16293                    w.keyword
16294                } else {
16295                    Keyword::NoKeyword
16296                };
16297
16298                let join_operator_type = match peek_keyword {
16299                    Keyword::INNER | Keyword::JOIN => {
16300                        let inner = self.parse_keyword(Keyword::INNER); // [ INNER ]
16301                        self.expect_keyword_is(Keyword::JOIN)?;
16302                        if inner {
16303                            JoinOperator::Inner
16304                        } else {
16305                            JoinOperator::Join
16306                        }
16307                    }
16308                    kw @ Keyword::LEFT | kw @ Keyword::RIGHT => {
16309                        let _ = self.next_token(); // consume LEFT/RIGHT
16310                        let is_left = kw == Keyword::LEFT;
16311                        let join_type = self.parse_one_of_keywords(&[
16312                            Keyword::OUTER,
16313                            Keyword::SEMI,
16314                            Keyword::ANTI,
16315                            Keyword::JOIN,
16316                        ]);
16317                        match join_type {
16318                            Some(Keyword::OUTER) => {
16319                                self.expect_keyword_is(Keyword::JOIN)?;
16320                                if is_left {
16321                                    JoinOperator::LeftOuter
16322                                } else {
16323                                    JoinOperator::RightOuter
16324                                }
16325                            }
16326                            Some(Keyword::SEMI) => {
16327                                self.expect_keyword_is(Keyword::JOIN)?;
16328                                if is_left {
16329                                    JoinOperator::LeftSemi
16330                                } else {
16331                                    JoinOperator::RightSemi
16332                                }
16333                            }
16334                            Some(Keyword::ANTI) => {
16335                                self.expect_keyword_is(Keyword::JOIN)?;
16336                                if is_left {
16337                                    JoinOperator::LeftAnti
16338                                } else {
16339                                    JoinOperator::RightAnti
16340                                }
16341                            }
16342                            Some(Keyword::JOIN) => {
16343                                if is_left {
16344                                    JoinOperator::Left
16345                                } else {
16346                                    JoinOperator::Right
16347                                }
16348                            }
16349                            _ => {
16350                                return Err(ParserError::ParserError(format!(
16351                                    "expected OUTER, SEMI, ANTI or JOIN after {kw:?}"
16352                                )))
16353                            }
16354                        }
16355                    }
16356                    Keyword::ANTI => {
16357                        let _ = self.next_token(); // consume ANTI
16358                        self.expect_keyword_is(Keyword::JOIN)?;
16359                        JoinOperator::Anti
16360                    }
16361                    Keyword::SEMI => {
16362                        let _ = self.next_token(); // consume SEMI
16363                        self.expect_keyword_is(Keyword::JOIN)?;
16364                        JoinOperator::Semi
16365                    }
16366                    Keyword::FULL => {
16367                        let _ = self.next_token(); // consume FULL
16368                        let _ = self.parse_keyword(Keyword::OUTER); // [ OUTER ]
16369                        self.expect_keyword_is(Keyword::JOIN)?;
16370                        JoinOperator::FullOuter
16371                    }
16372                    Keyword::OUTER => {
16373                        return self.expected_ref("LEFT, RIGHT, or FULL", self.peek_token_ref());
16374                    }
16375                    Keyword::STRAIGHT_JOIN => {
16376                        let _ = self.next_token(); // consume STRAIGHT_JOIN
16377                        JoinOperator::StraightJoin
16378                    }
16379                    _ if natural => {
16380                        return self
16381                            .expected_ref("a join type after NATURAL", self.peek_token_ref());
16382                    }
16383                    _ => break,
16384                };
16385                let mut relation = self.parse_table_factor()?;
16386
16387                if !self
16388                    .dialect
16389                    .supports_left_associative_joins_without_parens()
16390                    && !natural
16391                    && self.peek_parens_less_nested_join()
16392                {
16393                    let joins = self.parse_joins()?;
16394                    relation = TableFactor::NestedJoin {
16395                        table_with_joins: Box::new(TableWithJoins { relation, joins }),
16396                        alias: None,
16397                    };
16398                }
16399
16400                let join_constraint = self.parse_join_constraint(natural)?;
16401                Join {
16402                    relation,
16403                    global,
16404                    join_operator: join_operator_type(join_constraint),
16405                }
16406            };
16407            joins.push(join);
16408        }
16409        Ok(joins)
16410    }
16411
16412    fn peek_parens_less_nested_join(&self) -> bool {
16413        matches!(
16414            self.peek_token_ref().token,
16415            Token::Word(Word {
16416                keyword: Keyword::JOIN
16417                    | Keyword::INNER
16418                    | Keyword::LEFT
16419                    | Keyword::RIGHT
16420                    | Keyword::FULL,
16421                ..
16422            })
16423        )
16424    }
16425
16426    /// A table name or a parenthesized subquery, followed by optional `[AS] alias`
16427    #[cfg_attr(feature = "recursive-protection", recursive::recursive)]
16428    pub fn parse_table_factor(&mut self) -> Result<TableFactor, ParserError> {
16429        let _guard = self.recursion_counter.try_decrease()?;
16430        if self.parse_keyword(Keyword::LATERAL) {
16431            // LATERAL must always be followed by a subquery or table function.
16432            if self.consume_token(&Token::LParen) {
16433                self.parse_derived_table_factor(Lateral)
16434            } else {
16435                let name = self.parse_object_name(false)?;
16436                self.expect_token(&Token::LParen)?;
16437                let args = self.parse_optional_args()?;
16438                let with_ordinality = self.parse_keywords(&[Keyword::WITH, Keyword::ORDINALITY]);
16439                let alias = self.maybe_parse_table_alias()?;
16440                Ok(TableFactor::Function {
16441                    lateral: true,
16442                    name,
16443                    args,
16444                    with_ordinality,
16445                    alias,
16446                })
16447            }
16448        } else if self.parse_keyword(Keyword::TABLE) {
16449            // parse table function (SELECT * FROM TABLE (<expr>) [ AS <alias> ])
16450            self.expect_token(&Token::LParen)?;
16451            let expr = self.parse_expr()?;
16452            self.expect_token(&Token::RParen)?;
16453            let alias = self.maybe_parse_table_alias()?;
16454            Ok(TableFactor::TableFunction { expr, alias })
16455        } else if self.consume_token(&Token::LParen) {
16456            // A left paren introduces either a derived table (i.e., a subquery)
16457            // or a nested join. It's nearly impossible to determine ahead of
16458            // time which it is... so we just try to parse both.
16459            //
16460            // Here's an example that demonstrates the complexity:
16461            //                     /-------------------------------------------------------\
16462            //                     | /-----------------------------------\                 |
16463            //     SELECT * FROM ( ( ( (SELECT 1) UNION (SELECT 2) ) AS t1 NATURAL JOIN t2 ) )
16464            //                   ^ ^ ^ ^
16465            //                   | | | |
16466            //                   | | | |
16467            //                   | | | (4) belongs to a SetExpr::Query inside the subquery
16468            //                   | | (3) starts a derived table (subquery)
16469            //                   | (2) starts a nested join
16470            //                   (1) an additional set of parens around a nested join
16471            //
16472
16473            // If the recently consumed '(' starts a derived table, the call to
16474            // `parse_derived_table_factor` below will return success after parsing the
16475            // subquery, followed by the closing ')', and the alias of the derived table.
16476            // In the example above this is case (3).
16477            //
16478            // Memoize failures to break the 2^N work on inputs like
16479            // `FROM ((((...`, where the nested-join fallback recurses back into
16480            // `parse_table_factor` and re-attempts the same speculative parse.
16481            let derived_pos = self.index;
16482            let derived = if self
16483                .failed_derived_table_factor_positions
16484                .contains(&derived_pos)
16485            {
16486                None
16487            } else {
16488                match self.maybe_parse(|parser| parser.parse_derived_table_factor(NotLateral))? {
16489                    Some(t) => Some(t),
16490                    None => {
16491                        self.failed_derived_table_factor_positions
16492                            .insert(derived_pos);
16493                        None
16494                    }
16495                }
16496            };
16497            if let Some(mut table) = derived {
16498                while let Some(kw) = self.parse_one_of_keywords(&[Keyword::PIVOT, Keyword::UNPIVOT])
16499                {
16500                    table = match kw {
16501                        Keyword::PIVOT => self.parse_pivot_table_factor(table)?,
16502                        Keyword::UNPIVOT => self.parse_unpivot_table_factor(table)?,
16503                        unexpected_keyword => return Err(ParserError::ParserError(
16504                            format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in pivot/unpivot"),
16505                        )),
16506                    }
16507                }
16508                return Ok(table);
16509            }
16510
16511            // A parsing error from `parse_derived_table_factor` indicates that the '(' we've
16512            // recently consumed does not start a derived table (cases 1, 2, or 4).
16513            // `maybe_parse` will ignore such an error and rewind to be after the opening '('.
16514
16515            // Inside the parentheses we expect to find an (A) table factor
16516            // followed by some joins or (B) another level of nesting.
16517            let mut table_and_joins = self.parse_table_and_joins()?;
16518
16519            #[allow(clippy::if_same_then_else)]
16520            if !table_and_joins.joins.is_empty() {
16521                self.expect_token(&Token::RParen)?;
16522                let alias = self.maybe_parse_table_alias()?;
16523                Ok(TableFactor::NestedJoin {
16524                    table_with_joins: Box::new(table_and_joins),
16525                    alias,
16526                }) // (A)
16527            } else if let TableFactor::NestedJoin {
16528                table_with_joins: _,
16529                alias: _,
16530            } = &table_and_joins.relation
16531            {
16532                // (B): `table_and_joins` (what we found inside the parentheses)
16533                // is a nested join `(foo JOIN bar)`, not followed by other joins.
16534                self.expect_token(&Token::RParen)?;
16535                let alias = self.maybe_parse_table_alias()?;
16536                Ok(TableFactor::NestedJoin {
16537                    table_with_joins: Box::new(table_and_joins),
16538                    alias,
16539                })
16540            } else if self.dialect.supports_parens_around_table_factor() {
16541                // Dialect-specific behavior: Snowflake diverges from the
16542                // standard and from most of the other implementations by
16543                // allowing extra parentheses not only around a join (B), but
16544                // around lone table names (e.g. `FROM (mytable [AS alias])`)
16545                // and around derived tables (e.g. `FROM ((SELECT ...)
16546                // [AS alias])`) as well.
16547                self.expect_token(&Token::RParen)?;
16548
16549                if let Some(outer_alias) = self.maybe_parse_table_alias()? {
16550                    // Snowflake also allows specifying an alias *after* parens
16551                    // e.g. `FROM (mytable) AS alias`
16552                    match &mut table_and_joins.relation {
16553                        TableFactor::Derived { alias, .. }
16554                        | TableFactor::Table { alias, .. }
16555                        | TableFactor::Function { alias, .. }
16556                        | TableFactor::UNNEST { alias, .. }
16557                        | TableFactor::JsonTable { alias, .. }
16558                        | TableFactor::XmlTable { alias, .. }
16559                        | TableFactor::OpenJsonTable { alias, .. }
16560                        | TableFactor::TableFunction { alias, .. }
16561                        | TableFactor::Pivot { alias, .. }
16562                        | TableFactor::Unpivot { alias, .. }
16563                        | TableFactor::MatchRecognize { alias, .. }
16564                        | TableFactor::SemanticView { alias, .. }
16565                        | TableFactor::NestedJoin { alias, .. } => {
16566                            // but not `FROM (mytable AS alias1) AS alias2`.
16567                            if let Some(inner_alias) = alias {
16568                                return Err(ParserError::ParserError(format!(
16569                                    "duplicate alias {inner_alias}"
16570                                )));
16571                            }
16572                            // Act as if the alias was specified normally next
16573                            // to the table name: `(mytable) AS alias` ->
16574                            // `(mytable AS alias)`
16575                            alias.replace(outer_alias);
16576                        }
16577                    };
16578                }
16579                // Do not store the extra set of parens in the AST
16580                Ok(table_and_joins.relation)
16581            } else {
16582                // The SQL spec prohibits derived tables and bare tables from
16583                // appearing alone in parentheses (e.g. `FROM (mytable)`)
16584                self.expected_ref("joined table", self.peek_token_ref())
16585            }
16586        } else if self.dialect.supports_values_as_table_factor()
16587            && matches!(
16588                self.peek_tokens(),
16589                [
16590                    Token::Word(Word {
16591                        keyword: Keyword::VALUES,
16592                        ..
16593                    }),
16594                    Token::LParen
16595                ]
16596            )
16597        {
16598            self.expect_keyword_is(Keyword::VALUES)?;
16599
16600            // Snowflake and Databricks allow syntax like below:
16601            // SELECT * FROM VALUES (1, 'a'), (2, 'b') AS t (col1, col2)
16602            // where there are no parentheses around the VALUES clause.
16603            let values = SetExpr::Values(self.parse_values(false, false)?);
16604            let alias = self.maybe_parse_table_alias()?;
16605            Ok(TableFactor::Derived {
16606                lateral: false,
16607                subquery: Box::new(Query {
16608                    with: None,
16609                    body: Box::new(values),
16610                    order_by: None,
16611                    limit_clause: None,
16612                    fetch: None,
16613                    locks: vec![],
16614                    for_clause: None,
16615                    settings: None,
16616                    format_clause: None,
16617                    pipe_operators: vec![],
16618                }),
16619                alias,
16620                sample: None,
16621            })
16622        } else if dialect_of!(self is BigQueryDialect | PostgreSqlDialect | GenericDialect)
16623            && self.parse_keyword(Keyword::UNNEST)
16624        {
16625            self.expect_token(&Token::LParen)?;
16626            let array_exprs = self.parse_comma_separated(Parser::parse_expr)?;
16627            self.expect_token(&Token::RParen)?;
16628
16629            let with_ordinality = self.parse_keywords(&[Keyword::WITH, Keyword::ORDINALITY]);
16630            let alias = match self.maybe_parse_table_alias() {
16631                Ok(Some(alias)) => Some(alias),
16632                Ok(None) => None,
16633                Err(e) => return Err(e),
16634            };
16635
16636            let with_offset = match self.expect_keywords(&[Keyword::WITH, Keyword::OFFSET]) {
16637                Ok(()) => true,
16638                Err(_) => false,
16639            };
16640
16641            let with_offset_alias = if with_offset {
16642                match self.parse_optional_alias(keywords::RESERVED_FOR_COLUMN_ALIAS) {
16643                    Ok(Some(alias)) => Some(alias),
16644                    Ok(None) => None,
16645                    Err(e) => return Err(e),
16646                }
16647            } else {
16648                None
16649            };
16650
16651            Ok(TableFactor::UNNEST {
16652                alias,
16653                array_exprs,
16654                with_offset,
16655                with_offset_alias,
16656                with_ordinality,
16657            })
16658        } else if self.parse_keyword_with_tokens(Keyword::JSON_TABLE, &[Token::LParen]) {
16659            let json_expr = self.parse_expr()?;
16660            self.expect_token(&Token::Comma)?;
16661            let json_path = self.parse_value()?;
16662            self.expect_keyword_is(Keyword::COLUMNS)?;
16663            self.expect_token(&Token::LParen)?;
16664            let columns = self.parse_comma_separated(Parser::parse_json_table_column_def)?;
16665            self.expect_token(&Token::RParen)?;
16666            self.expect_token(&Token::RParen)?;
16667            let alias = self.maybe_parse_table_alias()?;
16668            Ok(TableFactor::JsonTable {
16669                json_expr,
16670                json_path,
16671                columns,
16672                alias,
16673            })
16674        } else if self.parse_keyword_with_tokens(Keyword::OPENJSON, &[Token::LParen]) {
16675            self.prev_token();
16676            self.parse_open_json_table_factor()
16677        } else if self.parse_keyword_with_tokens(Keyword::XMLTABLE, &[Token::LParen]) {
16678            self.prev_token();
16679            self.parse_xml_table_factor()
16680        } else if self.dialect.supports_semantic_view_table_factor()
16681            && self.peek_keyword_with_tokens(Keyword::SEMANTIC_VIEW, &[Token::LParen])
16682        {
16683            self.parse_semantic_view_table_factor()
16684        } else if self.peek_token_ref().token == Token::AtSign {
16685            // Stage reference: @mystage or @namespace.stage (e.g. Snowflake)
16686            self.parse_snowflake_stage_table_factor()
16687        } else {
16688            let name = self.parse_object_name(true)?;
16689
16690            let json_path = match &self.peek_token_ref().token {
16691                Token::LBracket if self.dialect.supports_partiql() => Some(self.parse_json_path()?),
16692                _ => None,
16693            };
16694
16695            let partitions: Vec<Ident> = if dialect_of!(self is MySqlDialect | GenericDialect)
16696                && self.parse_keyword(Keyword::PARTITION)
16697            {
16698                self.parse_parenthesized_identifiers()?
16699            } else {
16700                vec![]
16701            };
16702
16703            // Parse potential version qualifier
16704            let version = self.maybe_parse_table_version()?;
16705
16706            // Postgres, MSSQL, ClickHouse: table-valued functions:
16707            let args = if self.consume_token(&Token::LParen) {
16708                Some(self.parse_table_function_args()?)
16709            } else {
16710                None
16711            };
16712
16713            let with_ordinality = self.parse_keywords(&[Keyword::WITH, Keyword::ORDINALITY]);
16714
16715            let mut sample = None;
16716            if self.dialect.supports_table_sample_before_alias() {
16717                if let Some(parsed_sample) = self.maybe_parse_table_sample()? {
16718                    sample = Some(TableSampleKind::BeforeTableAlias(parsed_sample));
16719                }
16720            }
16721
16722            let alias = self.maybe_parse_table_alias()?;
16723
16724            // MYSQL-specific table hints:
16725            let index_hints = if self.dialect.supports_table_hints() {
16726                self.maybe_parse(|p| p.parse_table_index_hints())?
16727                    .unwrap_or(vec![])
16728            } else {
16729                vec![]
16730            };
16731
16732            // MSSQL-specific table hints:
16733            let mut with_hints = vec![];
16734            if self.parse_keyword(Keyword::WITH) {
16735                if self.consume_token(&Token::LParen) {
16736                    with_hints = self.parse_comma_separated(Parser::parse_expr)?;
16737                    self.expect_token(&Token::RParen)?;
16738                } else {
16739                    // rewind, as WITH may belong to the next statement's CTE
16740                    self.prev_token();
16741                }
16742            };
16743
16744            if !self.dialect.supports_table_sample_before_alias() {
16745                if let Some(parsed_sample) = self.maybe_parse_table_sample()? {
16746                    sample = Some(TableSampleKind::AfterTableAlias(parsed_sample));
16747                }
16748            }
16749
16750            let mut table = TableFactor::Table {
16751                name,
16752                alias,
16753                args,
16754                with_hints,
16755                version,
16756                partitions,
16757                with_ordinality,
16758                json_path,
16759                sample,
16760                index_hints,
16761            };
16762
16763            while let Some(kw) = self.parse_one_of_keywords(&[Keyword::PIVOT, Keyword::UNPIVOT]) {
16764                table = match kw {
16765                    Keyword::PIVOT => self.parse_pivot_table_factor(table)?,
16766                    Keyword::UNPIVOT => self.parse_unpivot_table_factor(table)?,
16767                    unexpected_keyword => return Err(ParserError::ParserError(
16768                        format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in pivot/unpivot"),
16769                    )),
16770                }
16771            }
16772
16773            if self.dialect.supports_match_recognize()
16774                && self.parse_keyword(Keyword::MATCH_RECOGNIZE)
16775            {
16776                table = self.parse_match_recognize(table)?;
16777            }
16778
16779            Ok(table)
16780        }
16781    }
16782
16783    /// Parse a Snowflake stage reference as a table factor.
16784    /// Handles syntax like: `@mystage1 (file_format => 'myformat', pattern => '...')`
16785    ///
16786    /// See: <https://docs.snowflake.com/en/user-guide/querying-stage>
16787    fn parse_snowflake_stage_table_factor(&mut self) -> Result<TableFactor, ParserError> {
16788        // Parse the stage name starting with @
16789        let name = crate::dialect::parse_snowflake_stage_name(self)?;
16790
16791        // Parse optional stage options like (file_format => 'myformat', pattern => '...')
16792        let args = if self.consume_token(&Token::LParen) {
16793            Some(self.parse_table_function_args()?)
16794        } else {
16795            None
16796        };
16797
16798        let alias = self.maybe_parse_table_alias()?;
16799
16800        Ok(TableFactor::Table {
16801            name,
16802            alias,
16803            args,
16804            with_hints: vec![],
16805            version: None,
16806            partitions: vec![],
16807            with_ordinality: false,
16808            json_path: None,
16809            sample: None,
16810            index_hints: vec![],
16811        })
16812    }
16813
16814    fn maybe_parse_table_sample(&mut self) -> Result<Option<Box<TableSample>>, ParserError> {
16815        let modifier = if self.parse_keyword(Keyword::TABLESAMPLE) {
16816            TableSampleModifier::TableSample
16817        } else if self.parse_keyword(Keyword::SAMPLE) {
16818            TableSampleModifier::Sample
16819        } else {
16820            return Ok(None);
16821        };
16822        self.parse_table_sample(modifier).map(Some)
16823    }
16824
16825    fn parse_table_sample(
16826        &mut self,
16827        modifier: TableSampleModifier,
16828    ) -> Result<Box<TableSample>, ParserError> {
16829        let name = match self.parse_one_of_keywords(&[
16830            Keyword::BERNOULLI,
16831            Keyword::ROW,
16832            Keyword::SYSTEM,
16833            Keyword::BLOCK,
16834        ]) {
16835            Some(Keyword::BERNOULLI) => Some(TableSampleMethod::Bernoulli),
16836            Some(Keyword::ROW) => Some(TableSampleMethod::Row),
16837            Some(Keyword::SYSTEM) => Some(TableSampleMethod::System),
16838            Some(Keyword::BLOCK) => Some(TableSampleMethod::Block),
16839            _ => None,
16840        };
16841
16842        let parenthesized = self.consume_token(&Token::LParen);
16843
16844        let (quantity, bucket) = if parenthesized && self.parse_keyword(Keyword::BUCKET) {
16845            let selected_bucket = self.parse_number_value()?;
16846            self.expect_keywords(&[Keyword::OUT, Keyword::OF])?;
16847            let total = self.parse_number_value()?;
16848            let on = if self.parse_keyword(Keyword::ON) {
16849                Some(self.parse_expr()?)
16850            } else {
16851                None
16852            };
16853            (
16854                None,
16855                Some(TableSampleBucket {
16856                    bucket: selected_bucket,
16857                    total,
16858                    on,
16859                }),
16860            )
16861        } else {
16862            let value = match self.maybe_parse(|p| p.parse_expr())? {
16863                Some(num) => num,
16864                None => {
16865                    let next_token = self.next_token();
16866                    if let Token::Word(w) = next_token.token {
16867                        Expr::Value(Value::Placeholder(w.value).with_span(next_token.span))
16868                    } else {
16869                        return parser_err!(
16870                            "Expecting number or byte length e.g. 100M",
16871                            self.peek_token_ref().span.start
16872                        );
16873                    }
16874                }
16875            };
16876            let unit = if self.parse_keyword(Keyword::ROWS) {
16877                Some(TableSampleUnit::Rows)
16878            } else if self.parse_keyword(Keyword::PERCENT) {
16879                Some(TableSampleUnit::Percent)
16880            } else {
16881                None
16882            };
16883            (
16884                Some(TableSampleQuantity {
16885                    parenthesized,
16886                    value,
16887                    unit,
16888                }),
16889                None,
16890            )
16891        };
16892        if parenthesized {
16893            self.expect_token(&Token::RParen)?;
16894        }
16895
16896        let seed = if self.parse_keyword(Keyword::REPEATABLE) {
16897            Some(self.parse_table_sample_seed(TableSampleSeedModifier::Repeatable)?)
16898        } else if self.parse_keyword(Keyword::SEED) {
16899            Some(self.parse_table_sample_seed(TableSampleSeedModifier::Seed)?)
16900        } else {
16901            None
16902        };
16903
16904        let offset = if self.parse_keyword(Keyword::OFFSET) {
16905            Some(self.parse_expr()?)
16906        } else {
16907            None
16908        };
16909
16910        Ok(Box::new(TableSample {
16911            modifier,
16912            name,
16913            quantity,
16914            seed,
16915            bucket,
16916            offset,
16917        }))
16918    }
16919
16920    fn parse_table_sample_seed(
16921        &mut self,
16922        modifier: TableSampleSeedModifier,
16923    ) -> Result<TableSampleSeed, ParserError> {
16924        self.expect_token(&Token::LParen)?;
16925        let value = self.parse_number_value()?;
16926        self.expect_token(&Token::RParen)?;
16927        Ok(TableSampleSeed { modifier, value })
16928    }
16929
16930    /// Parses `OPENJSON( jsonExpression [ , path ] )  [ <with_clause> ]` clause,
16931    /// assuming the `OPENJSON` keyword was already consumed.
16932    fn parse_open_json_table_factor(&mut self) -> Result<TableFactor, ParserError> {
16933        self.expect_token(&Token::LParen)?;
16934        let json_expr = self.parse_expr()?;
16935        let json_path = if self.consume_token(&Token::Comma) {
16936            Some(self.parse_value()?)
16937        } else {
16938            None
16939        };
16940        self.expect_token(&Token::RParen)?;
16941        let columns = if self.parse_keyword(Keyword::WITH) {
16942            self.expect_token(&Token::LParen)?;
16943            let columns = self.parse_comma_separated(Parser::parse_openjson_table_column_def)?;
16944            self.expect_token(&Token::RParen)?;
16945            columns
16946        } else {
16947            Vec::new()
16948        };
16949        let alias = self.maybe_parse_table_alias()?;
16950        Ok(TableFactor::OpenJsonTable {
16951            json_expr,
16952            json_path,
16953            columns,
16954            alias,
16955        })
16956    }
16957
16958    fn parse_xml_table_factor(&mut self) -> Result<TableFactor, ParserError> {
16959        self.expect_token(&Token::LParen)?;
16960        let namespaces = if self.parse_keyword(Keyword::XMLNAMESPACES) {
16961            self.expect_token(&Token::LParen)?;
16962            let namespaces = self.parse_comma_separated(Parser::parse_xml_namespace_definition)?;
16963            self.expect_token(&Token::RParen)?;
16964            self.expect_token(&Token::Comma)?;
16965            namespaces
16966        } else {
16967            vec![]
16968        };
16969        let row_expression = self.parse_expr()?;
16970        let passing = self.parse_xml_passing_clause()?;
16971        self.expect_keyword_is(Keyword::COLUMNS)?;
16972        let columns = self.parse_comma_separated(Parser::parse_xml_table_column)?;
16973        self.expect_token(&Token::RParen)?;
16974        let alias = self.maybe_parse_table_alias()?;
16975        Ok(TableFactor::XmlTable {
16976            namespaces,
16977            row_expression,
16978            passing,
16979            columns,
16980            alias,
16981        })
16982    }
16983
16984    fn parse_xml_namespace_definition(&mut self) -> Result<XmlNamespaceDefinition, ParserError> {
16985        let uri = self.parse_expr()?;
16986        self.expect_keyword_is(Keyword::AS)?;
16987        let name = self.parse_identifier()?;
16988        Ok(XmlNamespaceDefinition { uri, name })
16989    }
16990
16991    fn parse_xml_table_column(&mut self) -> Result<XmlTableColumn, ParserError> {
16992        let name = self.parse_identifier()?;
16993
16994        let option = if self.parse_keyword(Keyword::FOR) {
16995            self.expect_keyword(Keyword::ORDINALITY)?;
16996            XmlTableColumnOption::ForOrdinality
16997        } else {
16998            let r#type = self.parse_data_type()?;
16999            let mut path = None;
17000            let mut default = None;
17001
17002            if self.parse_keyword(Keyword::PATH) {
17003                path = Some(self.parse_expr()?);
17004            }
17005
17006            if self.parse_keyword(Keyword::DEFAULT) {
17007                default = Some(self.parse_expr()?);
17008            }
17009
17010            let not_null = self.parse_keywords(&[Keyword::NOT, Keyword::NULL]);
17011            if !not_null {
17012                // NULL is the default but can be specified explicitly
17013                let _ = self.parse_keyword(Keyword::NULL);
17014            }
17015
17016            XmlTableColumnOption::NamedInfo {
17017                r#type,
17018                path,
17019                default,
17020                nullable: !not_null,
17021            }
17022        };
17023        Ok(XmlTableColumn { name, option })
17024    }
17025
17026    fn parse_xml_passing_clause(&mut self) -> Result<XmlPassingClause, ParserError> {
17027        let mut arguments = vec![];
17028        if self.parse_keyword(Keyword::PASSING) {
17029            loop {
17030                let by_value =
17031                    self.parse_keyword(Keyword::BY) && self.expect_keyword(Keyword::VALUE).is_ok();
17032                let expr = self.parse_expr()?;
17033                let alias = if self.parse_keyword(Keyword::AS) {
17034                    Some(self.parse_identifier()?)
17035                } else {
17036                    None
17037                };
17038                arguments.push(XmlPassingArgument {
17039                    expr,
17040                    alias,
17041                    by_value,
17042                });
17043                if !self.consume_token(&Token::Comma) {
17044                    break;
17045                }
17046            }
17047        }
17048        Ok(XmlPassingClause { arguments })
17049    }
17050
17051    /// Parse a [TableFactor::SemanticView]
17052    fn parse_semantic_view_table_factor(&mut self) -> Result<TableFactor, ParserError> {
17053        self.expect_keyword(Keyword::SEMANTIC_VIEW)?;
17054        self.expect_token(&Token::LParen)?;
17055
17056        let name = self.parse_object_name(true)?;
17057
17058        // Parse DIMENSIONS, METRICS, FACTS and WHERE clauses in flexible order
17059        let mut dimensions = Vec::new();
17060        let mut metrics = Vec::new();
17061        let mut facts = Vec::new();
17062        let mut where_clause = None;
17063
17064        while self.peek_token_ref().token != Token::RParen {
17065            if self.parse_keyword(Keyword::DIMENSIONS) {
17066                if !dimensions.is_empty() {
17067                    return Err(ParserError::ParserError(
17068                        "DIMENSIONS clause can only be specified once".to_string(),
17069                    ));
17070                }
17071                dimensions = self.parse_comma_separated(Parser::parse_wildcard_expr)?;
17072            } else if self.parse_keyword(Keyword::METRICS) {
17073                if !metrics.is_empty() {
17074                    return Err(ParserError::ParserError(
17075                        "METRICS clause can only be specified once".to_string(),
17076                    ));
17077                }
17078                metrics = self.parse_comma_separated(Parser::parse_wildcard_expr)?;
17079            } else if self.parse_keyword(Keyword::FACTS) {
17080                if !facts.is_empty() {
17081                    return Err(ParserError::ParserError(
17082                        "FACTS clause can only be specified once".to_string(),
17083                    ));
17084                }
17085                facts = self.parse_comma_separated(Parser::parse_wildcard_expr)?;
17086            } else if self.parse_keyword(Keyword::WHERE) {
17087                if where_clause.is_some() {
17088                    return Err(ParserError::ParserError(
17089                        "WHERE clause can only be specified once".to_string(),
17090                    ));
17091                }
17092                where_clause = Some(self.parse_expr()?);
17093            } else {
17094                let tok = self.peek_token_ref();
17095                return parser_err!(
17096                    format!(
17097                        "Expected one of DIMENSIONS, METRICS, FACTS or WHERE, got {}",
17098                        tok.token
17099                    ),
17100                    tok.span.start
17101                )?;
17102            }
17103        }
17104
17105        self.expect_token(&Token::RParen)?;
17106
17107        let alias = self.maybe_parse_table_alias()?;
17108
17109        Ok(TableFactor::SemanticView {
17110            name,
17111            dimensions,
17112            metrics,
17113            facts,
17114            where_clause,
17115            alias,
17116        })
17117    }
17118
17119    fn parse_match_recognize(&mut self, table: TableFactor) -> Result<TableFactor, ParserError> {
17120        self.expect_token(&Token::LParen)?;
17121
17122        let partition_by = if self.parse_keywords(&[Keyword::PARTITION, Keyword::BY]) {
17123            self.parse_comma_separated(Parser::parse_expr)?
17124        } else {
17125            vec![]
17126        };
17127
17128        let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
17129            self.parse_comma_separated(Parser::parse_order_by_expr)?
17130        } else {
17131            vec![]
17132        };
17133
17134        let measures = if self.parse_keyword(Keyword::MEASURES) {
17135            self.parse_comma_separated(|p| {
17136                let expr = p.parse_expr()?;
17137                let _ = p.parse_keyword(Keyword::AS);
17138                let alias = p.parse_identifier()?;
17139                Ok(Measure { expr, alias })
17140            })?
17141        } else {
17142            vec![]
17143        };
17144
17145        let rows_per_match =
17146            if self.parse_keywords(&[Keyword::ONE, Keyword::ROW, Keyword::PER, Keyword::MATCH]) {
17147                Some(RowsPerMatch::OneRow)
17148            } else if self.parse_keywords(&[
17149                Keyword::ALL,
17150                Keyword::ROWS,
17151                Keyword::PER,
17152                Keyword::MATCH,
17153            ]) {
17154                Some(RowsPerMatch::AllRows(
17155                    if self.parse_keywords(&[Keyword::SHOW, Keyword::EMPTY, Keyword::MATCHES]) {
17156                        Some(EmptyMatchesMode::Show)
17157                    } else if self.parse_keywords(&[
17158                        Keyword::OMIT,
17159                        Keyword::EMPTY,
17160                        Keyword::MATCHES,
17161                    ]) {
17162                        Some(EmptyMatchesMode::Omit)
17163                    } else if self.parse_keywords(&[
17164                        Keyword::WITH,
17165                        Keyword::UNMATCHED,
17166                        Keyword::ROWS,
17167                    ]) {
17168                        Some(EmptyMatchesMode::WithUnmatched)
17169                    } else {
17170                        None
17171                    },
17172                ))
17173            } else {
17174                None
17175            };
17176
17177        let after_match_skip =
17178            if self.parse_keywords(&[Keyword::AFTER, Keyword::MATCH, Keyword::SKIP]) {
17179                if self.parse_keywords(&[Keyword::PAST, Keyword::LAST, Keyword::ROW]) {
17180                    Some(AfterMatchSkip::PastLastRow)
17181                } else if self.parse_keywords(&[Keyword::TO, Keyword::NEXT, Keyword::ROW]) {
17182                    Some(AfterMatchSkip::ToNextRow)
17183                } else if self.parse_keywords(&[Keyword::TO, Keyword::FIRST]) {
17184                    Some(AfterMatchSkip::ToFirst(self.parse_identifier()?))
17185                } else if self.parse_keywords(&[Keyword::TO, Keyword::LAST]) {
17186                    Some(AfterMatchSkip::ToLast(self.parse_identifier()?))
17187                } else {
17188                    let found = self.next_token();
17189                    return self.expected("after match skip option", found);
17190                }
17191            } else {
17192                None
17193            };
17194
17195        self.expect_keyword_is(Keyword::PATTERN)?;
17196        let pattern = self.parse_parenthesized(Self::parse_pattern)?;
17197
17198        self.expect_keyword_is(Keyword::DEFINE)?;
17199
17200        let symbols = self.parse_comma_separated(|p| {
17201            let symbol = p.parse_identifier()?;
17202            p.expect_keyword_is(Keyword::AS)?;
17203            let definition = p.parse_expr()?;
17204            Ok(SymbolDefinition { symbol, definition })
17205        })?;
17206
17207        self.expect_token(&Token::RParen)?;
17208
17209        let alias = self.maybe_parse_table_alias()?;
17210
17211        Ok(TableFactor::MatchRecognize {
17212            table: Box::new(table),
17213            partition_by,
17214            order_by,
17215            measures,
17216            rows_per_match,
17217            after_match_skip,
17218            pattern,
17219            symbols,
17220            alias,
17221        })
17222    }
17223
17224    fn parse_base_pattern(&mut self) -> Result<MatchRecognizePattern, ParserError> {
17225        match self.next_token().token {
17226            Token::Caret => Ok(MatchRecognizePattern::Symbol(MatchRecognizeSymbol::Start)),
17227            Token::Placeholder(s) if s == "$" => {
17228                Ok(MatchRecognizePattern::Symbol(MatchRecognizeSymbol::End))
17229            }
17230            Token::LBrace => {
17231                self.expect_token(&Token::Minus)?;
17232                let symbol = self.parse_identifier().map(MatchRecognizeSymbol::Named)?;
17233                self.expect_token(&Token::Minus)?;
17234                self.expect_token(&Token::RBrace)?;
17235                Ok(MatchRecognizePattern::Exclude(symbol))
17236            }
17237            Token::Word(Word {
17238                value,
17239                quote_style: None,
17240                ..
17241            }) if value == "PERMUTE" => {
17242                self.expect_token(&Token::LParen)?;
17243                let symbols = self.parse_comma_separated(|p| {
17244                    p.parse_identifier().map(MatchRecognizeSymbol::Named)
17245                })?;
17246                self.expect_token(&Token::RParen)?;
17247                Ok(MatchRecognizePattern::Permute(symbols))
17248            }
17249            Token::LParen => {
17250                let pattern = self.parse_pattern()?;
17251                self.expect_token(&Token::RParen)?;
17252                Ok(MatchRecognizePattern::Group(Box::new(pattern)))
17253            }
17254            _ => {
17255                self.prev_token();
17256                self.parse_identifier()
17257                    .map(MatchRecognizeSymbol::Named)
17258                    .map(MatchRecognizePattern::Symbol)
17259            }
17260        }
17261    }
17262
17263    fn parse_repetition_pattern(&mut self) -> Result<MatchRecognizePattern, ParserError> {
17264        let mut pattern = self.parse_base_pattern()?;
17265        loop {
17266            let token = self.next_token();
17267            let quantifier = match token.token {
17268                Token::Mul => RepetitionQuantifier::ZeroOrMore,
17269                Token::Plus => RepetitionQuantifier::OneOrMore,
17270                Token::Placeholder(s) if s == "?" => RepetitionQuantifier::AtMostOne,
17271                Token::LBrace => {
17272                    // quantifier is a range like {n} or {n,} or {,m} or {n,m}
17273                    let token = self.next_token();
17274                    match token.token {
17275                        Token::Comma => {
17276                            let next_token = self.next_token();
17277                            let Token::Number(n, _) = next_token.token else {
17278                                return self.expected("literal number", next_token);
17279                            };
17280                            self.expect_token(&Token::RBrace)?;
17281                            RepetitionQuantifier::AtMost(Self::parse(n, token.span.start)?)
17282                        }
17283                        Token::Number(n, _) if self.consume_token(&Token::Comma) => {
17284                            let next_token = self.next_token();
17285                            match next_token.token {
17286                                Token::Number(m, _) => {
17287                                    self.expect_token(&Token::RBrace)?;
17288                                    RepetitionQuantifier::Range(
17289                                        Self::parse(n, token.span.start)?,
17290                                        Self::parse(m, token.span.start)?,
17291                                    )
17292                                }
17293                                Token::RBrace => {
17294                                    RepetitionQuantifier::AtLeast(Self::parse(n, token.span.start)?)
17295                                }
17296                                _ => {
17297                                    return self.expected("} or upper bound", next_token);
17298                                }
17299                            }
17300                        }
17301                        Token::Number(n, _) => {
17302                            self.expect_token(&Token::RBrace)?;
17303                            RepetitionQuantifier::Exactly(Self::parse(n, token.span.start)?)
17304                        }
17305                        _ => return self.expected("quantifier range", token),
17306                    }
17307                }
17308                _ => {
17309                    self.prev_token();
17310                    break;
17311                }
17312            };
17313            pattern = MatchRecognizePattern::Repetition(Box::new(pattern), quantifier);
17314        }
17315        Ok(pattern)
17316    }
17317
17318    fn parse_concat_pattern(&mut self) -> Result<MatchRecognizePattern, ParserError> {
17319        let mut patterns = vec![self.parse_repetition_pattern()?];
17320        while !matches!(self.peek_token_ref().token, Token::RParen | Token::Pipe) {
17321            patterns.push(self.parse_repetition_pattern()?);
17322        }
17323        match <[MatchRecognizePattern; 1]>::try_from(patterns) {
17324            Ok([pattern]) => Ok(pattern),
17325            Err(patterns) => Ok(MatchRecognizePattern::Concat(patterns)),
17326        }
17327    }
17328
17329    fn parse_pattern(&mut self) -> Result<MatchRecognizePattern, ParserError> {
17330        let pattern = self.parse_concat_pattern()?;
17331        if self.consume_token(&Token::Pipe) {
17332            match self.parse_pattern()? {
17333                // flatten nested alternations
17334                MatchRecognizePattern::Alternation(mut patterns) => {
17335                    patterns.insert(0, pattern);
17336                    Ok(MatchRecognizePattern::Alternation(patterns))
17337                }
17338                next => Ok(MatchRecognizePattern::Alternation(vec![pattern, next])),
17339            }
17340        } else {
17341            Ok(pattern)
17342        }
17343    }
17344
17345    /// Parses a the timestamp version specifier (i.e. query historical data)
17346    pub fn maybe_parse_table_version(&mut self) -> Result<Option<TableVersion>, ParserError> {
17347        if self.dialect.supports_table_versioning() {
17348            if self.parse_keywords(&[Keyword::FOR, Keyword::SYSTEM_TIME, Keyword::AS, Keyword::OF])
17349            {
17350                let expr = self.parse_expr()?;
17351                return Ok(Some(TableVersion::ForSystemTimeAsOf(expr)));
17352            } else if self.peek_keyword(Keyword::CHANGES) {
17353                return self.parse_table_version_changes().map(Some);
17354            } else if self.peek_keyword(Keyword::AT) || self.peek_keyword(Keyword::BEFORE) {
17355                let func_name = self.parse_object_name(true)?;
17356                let func = self.parse_function(func_name)?;
17357                return Ok(Some(TableVersion::Function(func)));
17358            } else if self.parse_keywords(&[Keyword::TIMESTAMP, Keyword::AS, Keyword::OF]) {
17359                let expr = self.parse_expr()?;
17360                return Ok(Some(TableVersion::TimestampAsOf(expr)));
17361            } else if self.parse_keywords(&[Keyword::VERSION, Keyword::AS, Keyword::OF]) {
17362                let expr = Expr::Value(self.parse_number_value()?);
17363                return Ok(Some(TableVersion::VersionAsOf(expr)));
17364            }
17365        }
17366        Ok(None)
17367    }
17368
17369    /// Parses the Snowflake `CHANGES` clause for change tracking queries.
17370    ///
17371    /// Syntax:
17372    /// ```sql
17373    /// CHANGES (INFORMATION => DEFAULT)
17374    ///   AT (TIMESTAMP => <expr>)
17375    ///   [END (TIMESTAMP => <expr>)]
17376    /// ```
17377    ///
17378    /// <https://docs.snowflake.com/en/sql-reference/constructs/changes>
17379    fn parse_table_version_changes(&mut self) -> Result<TableVersion, ParserError> {
17380        let changes_name = self.parse_object_name(true)?;
17381        let changes = self.parse_function(changes_name)?;
17382        let at_name = self.parse_object_name(true)?;
17383        let at = self.parse_function(at_name)?;
17384        let end = if self.peek_keyword(Keyword::END) {
17385            let end_name = self.parse_object_name(true)?;
17386            Some(self.parse_function(end_name)?)
17387        } else {
17388            None
17389        };
17390        Ok(TableVersion::Changes { changes, at, end })
17391    }
17392
17393    /// Parses MySQL's JSON_TABLE column definition.
17394    /// For example: `id INT EXISTS PATH '$' DEFAULT '0' ON EMPTY ERROR ON ERROR`
17395    pub fn parse_json_table_column_def(&mut self) -> Result<JsonTableColumn, ParserError> {
17396        if self.parse_keyword(Keyword::NESTED) {
17397            let _has_path_keyword = self.parse_keyword(Keyword::PATH);
17398            let path = self.parse_value()?;
17399            self.expect_keyword_is(Keyword::COLUMNS)?;
17400            let columns = self.parse_parenthesized(|p| {
17401                p.parse_comma_separated(Self::parse_json_table_column_def)
17402            })?;
17403            return Ok(JsonTableColumn::Nested(JsonTableNestedColumn {
17404                path,
17405                columns,
17406            }));
17407        }
17408        let name = self.parse_identifier()?;
17409        if self.parse_keyword(Keyword::FOR) {
17410            self.expect_keyword_is(Keyword::ORDINALITY)?;
17411            return Ok(JsonTableColumn::ForOrdinality(name));
17412        }
17413        let r#type = self.parse_data_type()?;
17414        let exists = self.parse_keyword(Keyword::EXISTS);
17415        self.expect_keyword_is(Keyword::PATH)?;
17416        let path = self.parse_value()?;
17417        let mut on_empty = None;
17418        let mut on_error = None;
17419        while let Some(error_handling) = self.parse_json_table_column_error_handling()? {
17420            if self.parse_keyword(Keyword::EMPTY) {
17421                on_empty = Some(error_handling);
17422            } else {
17423                self.expect_keyword_is(Keyword::ERROR)?;
17424                on_error = Some(error_handling);
17425            }
17426        }
17427        Ok(JsonTableColumn::Named(JsonTableNamedColumn {
17428            name,
17429            r#type,
17430            path,
17431            exists,
17432            on_empty,
17433            on_error,
17434        }))
17435    }
17436
17437    /// Parses MSSQL's `OPENJSON WITH` column definition.
17438    ///
17439    /// ```sql
17440    /// colName type [ column_path ] [ AS JSON ]
17441    /// ```
17442    ///
17443    /// Reference: <https://learn.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver16#syntax>
17444    pub fn parse_openjson_table_column_def(&mut self) -> Result<OpenJsonTableColumn, ParserError> {
17445        let name = self.parse_identifier()?;
17446        let r#type = self.parse_data_type()?;
17447        let path = if let Token::SingleQuotedString(path) = self.peek_token().token {
17448            self.next_token();
17449            Some(path)
17450        } else {
17451            None
17452        };
17453        let as_json = self.parse_keyword(Keyword::AS);
17454        if as_json {
17455            self.expect_keyword_is(Keyword::JSON)?;
17456        }
17457        Ok(OpenJsonTableColumn {
17458            name,
17459            r#type,
17460            path,
17461            as_json,
17462        })
17463    }
17464
17465    fn parse_json_table_column_error_handling(
17466        &mut self,
17467    ) -> Result<Option<JsonTableColumnErrorHandling>, ParserError> {
17468        let res = if self.parse_keyword(Keyword::NULL) {
17469            JsonTableColumnErrorHandling::Null
17470        } else if self.parse_keyword(Keyword::ERROR) {
17471            JsonTableColumnErrorHandling::Error
17472        } else if self.parse_keyword(Keyword::DEFAULT) {
17473            JsonTableColumnErrorHandling::Default(self.parse_value()?)
17474        } else {
17475            return Ok(None);
17476        };
17477        self.expect_keyword_is(Keyword::ON)?;
17478        Ok(Some(res))
17479    }
17480
17481    /// Parse a derived table factor (a parenthesized subquery), handling optional LATERAL.
17482    pub fn parse_derived_table_factor(
17483        &mut self,
17484        lateral: IsLateral,
17485    ) -> Result<TableFactor, ParserError> {
17486        let subquery = self.parse_query()?;
17487        self.expect_token(&Token::RParen)?;
17488        let alias = self.maybe_parse_table_alias()?;
17489
17490        // Parse optional SAMPLE clause after alias
17491        let sample = self
17492            .maybe_parse_table_sample()?
17493            .map(TableSampleKind::AfterTableAlias);
17494
17495        Ok(TableFactor::Derived {
17496            lateral: match lateral {
17497                Lateral => true,
17498                NotLateral => false,
17499            },
17500            subquery,
17501            alias,
17502            sample,
17503        })
17504    }
17505
17506    /// Parses an expression with an optional alias
17507    ///
17508    /// Examples:
17509    ///
17510    /// ```sql
17511    /// SUM(price) AS total_price
17512    /// ```
17513    /// ```sql
17514    /// SUM(price)
17515    /// ```
17516    ///
17517    /// Example
17518    /// ```
17519    /// # use sqlparser::parser::{Parser, ParserError};
17520    /// # use sqlparser::dialect::GenericDialect;
17521    /// # fn main() ->Result<(), ParserError> {
17522    /// let sql = r#"SUM("a") as "b""#;
17523    /// let mut parser = Parser::new(&GenericDialect).try_with_sql(sql)?;
17524    /// let expr_with_alias = parser.parse_expr_with_alias()?;
17525    /// assert_eq!(Some("b".to_string()), expr_with_alias.alias.map(|x|x.value));
17526    /// # Ok(())
17527    /// # }
17528    pub fn parse_expr_with_alias(&mut self) -> Result<ExprWithAlias, ParserError> {
17529        let expr = self.parse_expr()?;
17530        let alias = if self.parse_keyword(Keyword::AS) {
17531            Some(self.parse_identifier()?)
17532        } else {
17533            None
17534        };
17535
17536        Ok(ExprWithAlias { expr, alias })
17537    }
17538
17539    /// Parse an expression followed by an optional alias; Unlike
17540    /// [Self::parse_expr_with_alias] the "AS" keyword between the expression
17541    /// and the alias is optional.
17542    fn parse_expr_with_alias_optional_as_keyword(&mut self) -> Result<ExprWithAlias, ParserError> {
17543        let expr = self.parse_expr()?;
17544        let alias = self.parse_identifier_optional_alias()?;
17545        Ok(ExprWithAlias { expr, alias })
17546    }
17547
17548    /// Parses a plain function call with an optional alias for the `PIVOT` clause
17549    fn parse_pivot_aggregate_function(&mut self) -> Result<ExprWithAlias, ParserError> {
17550        let function_name = match self.next_token().token {
17551            Token::Word(w) => Ok(w.value),
17552            _ => self.expected_ref("a function identifier", self.peek_token_ref()),
17553        }?;
17554        let expr = self.parse_function(ObjectName::from(vec![Ident::new(function_name)]))?;
17555        let alias = {
17556            fn validator(explicit: bool, kw: &Keyword, parser: &mut Parser) -> bool {
17557                // ~ for a PIVOT aggregate function the alias must not be a "FOR"; in any dialect
17558                kw != &Keyword::FOR && parser.dialect.is_select_item_alias(explicit, kw, parser)
17559            }
17560            self.parse_optional_alias_inner(None, validator)?
17561        };
17562        Ok(ExprWithAlias { expr, alias })
17563    }
17564
17565    /// Parse a PIVOT table factor (ClickHouse/Oracle style pivot), returning a TableFactor.
17566    pub fn parse_pivot_table_factor(
17567        &mut self,
17568        table: TableFactor,
17569    ) -> Result<TableFactor, ParserError> {
17570        self.expect_token(&Token::LParen)?;
17571        let aggregate_functions =
17572            self.parse_comma_separated(Self::parse_pivot_aggregate_function)?;
17573        self.expect_keyword_is(Keyword::FOR)?;
17574        let value_column = if self.peek_token_ref().token == Token::LParen {
17575            self.parse_parenthesized_column_list_inner(Mandatory, false, |p| {
17576                p.parse_subexpr(self.dialect.prec_value(Precedence::Between))
17577            })?
17578        } else {
17579            vec![self.parse_subexpr(self.dialect.prec_value(Precedence::Between))?]
17580        };
17581        self.expect_keyword_is(Keyword::IN)?;
17582
17583        self.expect_token(&Token::LParen)?;
17584        let value_source = if self.parse_keyword(Keyword::ANY) {
17585            let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
17586                self.parse_comma_separated(Parser::parse_order_by_expr)?
17587            } else {
17588                vec![]
17589            };
17590            PivotValueSource::Any(order_by)
17591        } else if self.peek_sub_query() {
17592            PivotValueSource::Subquery(self.parse_query()?)
17593        } else {
17594            PivotValueSource::List(
17595                self.parse_comma_separated(Self::parse_expr_with_alias_optional_as_keyword)?,
17596            )
17597        };
17598        self.expect_token(&Token::RParen)?;
17599
17600        let default_on_null =
17601            if self.parse_keywords(&[Keyword::DEFAULT, Keyword::ON, Keyword::NULL]) {
17602                self.expect_token(&Token::LParen)?;
17603                let expr = self.parse_expr()?;
17604                self.expect_token(&Token::RParen)?;
17605                Some(expr)
17606            } else {
17607                None
17608            };
17609
17610        self.expect_token(&Token::RParen)?;
17611        let alias = self.maybe_parse_table_alias()?;
17612        Ok(TableFactor::Pivot {
17613            table: Box::new(table),
17614            aggregate_functions,
17615            value_column,
17616            value_source,
17617            default_on_null,
17618            alias,
17619        })
17620    }
17621
17622    /// Parse an UNPIVOT table factor, returning a TableFactor.
17623    pub fn parse_unpivot_table_factor(
17624        &mut self,
17625        table: TableFactor,
17626    ) -> Result<TableFactor, ParserError> {
17627        let null_inclusion = if self.parse_keyword(Keyword::INCLUDE) {
17628            self.expect_keyword_is(Keyword::NULLS)?;
17629            Some(NullInclusion::IncludeNulls)
17630        } else if self.parse_keyword(Keyword::EXCLUDE) {
17631            self.expect_keyword_is(Keyword::NULLS)?;
17632            Some(NullInclusion::ExcludeNulls)
17633        } else {
17634            None
17635        };
17636        self.expect_token(&Token::LParen)?;
17637        let value = self.parse_expr()?;
17638        self.expect_keyword_is(Keyword::FOR)?;
17639        let name = self.parse_identifier()?;
17640        self.expect_keyword_is(Keyword::IN)?;
17641        let columns = self.parse_parenthesized_column_list_inner(Mandatory, false, |p| {
17642            p.parse_expr_with_alias()
17643        })?;
17644        self.expect_token(&Token::RParen)?;
17645        let alias = self.maybe_parse_table_alias()?;
17646        Ok(TableFactor::Unpivot {
17647            table: Box::new(table),
17648            value,
17649            null_inclusion,
17650            name,
17651            columns,
17652            alias,
17653        })
17654    }
17655
17656    /// Parse a JOIN constraint (`NATURAL`, `ON <expr>`, `USING (...)`, or no constraint).
17657    pub fn parse_join_constraint(&mut self, natural: bool) -> Result<JoinConstraint, ParserError> {
17658        if natural {
17659            Ok(JoinConstraint::Natural)
17660        } else if self.parse_keyword(Keyword::ON) {
17661            let constraint = self.parse_expr()?;
17662            Ok(JoinConstraint::On(constraint))
17663        } else if self.parse_keyword(Keyword::USING) {
17664            let columns = self.parse_parenthesized_qualified_column_list(Mandatory, false)?;
17665            Ok(JoinConstraint::Using(columns))
17666        } else {
17667            Ok(JoinConstraint::None)
17668            //self.expected_ref("ON, or USING after JOIN", self.peek_token_ref())
17669        }
17670    }
17671
17672    /// Parse a GRANT statement.
17673    pub fn parse_grant(&mut self) -> Result<Grant, ParserError> {
17674        let (privileges, objects) = self.parse_grant_deny_revoke_privileges_objects()?;
17675
17676        self.expect_keyword_is(Keyword::TO)?;
17677        let grantees = self.parse_grantees()?;
17678
17679        let with_grant_option =
17680            self.parse_keywords(&[Keyword::WITH, Keyword::GRANT, Keyword::OPTION]);
17681
17682        let current_grants =
17683            if self.parse_keywords(&[Keyword::COPY, Keyword::CURRENT, Keyword::GRANTS]) {
17684                Some(CurrentGrantsKind::CopyCurrentGrants)
17685            } else if self.parse_keywords(&[Keyword::REVOKE, Keyword::CURRENT, Keyword::GRANTS]) {
17686                Some(CurrentGrantsKind::RevokeCurrentGrants)
17687            } else {
17688                None
17689            };
17690
17691        let as_grantor = if self.parse_keywords(&[Keyword::AS]) {
17692            Some(self.parse_identifier()?)
17693        } else {
17694            None
17695        };
17696
17697        let granted_by = if self.parse_keywords(&[Keyword::GRANTED, Keyword::BY]) {
17698            Some(self.parse_identifier()?)
17699        } else {
17700            None
17701        };
17702
17703        Ok(Grant {
17704            privileges,
17705            objects,
17706            grantees,
17707            with_grant_option,
17708            as_grantor,
17709            granted_by,
17710            current_grants,
17711        })
17712    }
17713
17714    fn parse_grantees(&mut self) -> Result<Vec<Grantee>, ParserError> {
17715        let mut values = vec![];
17716        let mut grantee_type = GranteesType::None;
17717        loop {
17718            let new_grantee_type = if self.parse_keyword(Keyword::ROLE) {
17719                GranteesType::Role
17720            } else if self.parse_keyword(Keyword::USER) {
17721                GranteesType::User
17722            } else if self.parse_keyword(Keyword::SHARE) {
17723                GranteesType::Share
17724            } else if self.parse_keyword(Keyword::GROUP) {
17725                GranteesType::Group
17726            } else if self.parse_keyword(Keyword::PUBLIC) {
17727                GranteesType::Public
17728            } else if self.parse_keywords(&[Keyword::DATABASE, Keyword::ROLE]) {
17729                GranteesType::DatabaseRole
17730            } else if self.parse_keywords(&[Keyword::APPLICATION, Keyword::ROLE]) {
17731                GranteesType::ApplicationRole
17732            } else if self.parse_keyword(Keyword::APPLICATION) {
17733                GranteesType::Application
17734            } else {
17735                grantee_type.clone() // keep from previous iteraton, if not specified
17736            };
17737
17738            if self
17739                .dialect
17740                .get_reserved_grantees_types()
17741                .contains(&new_grantee_type)
17742            {
17743                self.prev_token();
17744            } else {
17745                grantee_type = new_grantee_type;
17746            }
17747
17748            let grantee = if grantee_type == GranteesType::Public {
17749                Grantee {
17750                    grantee_type: grantee_type.clone(),
17751                    name: None,
17752                }
17753            } else {
17754                let mut name = self.parse_grantee_name()?;
17755                if self.consume_token(&Token::Colon) {
17756                    // Redshift supports namespace prefix for external users and groups:
17757                    // <Namespace>:<GroupName> or <Namespace>:<UserName>
17758                    // https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-iam-access-control-native-idp.html
17759                    let ident = self.parse_identifier()?;
17760                    if let GranteeName::ObjectName(namespace) = name {
17761                        name = GranteeName::ObjectName(ObjectName::from(vec![Ident::new(
17762                            format!("{namespace}:{ident}"),
17763                        )]));
17764                    };
17765                }
17766                Grantee {
17767                    grantee_type: grantee_type.clone(),
17768                    name: Some(name),
17769                }
17770            };
17771
17772            values.push(grantee);
17773
17774            if !self.consume_token(&Token::Comma) {
17775                break;
17776            }
17777        }
17778
17779        Ok(values)
17780    }
17781
17782    /// Parse privileges and optional target objects for GRANT/DENY/REVOKE statements.
17783    pub fn parse_grant_deny_revoke_privileges_objects(
17784        &mut self,
17785    ) -> Result<(Privileges, Option<GrantObjects>), ParserError> {
17786        let privileges = if self.parse_keyword(Keyword::ALL) {
17787            Privileges::All {
17788                with_privileges_keyword: self.parse_keyword(Keyword::PRIVILEGES),
17789            }
17790        } else {
17791            let actions = self.parse_actions_list()?;
17792            Privileges::Actions(actions)
17793        };
17794
17795        let objects = if self.parse_keyword(Keyword::ON) {
17796            if self.parse_keywords(&[Keyword::ALL, Keyword::TABLES, Keyword::IN, Keyword::SCHEMA]) {
17797                Some(GrantObjects::AllTablesInSchema {
17798                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17799                })
17800            } else if self.parse_keywords(&[
17801                Keyword::ALL,
17802                Keyword::EXTERNAL,
17803                Keyword::TABLES,
17804                Keyword::IN,
17805                Keyword::SCHEMA,
17806            ]) {
17807                Some(GrantObjects::AllExternalTablesInSchema {
17808                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17809                })
17810            } else if self.parse_keywords(&[
17811                Keyword::ALL,
17812                Keyword::VIEWS,
17813                Keyword::IN,
17814                Keyword::SCHEMA,
17815            ]) {
17816                Some(GrantObjects::AllViewsInSchema {
17817                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17818                })
17819            } else if self.parse_keywords(&[
17820                Keyword::ALL,
17821                Keyword::MATERIALIZED,
17822                Keyword::VIEWS,
17823                Keyword::IN,
17824                Keyword::SCHEMA,
17825            ]) {
17826                Some(GrantObjects::AllMaterializedViewsInSchema {
17827                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17828                })
17829            } else if self.parse_keywords(&[
17830                Keyword::ALL,
17831                Keyword::FUNCTIONS,
17832                Keyword::IN,
17833                Keyword::SCHEMA,
17834            ]) {
17835                Some(GrantObjects::AllFunctionsInSchema {
17836                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17837                })
17838            } else if self.parse_keywords(&[
17839                Keyword::FUTURE,
17840                Keyword::SCHEMAS,
17841                Keyword::IN,
17842                Keyword::DATABASE,
17843            ]) {
17844                Some(GrantObjects::FutureSchemasInDatabase {
17845                    databases: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17846                })
17847            } else if self.parse_keywords(&[
17848                Keyword::FUTURE,
17849                Keyword::TABLES,
17850                Keyword::IN,
17851                Keyword::SCHEMA,
17852            ]) {
17853                Some(GrantObjects::FutureTablesInSchema {
17854                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17855                })
17856            } else if self.parse_keywords(&[
17857                Keyword::FUTURE,
17858                Keyword::EXTERNAL,
17859                Keyword::TABLES,
17860                Keyword::IN,
17861                Keyword::SCHEMA,
17862            ]) {
17863                Some(GrantObjects::FutureExternalTablesInSchema {
17864                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17865                })
17866            } else if self.parse_keywords(&[
17867                Keyword::FUTURE,
17868                Keyword::VIEWS,
17869                Keyword::IN,
17870                Keyword::SCHEMA,
17871            ]) {
17872                Some(GrantObjects::FutureViewsInSchema {
17873                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17874                })
17875            } else if self.parse_keywords(&[
17876                Keyword::FUTURE,
17877                Keyword::MATERIALIZED,
17878                Keyword::VIEWS,
17879                Keyword::IN,
17880                Keyword::SCHEMA,
17881            ]) {
17882                Some(GrantObjects::FutureMaterializedViewsInSchema {
17883                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17884                })
17885            } else if self.parse_keywords(&[
17886                Keyword::ALL,
17887                Keyword::SEQUENCES,
17888                Keyword::IN,
17889                Keyword::SCHEMA,
17890            ]) {
17891                Some(GrantObjects::AllSequencesInSchema {
17892                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17893                })
17894            } else if self.parse_keywords(&[
17895                Keyword::FUTURE,
17896                Keyword::SEQUENCES,
17897                Keyword::IN,
17898                Keyword::SCHEMA,
17899            ]) {
17900                Some(GrantObjects::FutureSequencesInSchema {
17901                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17902                })
17903            } else if self.parse_keywords(&[Keyword::RESOURCE, Keyword::MONITOR]) {
17904                Some(GrantObjects::ResourceMonitors(
17905                    self.parse_comma_separated(|p| p.parse_object_name(false))?,
17906                ))
17907            } else if self.parse_keywords(&[Keyword::COMPUTE, Keyword::POOL]) {
17908                Some(GrantObjects::ComputePools(
17909                    self.parse_comma_separated(|p| p.parse_object_name(false))?,
17910                ))
17911            } else if self.parse_keywords(&[Keyword::FAILOVER, Keyword::GROUP]) {
17912                Some(GrantObjects::FailoverGroup(
17913                    self.parse_comma_separated(|p| p.parse_object_name(false))?,
17914                ))
17915            } else if self.parse_keywords(&[Keyword::REPLICATION, Keyword::GROUP]) {
17916                Some(GrantObjects::ReplicationGroup(
17917                    self.parse_comma_separated(|p| p.parse_object_name(false))?,
17918                ))
17919            } else if self.parse_keywords(&[Keyword::EXTERNAL, Keyword::VOLUME]) {
17920                Some(GrantObjects::ExternalVolumes(
17921                    self.parse_comma_separated(|p| p.parse_object_name(false))?,
17922                ))
17923            } else {
17924                let object_type = self.parse_one_of_keywords(&[
17925                    Keyword::SEQUENCE,
17926                    Keyword::DATABASE,
17927                    Keyword::SCHEMA,
17928                    Keyword::TABLE,
17929                    Keyword::VIEW,
17930                    Keyword::WAREHOUSE,
17931                    Keyword::INTEGRATION,
17932                    Keyword::VIEW,
17933                    Keyword::WAREHOUSE,
17934                    Keyword::INTEGRATION,
17935                    Keyword::USER,
17936                    Keyword::CONNECTION,
17937                    Keyword::PROCEDURE,
17938                    Keyword::FUNCTION,
17939                ]);
17940                let objects =
17941                    self.parse_comma_separated(|p| p.parse_object_name_inner(false, true));
17942                match object_type {
17943                    Some(Keyword::DATABASE) => Some(GrantObjects::Databases(objects?)),
17944                    Some(Keyword::SCHEMA) => Some(GrantObjects::Schemas(objects?)),
17945                    Some(Keyword::SEQUENCE) => Some(GrantObjects::Sequences(objects?)),
17946                    Some(Keyword::WAREHOUSE) => Some(GrantObjects::Warehouses(objects?)),
17947                    Some(Keyword::INTEGRATION) => Some(GrantObjects::Integrations(objects?)),
17948                    Some(Keyword::VIEW) => Some(GrantObjects::Views(objects?)),
17949                    Some(Keyword::USER) => Some(GrantObjects::Users(objects?)),
17950                    Some(Keyword::CONNECTION) => Some(GrantObjects::Connections(objects?)),
17951                    kw @ (Some(Keyword::PROCEDURE) | Some(Keyword::FUNCTION)) => {
17952                        if let Some(name) = objects?.first() {
17953                            self.parse_grant_procedure_or_function(name, &kw)?
17954                        } else {
17955                            self.expected_ref("procedure or function name", self.peek_token_ref())?
17956                        }
17957                    }
17958                    Some(Keyword::TABLE) | None => Some(GrantObjects::Tables(objects?)),
17959                    Some(unexpected_keyword) => return Err(ParserError::ParserError(
17960                        format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in grant objects"),
17961                    )),
17962                }
17963            }
17964        } else {
17965            None
17966        };
17967
17968        Ok((privileges, objects))
17969    }
17970
17971    fn parse_grant_procedure_or_function(
17972        &mut self,
17973        name: &ObjectName,
17974        kw: &Option<Keyword>,
17975    ) -> Result<Option<GrantObjects>, ParserError> {
17976        let arg_types = if self.consume_token(&Token::LParen) {
17977            let list = self.parse_comma_separated0(Self::parse_data_type, Token::RParen)?;
17978            self.expect_token(&Token::RParen)?;
17979            list
17980        } else {
17981            vec![]
17982        };
17983        match kw {
17984            Some(Keyword::PROCEDURE) => Ok(Some(GrantObjects::Procedure {
17985                name: name.clone(),
17986                arg_types,
17987            })),
17988            Some(Keyword::FUNCTION) => Ok(Some(GrantObjects::Function {
17989                name: name.clone(),
17990                arg_types,
17991            })),
17992            _ => self.expected_ref("procedure or function keywords", self.peek_token_ref())?,
17993        }
17994    }
17995
17996    /// Parse a single grantable permission/action (used within GRANT statements).
17997    pub fn parse_grant_permission(&mut self) -> Result<Action, ParserError> {
17998        fn parse_columns(parser: &mut Parser) -> Result<Option<Vec<Ident>>, ParserError> {
17999            let columns = parser.parse_parenthesized_column_list(Optional, false)?;
18000            if columns.is_empty() {
18001                Ok(None)
18002            } else {
18003                Ok(Some(columns))
18004            }
18005        }
18006
18007        // Multi-word privileges
18008        if self.parse_keywords(&[Keyword::IMPORTED, Keyword::PRIVILEGES]) {
18009            Ok(Action::ImportedPrivileges)
18010        } else if self.parse_keywords(&[Keyword::ADD, Keyword::SEARCH, Keyword::OPTIMIZATION]) {
18011            Ok(Action::AddSearchOptimization)
18012        } else if self.parse_keywords(&[Keyword::ATTACH, Keyword::LISTING]) {
18013            Ok(Action::AttachListing)
18014        } else if self.parse_keywords(&[Keyword::ATTACH, Keyword::POLICY]) {
18015            Ok(Action::AttachPolicy)
18016        } else if self.parse_keywords(&[Keyword::BIND, Keyword::SERVICE, Keyword::ENDPOINT]) {
18017            Ok(Action::BindServiceEndpoint)
18018        } else if self.parse_keywords(&[Keyword::DATABASE, Keyword::ROLE]) {
18019            let role = self.parse_object_name(false)?;
18020            Ok(Action::DatabaseRole { role })
18021        } else if self.parse_keywords(&[Keyword::EVOLVE, Keyword::SCHEMA]) {
18022            Ok(Action::EvolveSchema)
18023        } else if self.parse_keywords(&[Keyword::IMPORT, Keyword::SHARE]) {
18024            Ok(Action::ImportShare)
18025        } else if self.parse_keywords(&[Keyword::MANAGE, Keyword::VERSIONS]) {
18026            Ok(Action::ManageVersions)
18027        } else if self.parse_keywords(&[Keyword::MANAGE, Keyword::RELEASES]) {
18028            Ok(Action::ManageReleases)
18029        } else if self.parse_keywords(&[Keyword::OVERRIDE, Keyword::SHARE, Keyword::RESTRICTIONS]) {
18030            Ok(Action::OverrideShareRestrictions)
18031        } else if self.parse_keywords(&[
18032            Keyword::PURCHASE,
18033            Keyword::DATA,
18034            Keyword::EXCHANGE,
18035            Keyword::LISTING,
18036        ]) {
18037            Ok(Action::PurchaseDataExchangeListing)
18038        } else if self.parse_keywords(&[Keyword::RESOLVE, Keyword::ALL]) {
18039            Ok(Action::ResolveAll)
18040        } else if self.parse_keywords(&[Keyword::READ, Keyword::SESSION]) {
18041            Ok(Action::ReadSession)
18042
18043        // Single-word privileges
18044        } else if self.parse_keyword(Keyword::APPLY) {
18045            let apply_type = self.parse_action_apply_type()?;
18046            Ok(Action::Apply { apply_type })
18047        } else if self.parse_keyword(Keyword::APPLYBUDGET) {
18048            Ok(Action::ApplyBudget)
18049        } else if self.parse_keyword(Keyword::AUDIT) {
18050            Ok(Action::Audit)
18051        } else if self.parse_keyword(Keyword::CONNECT) {
18052            Ok(Action::Connect)
18053        } else if self.parse_keyword(Keyword::CREATE) {
18054            let obj_type = self.maybe_parse_action_create_object_type();
18055            Ok(Action::Create { obj_type })
18056        } else if self.parse_keyword(Keyword::DELETE) {
18057            Ok(Action::Delete)
18058        } else if self.parse_keyword(Keyword::EXEC) {
18059            let obj_type = self.maybe_parse_action_execute_obj_type();
18060            Ok(Action::Exec { obj_type })
18061        } else if self.parse_keyword(Keyword::EXECUTE) {
18062            let obj_type = self.maybe_parse_action_execute_obj_type();
18063            Ok(Action::Execute { obj_type })
18064        } else if self.parse_keyword(Keyword::FAILOVER) {
18065            Ok(Action::Failover)
18066        } else if self.parse_keyword(Keyword::INSERT) {
18067            Ok(Action::Insert {
18068                columns: parse_columns(self)?,
18069            })
18070        } else if self.parse_keyword(Keyword::MANAGE) {
18071            let manage_type = self.parse_action_manage_type()?;
18072            Ok(Action::Manage { manage_type })
18073        } else if self.parse_keyword(Keyword::MODIFY) {
18074            let modify_type = self.parse_action_modify_type();
18075            Ok(Action::Modify { modify_type })
18076        } else if self.parse_keyword(Keyword::MONITOR) {
18077            let monitor_type = self.parse_action_monitor_type();
18078            Ok(Action::Monitor { monitor_type })
18079        } else if self.parse_keyword(Keyword::OPERATE) {
18080            Ok(Action::Operate)
18081        } else if self.parse_keyword(Keyword::REFERENCES) {
18082            Ok(Action::References {
18083                columns: parse_columns(self)?,
18084            })
18085        } else if self.parse_keyword(Keyword::READ) {
18086            Ok(Action::Read)
18087        } else if self.parse_keyword(Keyword::REPLICATE) {
18088            Ok(Action::Replicate)
18089        } else if self.parse_keyword(Keyword::ROLE) {
18090            let role = self.parse_object_name(false)?;
18091            Ok(Action::Role { role })
18092        } else if self.parse_keyword(Keyword::SELECT) {
18093            Ok(Action::Select {
18094                columns: parse_columns(self)?,
18095            })
18096        } else if self.parse_keyword(Keyword::TEMPORARY) {
18097            Ok(Action::Temporary)
18098        } else if self.parse_keyword(Keyword::TRIGGER) {
18099            Ok(Action::Trigger)
18100        } else if self.parse_keyword(Keyword::TRUNCATE) {
18101            Ok(Action::Truncate)
18102        } else if self.parse_keyword(Keyword::UPDATE) {
18103            Ok(Action::Update {
18104                columns: parse_columns(self)?,
18105            })
18106        } else if self.parse_keyword(Keyword::USAGE) {
18107            Ok(Action::Usage)
18108        } else if self.parse_keyword(Keyword::OWNERSHIP) {
18109            Ok(Action::Ownership)
18110        } else if self.parse_keyword(Keyword::DROP) {
18111            Ok(Action::Drop)
18112        } else {
18113            self.expected_ref("a privilege keyword", self.peek_token_ref())?
18114        }
18115    }
18116
18117    fn maybe_parse_action_create_object_type(&mut self) -> Option<ActionCreateObjectType> {
18118        // Multi-word object types
18119        if self.parse_keywords(&[Keyword::APPLICATION, Keyword::PACKAGE]) {
18120            Some(ActionCreateObjectType::ApplicationPackage)
18121        } else if self.parse_keywords(&[Keyword::COMPUTE, Keyword::POOL]) {
18122            Some(ActionCreateObjectType::ComputePool)
18123        } else if self.parse_keywords(&[Keyword::DATA, Keyword::EXCHANGE, Keyword::LISTING]) {
18124            Some(ActionCreateObjectType::DataExchangeListing)
18125        } else if self.parse_keywords(&[Keyword::EXTERNAL, Keyword::VOLUME]) {
18126            Some(ActionCreateObjectType::ExternalVolume)
18127        } else if self.parse_keywords(&[Keyword::FAILOVER, Keyword::GROUP]) {
18128            Some(ActionCreateObjectType::FailoverGroup)
18129        } else if self.parse_keywords(&[Keyword::NETWORK, Keyword::POLICY]) {
18130            Some(ActionCreateObjectType::NetworkPolicy)
18131        } else if self.parse_keywords(&[Keyword::ORGANIZATION, Keyword::LISTING]) {
18132            Some(ActionCreateObjectType::OrganiationListing)
18133        } else if self.parse_keywords(&[Keyword::REPLICATION, Keyword::GROUP]) {
18134            Some(ActionCreateObjectType::ReplicationGroup)
18135        }
18136        // Single-word object types
18137        else if self.parse_keyword(Keyword::ACCOUNT) {
18138            Some(ActionCreateObjectType::Account)
18139        } else if self.parse_keyword(Keyword::APPLICATION) {
18140            Some(ActionCreateObjectType::Application)
18141        } else if self.parse_keyword(Keyword::DATABASE) {
18142            Some(ActionCreateObjectType::Database)
18143        } else if self.parse_keyword(Keyword::INTEGRATION) {
18144            Some(ActionCreateObjectType::Integration)
18145        } else if self.parse_keyword(Keyword::ROLE) {
18146            Some(ActionCreateObjectType::Role)
18147        } else if self.parse_keyword(Keyword::SCHEMA) {
18148            Some(ActionCreateObjectType::Schema)
18149        } else if self.parse_keyword(Keyword::SHARE) {
18150            Some(ActionCreateObjectType::Share)
18151        } else if self.parse_keyword(Keyword::USER) {
18152            Some(ActionCreateObjectType::User)
18153        } else if self.parse_keyword(Keyword::WAREHOUSE) {
18154            Some(ActionCreateObjectType::Warehouse)
18155        } else {
18156            None
18157        }
18158    }
18159
18160    fn parse_action_apply_type(&mut self) -> Result<ActionApplyType, ParserError> {
18161        if self.parse_keywords(&[Keyword::AGGREGATION, Keyword::POLICY]) {
18162            Ok(ActionApplyType::AggregationPolicy)
18163        } else if self.parse_keywords(&[Keyword::AUTHENTICATION, Keyword::POLICY]) {
18164            Ok(ActionApplyType::AuthenticationPolicy)
18165        } else if self.parse_keywords(&[Keyword::JOIN, Keyword::POLICY]) {
18166            Ok(ActionApplyType::JoinPolicy)
18167        } else if self.parse_keywords(&[Keyword::MASKING, Keyword::POLICY]) {
18168            Ok(ActionApplyType::MaskingPolicy)
18169        } else if self.parse_keywords(&[Keyword::PACKAGES, Keyword::POLICY]) {
18170            Ok(ActionApplyType::PackagesPolicy)
18171        } else if self.parse_keywords(&[Keyword::PASSWORD, Keyword::POLICY]) {
18172            Ok(ActionApplyType::PasswordPolicy)
18173        } else if self.parse_keywords(&[Keyword::PROJECTION, Keyword::POLICY]) {
18174            Ok(ActionApplyType::ProjectionPolicy)
18175        } else if self.parse_keywords(&[Keyword::ROW, Keyword::ACCESS, Keyword::POLICY]) {
18176            Ok(ActionApplyType::RowAccessPolicy)
18177        } else if self.parse_keywords(&[Keyword::SESSION, Keyword::POLICY]) {
18178            Ok(ActionApplyType::SessionPolicy)
18179        } else if self.parse_keyword(Keyword::TAG) {
18180            Ok(ActionApplyType::Tag)
18181        } else {
18182            self.expected_ref("GRANT APPLY type", self.peek_token_ref())
18183        }
18184    }
18185
18186    fn maybe_parse_action_execute_obj_type(&mut self) -> Option<ActionExecuteObjectType> {
18187        if self.parse_keywords(&[Keyword::DATA, Keyword::METRIC, Keyword::FUNCTION]) {
18188            Some(ActionExecuteObjectType::DataMetricFunction)
18189        } else if self.parse_keywords(&[Keyword::MANAGED, Keyword::ALERT]) {
18190            Some(ActionExecuteObjectType::ManagedAlert)
18191        } else if self.parse_keywords(&[Keyword::MANAGED, Keyword::TASK]) {
18192            Some(ActionExecuteObjectType::ManagedTask)
18193        } else if self.parse_keyword(Keyword::ALERT) {
18194            Some(ActionExecuteObjectType::Alert)
18195        } else if self.parse_keyword(Keyword::TASK) {
18196            Some(ActionExecuteObjectType::Task)
18197        } else {
18198            None
18199        }
18200    }
18201
18202    fn parse_action_manage_type(&mut self) -> Result<ActionManageType, ParserError> {
18203        if self.parse_keywords(&[Keyword::ACCOUNT, Keyword::SUPPORT, Keyword::CASES]) {
18204            Ok(ActionManageType::AccountSupportCases)
18205        } else if self.parse_keywords(&[Keyword::EVENT, Keyword::SHARING]) {
18206            Ok(ActionManageType::EventSharing)
18207        } else if self.parse_keywords(&[Keyword::LISTING, Keyword::AUTO, Keyword::FULFILLMENT]) {
18208            Ok(ActionManageType::ListingAutoFulfillment)
18209        } else if self.parse_keywords(&[Keyword::ORGANIZATION, Keyword::SUPPORT, Keyword::CASES]) {
18210            Ok(ActionManageType::OrganizationSupportCases)
18211        } else if self.parse_keywords(&[Keyword::USER, Keyword::SUPPORT, Keyword::CASES]) {
18212            Ok(ActionManageType::UserSupportCases)
18213        } else if self.parse_keyword(Keyword::GRANTS) {
18214            Ok(ActionManageType::Grants)
18215        } else if self.parse_keyword(Keyword::WAREHOUSES) {
18216            Ok(ActionManageType::Warehouses)
18217        } else {
18218            self.expected_ref("GRANT MANAGE type", self.peek_token_ref())
18219        }
18220    }
18221
18222    fn parse_action_modify_type(&mut self) -> Option<ActionModifyType> {
18223        if self.parse_keywords(&[Keyword::LOG, Keyword::LEVEL]) {
18224            Some(ActionModifyType::LogLevel)
18225        } else if self.parse_keywords(&[Keyword::TRACE, Keyword::LEVEL]) {
18226            Some(ActionModifyType::TraceLevel)
18227        } else if self.parse_keywords(&[Keyword::SESSION, Keyword::LOG, Keyword::LEVEL]) {
18228            Some(ActionModifyType::SessionLogLevel)
18229        } else if self.parse_keywords(&[Keyword::SESSION, Keyword::TRACE, Keyword::LEVEL]) {
18230            Some(ActionModifyType::SessionTraceLevel)
18231        } else {
18232            None
18233        }
18234    }
18235
18236    fn parse_action_monitor_type(&mut self) -> Option<ActionMonitorType> {
18237        if self.parse_keyword(Keyword::EXECUTION) {
18238            Some(ActionMonitorType::Execution)
18239        } else if self.parse_keyword(Keyword::SECURITY) {
18240            Some(ActionMonitorType::Security)
18241        } else if self.parse_keyword(Keyword::USAGE) {
18242            Some(ActionMonitorType::Usage)
18243        } else {
18244            None
18245        }
18246    }
18247
18248    /// Parse a grantee name, possibly with a host qualifier (user@host).
18249    pub fn parse_grantee_name(&mut self) -> Result<GranteeName, ParserError> {
18250        let mut name = self.parse_object_name(false)?;
18251        if self.dialect.supports_user_host_grantee()
18252            && name.0.len() == 1
18253            && name.0[0].as_ident().is_some()
18254            && self.consume_token(&Token::AtSign)
18255        {
18256            let user = name.0.pop().unwrap().as_ident().unwrap().clone();
18257            let host = self.parse_identifier()?;
18258            Ok(GranteeName::UserHost { user, host })
18259        } else {
18260            Ok(GranteeName::ObjectName(name))
18261        }
18262    }
18263
18264    /// Parse [`Statement::Deny`]
18265    pub fn parse_deny(&mut self) -> Result<Statement, ParserError> {
18266        self.expect_keyword(Keyword::DENY)?;
18267
18268        let (privileges, objects) = self.parse_grant_deny_revoke_privileges_objects()?;
18269        let objects = match objects {
18270            Some(o) => o,
18271            None => {
18272                return parser_err!(
18273                    "DENY statements must specify an object",
18274                    self.peek_token_ref().span.start
18275                )
18276            }
18277        };
18278
18279        self.expect_keyword_is(Keyword::TO)?;
18280        let grantees = self.parse_grantees()?;
18281        let cascade = self.parse_cascade_option();
18282        let granted_by = if self.parse_keywords(&[Keyword::AS]) {
18283            Some(self.parse_identifier()?)
18284        } else {
18285            None
18286        };
18287
18288        Ok(Statement::Deny(DenyStatement {
18289            privileges,
18290            objects,
18291            grantees,
18292            cascade,
18293            granted_by,
18294        }))
18295    }
18296
18297    /// Parse a REVOKE statement
18298    pub fn parse_revoke(&mut self) -> Result<Revoke, ParserError> {
18299        let (privileges, objects) = self.parse_grant_deny_revoke_privileges_objects()?;
18300
18301        self.expect_keyword_is(Keyword::FROM)?;
18302        let grantees = self.parse_grantees()?;
18303
18304        let granted_by = if self.parse_keywords(&[Keyword::GRANTED, Keyword::BY]) {
18305            Some(self.parse_identifier()?)
18306        } else {
18307            None
18308        };
18309
18310        let cascade = self.parse_cascade_option();
18311
18312        Ok(Revoke {
18313            privileges,
18314            objects,
18315            grantees,
18316            granted_by,
18317            cascade,
18318        })
18319    }
18320
18321    /// Parse an REPLACE statement
18322    pub fn parse_replace(
18323        &mut self,
18324        replace_token: TokenWithSpan,
18325    ) -> Result<Statement, ParserError> {
18326        if !dialect_of!(self is MySqlDialect | GenericDialect) {
18327            return parser_err!(
18328                "Unsupported statement REPLACE",
18329                self.peek_token_ref().span.start
18330            );
18331        }
18332
18333        let mut insert = self.parse_insert(replace_token)?;
18334        if let Statement::Insert(Insert { replace_into, .. }) = &mut insert {
18335            *replace_into = true;
18336        }
18337
18338        Ok(insert)
18339    }
18340
18341    /// Parse an INSERT statement, returning a `Box`ed SetExpr
18342    ///
18343    /// This is used to reduce the size of the stack frames in debug builds
18344    fn parse_insert_setexpr_boxed(
18345        &mut self,
18346        insert_token: TokenWithSpan,
18347    ) -> Result<Box<SetExpr>, ParserError> {
18348        Ok(Box::new(SetExpr::Insert(self.parse_insert(insert_token)?)))
18349    }
18350
18351    /// Parse an INSERT statement
18352    pub fn parse_insert(&mut self, insert_token: TokenWithSpan) -> Result<Statement, ParserError> {
18353        let optimizer_hints = self.maybe_parse_optimizer_hints()?;
18354        let or = self.parse_conflict_clause();
18355        let priority = if !dialect_of!(self is MySqlDialect | GenericDialect) {
18356            None
18357        } else if self.parse_keyword(Keyword::LOW_PRIORITY) {
18358            Some(MysqlInsertPriority::LowPriority)
18359        } else if self.parse_keyword(Keyword::DELAYED) {
18360            Some(MysqlInsertPriority::Delayed)
18361        } else if self.parse_keyword(Keyword::HIGH_PRIORITY) {
18362            Some(MysqlInsertPriority::HighPriority)
18363        } else {
18364            None
18365        };
18366
18367        let ignore = dialect_of!(self is MySqlDialect | GenericDialect)
18368            && self.parse_keyword(Keyword::IGNORE);
18369
18370        let replace_into = false;
18371
18372        let overwrite = self.parse_keyword(Keyword::OVERWRITE);
18373        let into = self.parse_keyword(Keyword::INTO);
18374
18375        let local = self.parse_keyword(Keyword::LOCAL);
18376
18377        if self.parse_keyword(Keyword::DIRECTORY) {
18378            let path = self.parse_literal_string()?;
18379            let file_format = if self.parse_keywords(&[Keyword::STORED, Keyword::AS]) {
18380                Some(self.parse_file_format()?)
18381            } else {
18382                None
18383            };
18384            let source = self.parse_query()?;
18385            Ok(Statement::Directory {
18386                local,
18387                path,
18388                overwrite,
18389                file_format,
18390                source,
18391            })
18392        } else {
18393            // Hive lets you put table here regardless
18394            let table = self.parse_keyword(Keyword::TABLE);
18395            let table_object = self.parse_table_object()?;
18396
18397            let table_alias = if self.dialect.supports_insert_table_alias()
18398                && !self.peek_sub_query()
18399                && self
18400                    .peek_one_of_keywords(&[Keyword::DEFAULT, Keyword::VALUES])
18401                    .is_none()
18402            {
18403                if self.parse_keyword(Keyword::AS) {
18404                    Some(TableAliasWithoutColumns {
18405                        explicit: true,
18406                        alias: self.parse_identifier()?,
18407                    })
18408                } else {
18409                    self.maybe_parse(|parser| parser.parse_identifier())?
18410                        .map(|alias| TableAliasWithoutColumns {
18411                            explicit: false,
18412                            alias,
18413                        })
18414                }
18415            } else {
18416                None
18417            };
18418
18419            let is_mysql = dialect_of!(self is MySqlDialect);
18420
18421            let (columns, partitioned, after_columns, output, source, assignments) = if self
18422                .parse_keywords(&[Keyword::DEFAULT, Keyword::VALUES])
18423            {
18424                (vec![], None, vec![], None, None, vec![])
18425            } else {
18426                let (columns, partitioned, after_columns) = if !self.peek_subquery_start() {
18427                    let columns =
18428                        self.parse_parenthesized_qualified_column_list(Optional, is_mysql)?;
18429
18430                    let partitioned = self.parse_insert_partition()?;
18431                    // Hive allows you to specify columns after partitions as well if you want.
18432                    let after_columns = if dialect_of!(self is HiveDialect) {
18433                        self.parse_parenthesized_column_list(Optional, false)?
18434                    } else {
18435                        vec![]
18436                    };
18437                    (columns, partitioned, after_columns)
18438                } else {
18439                    Default::default()
18440                };
18441
18442                let output = self.maybe_parse_output_clause()?;
18443
18444                let (source, assignments) = if self.peek_keyword(Keyword::FORMAT)
18445                    || self.peek_keyword(Keyword::SETTINGS)
18446                {
18447                    (None, vec![])
18448                } else if self.dialect.supports_insert_set() && self.parse_keyword(Keyword::SET) {
18449                    (None, self.parse_comma_separated(Parser::parse_assignment)?)
18450                } else {
18451                    (Some(self.parse_query()?), vec![])
18452                };
18453
18454                (
18455                    columns,
18456                    partitioned,
18457                    after_columns,
18458                    output,
18459                    source,
18460                    assignments,
18461                )
18462            };
18463
18464            let (format_clause, settings) = if self.dialect.supports_insert_format() {
18465                // Settings always comes before `FORMAT` for ClickHouse:
18466                // <https://clickhouse.com/docs/en/sql-reference/statements/insert-into>
18467                let settings = self.parse_settings()?;
18468
18469                let format = if self.parse_keyword(Keyword::FORMAT) {
18470                    Some(self.parse_input_format_clause()?)
18471                } else {
18472                    None
18473                };
18474
18475                (format, settings)
18476            } else {
18477                Default::default()
18478            };
18479
18480            let insert_alias = if dialect_of!(self is MySqlDialect | GenericDialect)
18481                && self.parse_keyword(Keyword::AS)
18482            {
18483                let row_alias = self.parse_object_name(false)?;
18484                let col_aliases = Some(self.parse_parenthesized_column_list(Optional, false)?);
18485                Some(InsertAliases {
18486                    row_alias,
18487                    col_aliases,
18488                })
18489            } else {
18490                None
18491            };
18492
18493            let on = if self.parse_keyword(Keyword::ON) {
18494                if self.parse_keyword(Keyword::CONFLICT) {
18495                    let conflict_target =
18496                        if self.parse_keywords(&[Keyword::ON, Keyword::CONSTRAINT]) {
18497                            Some(ConflictTarget::OnConstraint(self.parse_object_name(false)?))
18498                        } else if self.peek_token_ref().token == Token::LParen {
18499                            Some(ConflictTarget::Columns(
18500                                self.parse_parenthesized_column_list(IsOptional::Mandatory, false)?,
18501                            ))
18502                        } else {
18503                            None
18504                        };
18505
18506                    self.expect_keyword_is(Keyword::DO)?;
18507                    let action = if self.parse_keyword(Keyword::NOTHING) {
18508                        OnConflictAction::DoNothing
18509                    } else {
18510                        self.expect_keyword_is(Keyword::UPDATE)?;
18511                        self.expect_keyword_is(Keyword::SET)?;
18512                        let assignments = self.parse_comma_separated(Parser::parse_assignment)?;
18513                        let selection = if self.parse_keyword(Keyword::WHERE) {
18514                            Some(self.parse_expr()?)
18515                        } else {
18516                            None
18517                        };
18518                        OnConflictAction::DoUpdate(DoUpdate {
18519                            assignments,
18520                            selection,
18521                        })
18522                    };
18523
18524                    Some(OnInsert::OnConflict(OnConflict {
18525                        conflict_target,
18526                        action,
18527                    }))
18528                } else {
18529                    self.expect_keyword_is(Keyword::DUPLICATE)?;
18530                    self.expect_keyword_is(Keyword::KEY)?;
18531                    self.expect_keyword_is(Keyword::UPDATE)?;
18532                    let l = self.parse_comma_separated(Parser::parse_assignment)?;
18533
18534                    Some(OnInsert::DuplicateKeyUpdate(l))
18535                }
18536            } else {
18537                None
18538            };
18539
18540            let returning = if self.parse_keyword(Keyword::RETURNING) {
18541                Some(self.parse_comma_separated(Parser::parse_select_item)?)
18542            } else {
18543                None
18544            };
18545
18546            Ok(Insert {
18547                insert_token: insert_token.into(),
18548                optimizer_hints,
18549                or,
18550                table: table_object,
18551                table_alias,
18552                ignore,
18553                into,
18554                overwrite,
18555                partitioned,
18556                columns,
18557                after_columns,
18558                source,
18559                assignments,
18560                has_table_keyword: table,
18561                on,
18562                returning,
18563                output,
18564                replace_into,
18565                priority,
18566                insert_alias,
18567                settings,
18568                format_clause,
18569                multi_table_insert_type: None,
18570                multi_table_into_clauses: vec![],
18571                multi_table_when_clauses: vec![],
18572                multi_table_else_clause: None,
18573            }
18574            .into())
18575        }
18576    }
18577
18578    /// Parses input format clause used for ClickHouse.
18579    ///
18580    /// <https://clickhouse.com/docs/en/interfaces/formats>
18581    pub fn parse_input_format_clause(&mut self) -> Result<InputFormatClause, ParserError> {
18582        let ident = self.parse_identifier()?;
18583        let values = self
18584            .maybe_parse(|p| p.parse_comma_separated(|p| p.parse_expr()))?
18585            .unwrap_or_default();
18586
18587        Ok(InputFormatClause { ident, values })
18588    }
18589
18590    /// Returns true if the immediate tokens look like the
18591    /// beginning of a subquery. `(SELECT ...` or `((SELECT ...` etc.
18592    fn peek_subquery_start(&mut self) -> bool {
18593        // Handle (SELECT, ((SELECT, (((SELECT, etc.
18594        // This makes INSERT consistent with other contexts where nested
18595        // parentheses around subqueries are handled by recursive descent.
18596        let mut i = 0;
18597        loop {
18598            match &self.peek_nth_token_ref(i).token {
18599                Token::LParen => i += 1,
18600                Token::Word(w) if w.keyword == Keyword::SELECT => return i > 0,
18601                _ => return false,
18602            }
18603        }
18604    }
18605
18606    /// Returns true if the immediate tokens look like the
18607    /// beginning of a subquery possibly preceded by CTEs;
18608    /// i.e. `(WITH ...` or `(SELECT ...`.
18609    fn peek_subquery_or_cte_start(&mut self) -> bool {
18610        matches!(
18611            self.peek_tokens_ref(),
18612            [
18613                TokenWithSpan {
18614                    token: Token::LParen,
18615                    ..
18616                },
18617                TokenWithSpan {
18618                    token: Token::Word(Word {
18619                        keyword: Keyword::SELECT | Keyword::WITH,
18620                        ..
18621                    }),
18622                    ..
18623                },
18624            ]
18625        )
18626    }
18627
18628    fn parse_conflict_clause(&mut self) -> Option<SqliteOnConflict> {
18629        if self.parse_keywords(&[Keyword::OR, Keyword::REPLACE]) {
18630            Some(SqliteOnConflict::Replace)
18631        } else if self.parse_keywords(&[Keyword::OR, Keyword::ROLLBACK]) {
18632            Some(SqliteOnConflict::Rollback)
18633        } else if self.parse_keywords(&[Keyword::OR, Keyword::ABORT]) {
18634            Some(SqliteOnConflict::Abort)
18635        } else if self.parse_keywords(&[Keyword::OR, Keyword::FAIL]) {
18636            Some(SqliteOnConflict::Fail)
18637        } else if self.parse_keywords(&[Keyword::OR, Keyword::IGNORE]) {
18638            Some(SqliteOnConflict::Ignore)
18639        } else if self.parse_keyword(Keyword::REPLACE) {
18640            Some(SqliteOnConflict::Replace)
18641        } else {
18642            None
18643        }
18644    }
18645
18646    /// Parse an optional `PARTITION (...)` clause for INSERT statements.
18647    pub fn parse_insert_partition(&mut self) -> Result<Option<Vec<Expr>>, ParserError> {
18648        if self.parse_keyword(Keyword::PARTITION) {
18649            self.expect_token(&Token::LParen)?;
18650            let partition_cols = Some(self.parse_comma_separated(Parser::parse_expr)?);
18651            self.expect_token(&Token::RParen)?;
18652            Ok(partition_cols)
18653        } else {
18654            Ok(None)
18655        }
18656    }
18657
18658    /// Parse optional Hive `INPUTFORMAT ... SERDE ...` clause used by LOAD DATA.
18659    pub fn parse_load_data_table_format(
18660        &mut self,
18661    ) -> Result<Option<HiveLoadDataFormat>, ParserError> {
18662        if self.parse_keyword(Keyword::INPUTFORMAT) {
18663            let input_format = self.parse_expr()?;
18664            self.expect_keyword_is(Keyword::SERDE)?;
18665            let serde = self.parse_expr()?;
18666            Ok(Some(HiveLoadDataFormat {
18667                input_format,
18668                serde,
18669            }))
18670        } else {
18671            Ok(None)
18672        }
18673    }
18674
18675    /// Parse an UPDATE statement, returning a `Box`ed SetExpr
18676    ///
18677    /// This is used to reduce the size of the stack frames in debug builds
18678    fn parse_update_setexpr_boxed(
18679        &mut self,
18680        update_token: TokenWithSpan,
18681    ) -> Result<Box<SetExpr>, ParserError> {
18682        Ok(Box::new(SetExpr::Update(self.parse_update(update_token)?)))
18683    }
18684
18685    /// Parse an `UPDATE` statement and return `Statement::Update`.
18686    pub fn parse_update(&mut self, update_token: TokenWithSpan) -> Result<Statement, ParserError> {
18687        let optimizer_hints = self.maybe_parse_optimizer_hints()?;
18688        let or = self.parse_conflict_clause();
18689        let table = self.parse_table_and_joins()?;
18690        let from_before_set = if self.parse_keyword(Keyword::FROM) {
18691            Some(UpdateTableFromKind::BeforeSet(
18692                self.parse_table_with_joins()?,
18693            ))
18694        } else {
18695            None
18696        };
18697        self.expect_keyword(Keyword::SET)?;
18698        let assignments = self.parse_comma_separated(Parser::parse_assignment)?;
18699
18700        let output = self.maybe_parse_output_clause()?;
18701
18702        let from = if from_before_set.is_none() && self.parse_keyword(Keyword::FROM) {
18703            Some(UpdateTableFromKind::AfterSet(
18704                self.parse_table_with_joins()?,
18705            ))
18706        } else {
18707            from_before_set
18708        };
18709        let selection = if self.parse_keyword(Keyword::WHERE) {
18710            Some(self.parse_expr()?)
18711        } else {
18712            None
18713        };
18714        let returning = if self.parse_keyword(Keyword::RETURNING) {
18715            Some(self.parse_comma_separated(Parser::parse_select_item)?)
18716        } else {
18717            None
18718        };
18719        let order_by = if self.dialect.supports_update_order_by()
18720            && self.parse_keywords(&[Keyword::ORDER, Keyword::BY])
18721        {
18722            self.parse_comma_separated(Parser::parse_order_by_expr)?
18723        } else {
18724            vec![]
18725        };
18726        let limit = if self.parse_keyword(Keyword::LIMIT) {
18727            Some(self.parse_expr()?)
18728        } else {
18729            None
18730        };
18731        Ok(Update {
18732            update_token: update_token.into(),
18733            optimizer_hints,
18734            table,
18735            assignments,
18736            from,
18737            selection,
18738            returning,
18739            output,
18740            or,
18741            order_by,
18742            limit,
18743        }
18744        .into())
18745    }
18746
18747    /// Parse a `var = expr` assignment, used in an UPDATE statement
18748    pub fn parse_assignment(&mut self) -> Result<Assignment, ParserError> {
18749        let target = self.parse_assignment_target()?;
18750        self.expect_token(&Token::Eq)?;
18751        let value = self.parse_expr()?;
18752        Ok(Assignment { target, value })
18753    }
18754
18755    /// Parse the left-hand side of an assignment, used in an UPDATE statement
18756    pub fn parse_assignment_target(&mut self) -> Result<AssignmentTarget, ParserError> {
18757        if self.consume_token(&Token::LParen) {
18758            let columns = self.parse_comma_separated(|p| p.parse_object_name(false))?;
18759            self.expect_token(&Token::RParen)?;
18760            Ok(AssignmentTarget::Tuple(columns))
18761        } else {
18762            let column = self.parse_object_name(false)?;
18763            Ok(AssignmentTarget::ColumnName(column))
18764        }
18765    }
18766
18767    /// Parse a single function argument, handling named and unnamed variants.
18768    pub fn parse_function_args(&mut self) -> Result<FunctionArg, ParserError> {
18769        let arg = if self.dialect.supports_named_fn_args_with_expr_name() {
18770            self.maybe_parse(|p| {
18771                let name = p.parse_expr()?;
18772                let operator = p.parse_function_named_arg_operator()?;
18773                let arg = p.parse_wildcard_expr()?.into();
18774                Ok(FunctionArg::ExprNamed {
18775                    name,
18776                    arg,
18777                    operator,
18778                })
18779            })?
18780        } else {
18781            self.maybe_parse(|p| {
18782                let name = p.parse_identifier()?;
18783                let operator = p.parse_function_named_arg_operator()?;
18784                let arg = p.parse_wildcard_expr()?.into();
18785                Ok(FunctionArg::Named {
18786                    name,
18787                    arg,
18788                    operator,
18789                })
18790            })?
18791        };
18792        if let Some(arg) = arg {
18793            return Ok(arg);
18794        }
18795        let wildcard_expr = self.parse_wildcard_expr()?;
18796        let arg_expr: FunctionArgExpr = match wildcard_expr {
18797            Expr::Wildcard(ref token) if self.dialect.supports_select_wildcard_exclude() => {
18798                // Support `* EXCLUDE(col1, col2, ...)` inside function calls (e.g. Snowflake's
18799                // `HASH(* EXCLUDE(col))`).  Parse the options the same way SELECT items do.
18800                let opts = self.parse_wildcard_additional_options(token.0.clone())?;
18801                if opts.opt_exclude.is_some()
18802                    || opts.opt_except.is_some()
18803                    || opts.opt_replace.is_some()
18804                    || opts.opt_rename.is_some()
18805                    || opts.opt_ilike.is_some()
18806                {
18807                    FunctionArgExpr::WildcardWithOptions(opts)
18808                } else {
18809                    wildcard_expr.into()
18810                }
18811            }
18812            other => other.into(),
18813        };
18814        // Aliased argument, e.g. `XMLFOREST(a AS x)` in PostgreSQL
18815        let arg_expr = match arg_expr {
18816            FunctionArgExpr::Expr(expr)
18817                if self.dialect.supports_aliased_function_args()
18818                    && self.parse_keyword(Keyword::AS) =>
18819            {
18820                FunctionArgExpr::Expr(Expr::Named {
18821                    expr: expr.into(),
18822                    name: self.parse_identifier()?,
18823                })
18824            }
18825            other => other,
18826        };
18827        Ok(FunctionArg::Unnamed(arg_expr))
18828    }
18829
18830    fn parse_function_named_arg_operator(&mut self) -> Result<FunctionArgOperator, ParserError> {
18831        if self.parse_keyword(Keyword::VALUE) {
18832            return Ok(FunctionArgOperator::Value);
18833        }
18834        let tok = self.next_token();
18835        match tok.token {
18836            Token::RArrow if self.dialect.supports_named_fn_args_with_rarrow_operator() => {
18837                Ok(FunctionArgOperator::RightArrow)
18838            }
18839            Token::Eq if self.dialect.supports_named_fn_args_with_eq_operator() => {
18840                Ok(FunctionArgOperator::Equals)
18841            }
18842            Token::Assignment
18843                if self
18844                    .dialect
18845                    .supports_named_fn_args_with_assignment_operator() =>
18846            {
18847                Ok(FunctionArgOperator::Assignment)
18848            }
18849            Token::Colon if self.dialect.supports_named_fn_args_with_colon_operator() => {
18850                Ok(FunctionArgOperator::Colon)
18851            }
18852            _ => {
18853                self.prev_token();
18854                self.expected("argument operator", tok)
18855            }
18856        }
18857    }
18858
18859    /// Parse an optional, comma-separated list of function arguments (consumes closing paren).
18860    pub fn parse_optional_args(&mut self) -> Result<Vec<FunctionArg>, ParserError> {
18861        if self.consume_token(&Token::RParen) {
18862            Ok(vec![])
18863        } else {
18864            let args = self.parse_comma_separated(Parser::parse_function_args)?;
18865            self.expect_token(&Token::RParen)?;
18866            Ok(args)
18867        }
18868    }
18869
18870    fn parse_table_function_args(&mut self) -> Result<TableFunctionArgs, ParserError> {
18871        if self.consume_token(&Token::RParen) {
18872            return Ok(TableFunctionArgs {
18873                args: vec![],
18874                settings: None,
18875            });
18876        }
18877        let mut args = vec![];
18878        let settings = loop {
18879            if let Some(settings) = self.parse_settings()? {
18880                break Some(settings);
18881            }
18882            args.push(self.parse_function_args()?);
18883            if self.is_parse_comma_separated_end() {
18884                break None;
18885            }
18886        };
18887        self.expect_token(&Token::RParen)?;
18888        Ok(TableFunctionArgs { args, settings })
18889    }
18890
18891    /// Parses a potentially empty list of arguments to a function
18892    /// (including the closing parenthesis).
18893    ///
18894    /// Examples:
18895    /// ```sql
18896    /// FIRST_VALUE(x ORDER BY 1,2,3);
18897    /// FIRST_VALUE(x IGNORE NULL);
18898    /// ```
18899    fn parse_function_argument_list(&mut self) -> Result<FunctionArgumentList, ParserError> {
18900        let mut clauses = vec![];
18901
18902        // Handle clauses that may exist with an empty argument list
18903
18904        if let Some(null_clause) = self.parse_json_null_clause() {
18905            clauses.push(FunctionArgumentClause::JsonNullClause(null_clause));
18906        }
18907
18908        if let Some(json_returning_clause) = self.maybe_parse_json_returning_clause()? {
18909            clauses.push(FunctionArgumentClause::JsonReturningClause(
18910                json_returning_clause,
18911            ));
18912        }
18913
18914        if self.consume_token(&Token::RParen) {
18915            return Ok(FunctionArgumentList {
18916                duplicate_treatment: None,
18917                args: vec![],
18918                clauses,
18919            });
18920        }
18921
18922        let duplicate_treatment = self.parse_duplicate_treatment()?;
18923        let args = self.parse_comma_separated(Parser::parse_function_args)?;
18924
18925        if self.dialect.supports_window_function_null_treatment_arg() {
18926            if let Some(null_treatment) = self.parse_null_treatment()? {
18927                clauses.push(FunctionArgumentClause::IgnoreOrRespectNulls(null_treatment));
18928            }
18929        }
18930
18931        if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
18932            clauses.push(FunctionArgumentClause::OrderBy(
18933                self.parse_comma_separated(Parser::parse_order_by_expr)?,
18934            ));
18935        }
18936
18937        if self.parse_keyword(Keyword::LIMIT) {
18938            clauses.push(FunctionArgumentClause::Limit(self.parse_expr()?));
18939        }
18940
18941        if dialect_of!(self is GenericDialect | BigQueryDialect)
18942            && self.parse_keyword(Keyword::HAVING)
18943        {
18944            let kind = match self.expect_one_of_keywords(&[Keyword::MIN, Keyword::MAX])? {
18945                Keyword::MIN => HavingBoundKind::Min,
18946                Keyword::MAX => HavingBoundKind::Max,
18947                unexpected_keyword => return Err(ParserError::ParserError(
18948                    format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in having bound"),
18949                )),
18950            };
18951            clauses.push(FunctionArgumentClause::Having(HavingBound(
18952                kind,
18953                self.parse_expr()?,
18954            )))
18955        }
18956
18957        if dialect_of!(self is GenericDialect | MySqlDialect)
18958            && self.parse_keyword(Keyword::SEPARATOR)
18959        {
18960            clauses.push(FunctionArgumentClause::Separator(self.parse_value()?));
18961        }
18962
18963        if let Some(on_overflow) = self.parse_listagg_on_overflow()? {
18964            clauses.push(FunctionArgumentClause::OnOverflow(on_overflow));
18965        }
18966
18967        if let Some(null_clause) = self.parse_json_null_clause() {
18968            clauses.push(FunctionArgumentClause::JsonNullClause(null_clause));
18969        }
18970
18971        if let Some(json_returning_clause) = self.maybe_parse_json_returning_clause()? {
18972            clauses.push(FunctionArgumentClause::JsonReturningClause(
18973                json_returning_clause,
18974            ));
18975        }
18976
18977        self.expect_token(&Token::RParen)?;
18978        Ok(FunctionArgumentList {
18979            duplicate_treatment,
18980            args,
18981            clauses,
18982        })
18983    }
18984
18985    fn parse_json_null_clause(&mut self) -> Option<JsonNullClause> {
18986        if self.parse_keywords(&[Keyword::ABSENT, Keyword::ON, Keyword::NULL]) {
18987            Some(JsonNullClause::AbsentOnNull)
18988        } else if self.parse_keywords(&[Keyword::NULL, Keyword::ON, Keyword::NULL]) {
18989            Some(JsonNullClause::NullOnNull)
18990        } else {
18991            None
18992        }
18993    }
18994
18995    fn maybe_parse_json_returning_clause(
18996        &mut self,
18997    ) -> Result<Option<JsonReturningClause>, ParserError> {
18998        if self.parse_keyword(Keyword::RETURNING) {
18999            let data_type = self.parse_data_type()?;
19000            Ok(Some(JsonReturningClause { data_type }))
19001        } else {
19002            Ok(None)
19003        }
19004    }
19005
19006    fn parse_duplicate_treatment(&mut self) -> Result<Option<DuplicateTreatment>, ParserError> {
19007        let loc = self.peek_token_ref().span.start;
19008        match (
19009            self.parse_keyword(Keyword::ALL),
19010            self.parse_keyword(Keyword::DISTINCT),
19011        ) {
19012            (true, false) => Ok(Some(DuplicateTreatment::All)),
19013            (false, true) => Ok(Some(DuplicateTreatment::Distinct)),
19014            (false, false) => Ok(None),
19015            (true, true) => parser_err!("Cannot specify both ALL and DISTINCT".to_string(), loc),
19016        }
19017    }
19018
19019    /// Parse a comma-delimited list of projections after SELECT
19020    pub fn parse_select_item(&mut self) -> Result<SelectItem, ParserError> {
19021        let prefix = self
19022            .parse_one_of_keywords(
19023                self.dialect
19024                    .get_reserved_keywords_for_select_item_operator(),
19025            )
19026            .map(|keyword| Ident::new(format!("{keyword:?}")));
19027
19028        match self.parse_wildcard_expr()? {
19029            Expr::QualifiedWildcard(prefix, token) => Ok(SelectItem::QualifiedWildcard(
19030                SelectItemQualifiedWildcardKind::ObjectName(prefix),
19031                self.parse_wildcard_additional_options(token.0)?,
19032            )),
19033            Expr::Wildcard(token) => Ok(SelectItem::Wildcard(
19034                self.parse_wildcard_additional_options(token.0)?,
19035            )),
19036            Expr::Identifier(v) if v.value.to_lowercase() == "from" && v.quote_style.is_none() => {
19037                parser_err!(
19038                    format!("Expected an expression, found: {}", v),
19039                    self.peek_token_ref().span.start
19040                )
19041            }
19042            Expr::BinaryOp {
19043                left,
19044                op: BinaryOperator::Eq,
19045                right,
19046            } if self.dialect.supports_eq_alias_assignment()
19047                && matches!(left.as_ref(), Expr::Identifier(_)) =>
19048            {
19049                let Expr::Identifier(alias) = *left else {
19050                    return parser_err!(
19051                        "BUG: expected identifier expression as alias",
19052                        self.peek_token_ref().span.start
19053                    );
19054                };
19055                Ok(SelectItem::ExprWithAlias {
19056                    expr: *right,
19057                    alias,
19058                })
19059            }
19060            expr if self.dialect.supports_select_expr_star()
19061                && self.consume_tokens(&[Token::Period, Token::Mul]) =>
19062            {
19063                let wildcard_token = self.get_previous_token().clone();
19064                Ok(SelectItem::QualifiedWildcard(
19065                    SelectItemQualifiedWildcardKind::Expr(expr),
19066                    self.parse_wildcard_additional_options(wildcard_token)?,
19067                ))
19068            }
19069            expr if self.dialect.supports_select_item_multi_column_alias()
19070                && self.peek_keyword(Keyword::AS)
19071                && self.peek_nth_token(1).token == Token::LParen =>
19072            {
19073                self.expect_keyword(Keyword::AS)?;
19074                self.expect_token(&Token::LParen)?;
19075                let aliases = self.parse_comma_separated(|p| p.parse_identifier())?;
19076                self.expect_token(&Token::RParen)?;
19077                Ok(SelectItem::ExprWithAliases {
19078                    expr: maybe_prefixed_expr(expr, prefix),
19079                    aliases,
19080                })
19081            }
19082            expr => self
19083                .maybe_parse_select_item_alias()
19084                .map(|alias| match alias {
19085                    Some(alias) => SelectItem::ExprWithAlias {
19086                        expr: maybe_prefixed_expr(expr, prefix),
19087                        alias,
19088                    },
19089                    None => SelectItem::UnnamedExpr(maybe_prefixed_expr(expr, prefix)),
19090                }),
19091        }
19092    }
19093
19094    /// Parse an [`WildcardAdditionalOptions`] information for wildcard select items.
19095    ///
19096    /// If it is not possible to parse it, will return an option.
19097    pub fn parse_wildcard_additional_options(
19098        &mut self,
19099        wildcard_token: TokenWithSpan,
19100    ) -> Result<WildcardAdditionalOptions, ParserError> {
19101        let opt_ilike = if self.dialect.supports_select_wildcard_ilike() {
19102            self.parse_optional_select_item_ilike()?
19103        } else {
19104            None
19105        };
19106        let opt_exclude = if opt_ilike.is_none() && self.dialect.supports_select_wildcard_exclude()
19107        {
19108            self.parse_optional_select_item_exclude()?
19109        } else {
19110            None
19111        };
19112        let opt_except = if self.dialect.supports_select_wildcard_except() {
19113            self.parse_optional_select_item_except()?
19114        } else {
19115            None
19116        };
19117        let opt_replace = if self.dialect.supports_select_wildcard_replace() {
19118            self.parse_optional_select_item_replace()?
19119        } else {
19120            None
19121        };
19122        let opt_rename = if self.dialect.supports_select_wildcard_rename() {
19123            self.parse_optional_select_item_rename()?
19124        } else {
19125            None
19126        };
19127
19128        let opt_alias = if self.dialect.supports_select_wildcard_with_alias() {
19129            self.maybe_parse_select_item_alias()?
19130        } else {
19131            None
19132        };
19133
19134        Ok(WildcardAdditionalOptions {
19135            wildcard_token: wildcard_token.into(),
19136            opt_ilike,
19137            opt_exclude,
19138            opt_except,
19139            opt_rename,
19140            opt_replace,
19141            opt_alias,
19142        })
19143    }
19144
19145    /// Parse an [`Ilike`](IlikeSelectItem) information for wildcard select items.
19146    ///
19147    /// If it is not possible to parse it, will return an option.
19148    pub fn parse_optional_select_item_ilike(
19149        &mut self,
19150    ) -> Result<Option<IlikeSelectItem>, ParserError> {
19151        let opt_ilike = if self.parse_keyword(Keyword::ILIKE) {
19152            let next_token = self.next_token();
19153            let pattern = match next_token.token {
19154                Token::SingleQuotedString(s) => s,
19155                _ => return self.expected("ilike pattern", next_token),
19156            };
19157            Some(IlikeSelectItem { pattern })
19158        } else {
19159            None
19160        };
19161        Ok(opt_ilike)
19162    }
19163
19164    /// Parse an [`Exclude`](ExcludeSelectItem) information for wildcard select items.
19165    ///
19166    /// If it is not possible to parse it, will return an option.
19167    pub fn parse_optional_select_item_exclude(
19168        &mut self,
19169    ) -> Result<Option<ExcludeSelectItem>, ParserError> {
19170        let opt_exclude = if self.parse_keyword(Keyword::EXCLUDE) {
19171            if self.consume_token(&Token::LParen) {
19172                let columns =
19173                    self.parse_comma_separated(|parser| parser.parse_object_name(false))?;
19174                self.expect_token(&Token::RParen)?;
19175                Some(ExcludeSelectItem::Multiple(columns))
19176            } else {
19177                let column = self.parse_object_name(false)?;
19178                Some(ExcludeSelectItem::Single(column))
19179            }
19180        } else {
19181            None
19182        };
19183
19184        Ok(opt_exclude)
19185    }
19186
19187    /// Parse an [`Except`](ExceptSelectItem) information for wildcard select items.
19188    ///
19189    /// If it is not possible to parse it, will return an option.
19190    pub fn parse_optional_select_item_except(
19191        &mut self,
19192    ) -> Result<Option<ExceptSelectItem>, ParserError> {
19193        let opt_except = if self.parse_keyword(Keyword::EXCEPT) {
19194            if self.peek_token_ref().token == Token::LParen {
19195                let idents = self.parse_parenthesized_column_list(Mandatory, false)?;
19196                match &idents[..] {
19197                    [] => {
19198                        return self.expected_ref(
19199                            "at least one column should be parsed by the expect clause",
19200                            self.peek_token_ref(),
19201                        )?;
19202                    }
19203                    [first, idents @ ..] => Some(ExceptSelectItem {
19204                        first_element: first.clone(),
19205                        additional_elements: idents.to_vec(),
19206                    }),
19207                }
19208            } else {
19209                // Clickhouse allows EXCEPT column_name
19210                let ident = self.parse_identifier()?;
19211                Some(ExceptSelectItem {
19212                    first_element: ident,
19213                    additional_elements: vec![],
19214                })
19215            }
19216        } else {
19217            None
19218        };
19219
19220        Ok(opt_except)
19221    }
19222
19223    /// Parse a [`Rename`](RenameSelectItem) information for wildcard select items.
19224    pub fn parse_optional_select_item_rename(
19225        &mut self,
19226    ) -> Result<Option<RenameSelectItem>, ParserError> {
19227        let opt_rename = if self.parse_keyword(Keyword::RENAME) {
19228            if self.consume_token(&Token::LParen) {
19229                let idents =
19230                    self.parse_comma_separated(|parser| parser.parse_identifier_with_alias())?;
19231                self.expect_token(&Token::RParen)?;
19232                Some(RenameSelectItem::Multiple(idents))
19233            } else {
19234                let ident = self.parse_identifier_with_alias()?;
19235                Some(RenameSelectItem::Single(ident))
19236            }
19237        } else {
19238            None
19239        };
19240
19241        Ok(opt_rename)
19242    }
19243
19244    /// Parse a [`Replace`](ReplaceSelectItem) information for wildcard select items.
19245    pub fn parse_optional_select_item_replace(
19246        &mut self,
19247    ) -> Result<Option<ReplaceSelectItem>, ParserError> {
19248        let opt_replace = if self.parse_keyword(Keyword::REPLACE) {
19249            if self.consume_token(&Token::LParen) {
19250                let items = self.parse_comma_separated(|parser| {
19251                    Ok(Box::new(parser.parse_replace_elements()?))
19252                })?;
19253                self.expect_token(&Token::RParen)?;
19254                Some(ReplaceSelectItem { items })
19255            } else {
19256                let tok = self.next_token();
19257                return self.expected("( after REPLACE but", tok);
19258            }
19259        } else {
19260            None
19261        };
19262
19263        Ok(opt_replace)
19264    }
19265    /// Parse a single element of a `REPLACE (...)` select-item clause.
19266    pub fn parse_replace_elements(&mut self) -> Result<ReplaceSelectElement, ParserError> {
19267        let expr = self.parse_expr()?;
19268        let as_keyword = self.parse_keyword(Keyword::AS);
19269        let ident = self.parse_identifier()?;
19270        Ok(ReplaceSelectElement {
19271            expr,
19272            column_name: ident,
19273            as_keyword,
19274        })
19275    }
19276
19277    /// Parse ASC or DESC, returns an Option with true if ASC, false of DESC or `None` if none of
19278    /// them.
19279    pub fn parse_asc_desc(&mut self) -> Option<bool> {
19280        if self.parse_keyword(Keyword::ASC) {
19281            Some(true)
19282        } else if self.parse_keyword(Keyword::DESC) {
19283            Some(false)
19284        } else {
19285            None
19286        }
19287    }
19288
19289    /// Parse ASC or DESC and map to [OrderBySort].
19290    fn parse_optional_order_by_sort(&mut self) -> Option<OrderBySort> {
19291        match self.parse_asc_desc() {
19292            Some(true) => Some(OrderBySort::Asc),
19293            Some(false) => Some(OrderBySort::Desc),
19294            None => None,
19295        }
19296    }
19297
19298    /// Parse an [OrderByExpr] expression.
19299    pub fn parse_order_by_expr(&mut self) -> Result<OrderByExpr, ParserError> {
19300        self.parse_order_by_expr_inner(false)
19301            .map(|(order_by, _)| order_by)
19302    }
19303
19304    /// Parse an [IndexColumn].
19305    pub fn parse_create_index_expr(&mut self) -> Result<IndexColumn, ParserError> {
19306        self.parse_order_by_expr_inner(true)
19307            .map(|(column, operator_class)| IndexColumn {
19308                column,
19309                operator_class,
19310            })
19311    }
19312
19313    fn parse_order_by_expr_inner(
19314        &mut self,
19315        with_operator_class: bool,
19316    ) -> Result<(OrderByExpr, Option<ObjectName>), ParserError> {
19317        let expr = self.parse_expr()?;
19318
19319        let operator_class: Option<ObjectName> = if with_operator_class {
19320            // We check that if non of the following keywords are present, then we parse an
19321            // identifier as operator class.
19322            if self
19323                .peek_one_of_keywords(&[Keyword::ASC, Keyword::DESC, Keyword::NULLS, Keyword::WITH])
19324                .is_some()
19325            {
19326                None
19327            } else {
19328                self.maybe_parse(|parser| parser.parse_object_name(false))?
19329            }
19330        } else {
19331            None
19332        };
19333
19334        let options = if !with_operator_class
19335            && self.dialect.supports_order_by_using_operator()
19336            && self.parse_keyword(Keyword::USING)
19337        {
19338            let op = self.parse_order_by_using_operator()?;
19339            OrderByOptions {
19340                sort: Some(OrderBySort::Using(op)),
19341                nulls_first: self.parse_null_ordering_modifier(),
19342            }
19343        } else {
19344            self.parse_order_by_options()?
19345        };
19346
19347        let with_fill = if self.dialect.supports_with_fill()
19348            && self.parse_keywords(&[Keyword::WITH, Keyword::FILL])
19349        {
19350            Some(self.parse_with_fill()?)
19351        } else {
19352            None
19353        };
19354
19355        Ok((
19356            OrderByExpr {
19357                expr,
19358                options,
19359                with_fill,
19360            },
19361            operator_class,
19362        ))
19363    }
19364
19365    fn parse_order_by_using_operator(&mut self) -> Result<ObjectName, ParserError> {
19366        if self.parse_keyword(Keyword::OPERATOR) {
19367            self.expect_token(&Token::LParen)?;
19368            let operator_name = self.parse_operator_name()?;
19369            self.expect_token(&Token::RParen)?;
19370            return Ok(operator_name);
19371        }
19372
19373        let token = self.next_token();
19374        Ok(ObjectName::from(vec![Ident::new(token.token.to_string())]))
19375    }
19376
19377    fn parse_null_ordering_modifier(&mut self) -> Option<bool> {
19378        if self.parse_keywords(&[Keyword::NULLS, Keyword::FIRST]) {
19379            Some(true)
19380        } else if self.parse_keywords(&[Keyword::NULLS, Keyword::LAST]) {
19381            Some(false)
19382        } else {
19383            None
19384        }
19385    }
19386
19387    fn parse_order_by_options(&mut self) -> Result<OrderByOptions, ParserError> {
19388        let sort = self.parse_optional_order_by_sort();
19389        let nulls_first = self.parse_null_ordering_modifier();
19390
19391        Ok(OrderByOptions { sort, nulls_first })
19392    }
19393
19394    // Parse a WITH FILL clause (ClickHouse dialect)
19395    // that follow the WITH FILL keywords in a ORDER BY clause
19396    /// Parse a `WITH FILL` clause used in ORDER BY (ClickHouse dialect).
19397    pub fn parse_with_fill(&mut self) -> Result<WithFill, ParserError> {
19398        let from = if self.parse_keyword(Keyword::FROM) {
19399            Some(self.parse_expr()?)
19400        } else {
19401            None
19402        };
19403
19404        let to = if self.parse_keyword(Keyword::TO) {
19405            Some(self.parse_expr()?)
19406        } else {
19407            None
19408        };
19409
19410        let step = if self.parse_keyword(Keyword::STEP) {
19411            Some(self.parse_expr()?)
19412        } else {
19413            None
19414        };
19415
19416        Ok(WithFill { from, to, step })
19417    }
19418
19419    /// Parse a set of comma separated INTERPOLATE expressions (ClickHouse dialect)
19420    /// that follow the INTERPOLATE keyword in an ORDER BY clause with the WITH FILL modifier
19421    pub fn parse_interpolations(&mut self) -> Result<Option<Interpolate>, ParserError> {
19422        if !self.parse_keyword(Keyword::INTERPOLATE) {
19423            return Ok(None);
19424        }
19425
19426        if self.consume_token(&Token::LParen) {
19427            let interpolations =
19428                self.parse_comma_separated0(|p| p.parse_interpolation(), Token::RParen)?;
19429            self.expect_token(&Token::RParen)?;
19430            // INTERPOLATE () and INTERPOLATE ( ... ) variants
19431            return Ok(Some(Interpolate {
19432                exprs: Some(interpolations),
19433            }));
19434        }
19435
19436        // INTERPOLATE
19437        Ok(Some(Interpolate { exprs: None }))
19438    }
19439
19440    /// Parse a INTERPOLATE expression (ClickHouse dialect)
19441    pub fn parse_interpolation(&mut self) -> Result<InterpolateExpr, ParserError> {
19442        let column = self.parse_identifier()?;
19443        let expr = if self.parse_keyword(Keyword::AS) {
19444            Some(self.parse_expr()?)
19445        } else {
19446            None
19447        };
19448        Ok(InterpolateExpr { column, expr })
19449    }
19450
19451    /// Parse a TOP clause, MSSQL equivalent of LIMIT,
19452    /// that follows after `SELECT [DISTINCT]`.
19453    pub fn parse_top(&mut self) -> Result<Top, ParserError> {
19454        let quantity = if self.consume_token(&Token::LParen) {
19455            let quantity = self.parse_expr()?;
19456            self.expect_token(&Token::RParen)?;
19457            Some(TopQuantity::Expr(quantity))
19458        } else {
19459            let next_token = self.next_token();
19460            let quantity = match next_token.token {
19461                Token::Number(s, _) => Self::parse::<u64>(s, next_token.span.start)?,
19462                _ => self.expected("literal int", next_token)?,
19463            };
19464            Some(TopQuantity::Constant(quantity))
19465        };
19466
19467        let percent = self.parse_keyword(Keyword::PERCENT);
19468
19469        let with_ties = self.parse_keywords(&[Keyword::WITH, Keyword::TIES]);
19470
19471        Ok(Top {
19472            with_ties,
19473            percent,
19474            quantity,
19475        })
19476    }
19477
19478    /// Parse a LIMIT clause
19479    pub fn parse_limit(&mut self) -> Result<Option<Expr>, ParserError> {
19480        if self.parse_keyword(Keyword::ALL) {
19481            Ok(None)
19482        } else {
19483            Ok(Some(self.parse_expr()?))
19484        }
19485    }
19486
19487    /// Parse an OFFSET clause
19488    pub fn parse_offset(&mut self) -> Result<Offset, ParserError> {
19489        let value = self.parse_expr()?;
19490        let rows = if self.parse_keyword(Keyword::ROW) {
19491            OffsetRows::Row
19492        } else if self.parse_keyword(Keyword::ROWS) {
19493            OffsetRows::Rows
19494        } else {
19495            OffsetRows::None
19496        };
19497        Ok(Offset { value, rows })
19498    }
19499
19500    /// Parse a FETCH clause
19501    pub fn parse_fetch(&mut self) -> Result<Fetch, ParserError> {
19502        let _ = self.parse_one_of_keywords(&[Keyword::FIRST, Keyword::NEXT]);
19503
19504        let (quantity, percent) = if self
19505            .parse_one_of_keywords(&[Keyword::ROW, Keyword::ROWS])
19506            .is_some()
19507        {
19508            (None, false)
19509        } else {
19510            let quantity = Expr::Value(self.parse_value()?);
19511            let percent = self.parse_keyword(Keyword::PERCENT);
19512            let _ = self.parse_one_of_keywords(&[Keyword::ROW, Keyword::ROWS]);
19513            (Some(quantity), percent)
19514        };
19515
19516        let with_ties = if self.parse_keyword(Keyword::ONLY) {
19517            false
19518        } else {
19519            self.parse_keywords(&[Keyword::WITH, Keyword::TIES])
19520        };
19521
19522        Ok(Fetch {
19523            with_ties,
19524            percent,
19525            quantity,
19526        })
19527    }
19528
19529    /// Parse a FOR UPDATE/FOR SHARE clause
19530    pub fn parse_lock(&mut self) -> Result<LockClause, ParserError> {
19531        let lock_type = match self.expect_one_of_keywords(&[Keyword::UPDATE, Keyword::SHARE])? {
19532            Keyword::UPDATE => LockType::Update,
19533            Keyword::SHARE => LockType::Share,
19534            unexpected_keyword => return Err(ParserError::ParserError(
19535                format!("Internal parser error: expected any of {{UPDATE, SHARE}}, got {unexpected_keyword:?}"),
19536            )),
19537        };
19538        let of = if self.parse_keyword(Keyword::OF) {
19539            Some(self.parse_object_name(false)?)
19540        } else {
19541            None
19542        };
19543        let nonblock = if self.parse_keyword(Keyword::NOWAIT) {
19544            Some(NonBlock::Nowait)
19545        } else if self.parse_keywords(&[Keyword::SKIP, Keyword::LOCKED]) {
19546            Some(NonBlock::SkipLocked)
19547        } else {
19548            None
19549        };
19550        Ok(LockClause {
19551            lock_type,
19552            of,
19553            nonblock,
19554        })
19555    }
19556
19557    /// Parse a PostgreSQL `LOCK` statement.
19558    pub fn parse_lock_statement(&mut self) -> Result<Lock, ParserError> {
19559        self.expect_keyword(Keyword::LOCK)?;
19560
19561        if self.peek_keyword(Keyword::TABLES) {
19562            return self.expected_ref("TABLE or a table name", self.peek_token_ref());
19563        }
19564
19565        let _ = self.parse_keyword(Keyword::TABLE);
19566        let tables = self.parse_comma_separated(Parser::parse_lock_table_target)?;
19567        let lock_mode = if self.parse_keyword(Keyword::IN) {
19568            let lock_mode = self.parse_lock_table_mode()?;
19569            self.expect_keyword(Keyword::MODE)?;
19570            Some(lock_mode)
19571        } else {
19572            None
19573        };
19574        let nowait = self.parse_keyword(Keyword::NOWAIT);
19575
19576        Ok(Lock {
19577            tables,
19578            lock_mode,
19579            nowait,
19580        })
19581    }
19582
19583    fn parse_lock_table_target(&mut self) -> Result<LockTableTarget, ParserError> {
19584        let only = self.parse_keyword(Keyword::ONLY);
19585        let name = self.parse_object_name(false)?;
19586        let has_asterisk = self.consume_token(&Token::Mul);
19587
19588        Ok(LockTableTarget {
19589            name,
19590            only,
19591            has_asterisk,
19592        })
19593    }
19594
19595    fn parse_lock_table_mode(&mut self) -> Result<LockTableMode, ParserError> {
19596        if self.parse_keywords(&[Keyword::ACCESS, Keyword::SHARE]) {
19597            Ok(LockTableMode::AccessShare)
19598        } else if self.parse_keywords(&[Keyword::ACCESS, Keyword::EXCLUSIVE]) {
19599            Ok(LockTableMode::AccessExclusive)
19600        } else if self.parse_keywords(&[Keyword::ROW, Keyword::SHARE]) {
19601            Ok(LockTableMode::RowShare)
19602        } else if self.parse_keywords(&[Keyword::ROW, Keyword::EXCLUSIVE]) {
19603            Ok(LockTableMode::RowExclusive)
19604        } else if self.parse_keywords(&[Keyword::SHARE, Keyword::UPDATE, Keyword::EXCLUSIVE]) {
19605            Ok(LockTableMode::ShareUpdateExclusive)
19606        } else if self.parse_keywords(&[Keyword::SHARE, Keyword::ROW, Keyword::EXCLUSIVE]) {
19607            Ok(LockTableMode::ShareRowExclusive)
19608        } else if self.parse_keyword(Keyword::SHARE) {
19609            Ok(LockTableMode::Share)
19610        } else if self.parse_keyword(Keyword::EXCLUSIVE) {
19611            Ok(LockTableMode::Exclusive)
19612        } else {
19613            self.expected_ref("a PostgreSQL LOCK TABLE mode", self.peek_token_ref())
19614        }
19615    }
19616
19617    /// Parse a VALUES clause
19618    pub fn parse_values(
19619        &mut self,
19620        allow_empty: bool,
19621        value_keyword: bool,
19622    ) -> Result<Values, ParserError> {
19623        let mut explicit_row = false;
19624
19625        let rows = self.parse_comma_separated(|parser| {
19626            if parser.parse_keyword(Keyword::ROW) {
19627                explicit_row = true;
19628            }
19629            Ok(Parens {
19630                opening_token: parser.expect_token(&Token::LParen)?.into(),
19631                content: if allow_empty && parser.peek_token_ref().token == Token::RParen {
19632                    vec![]
19633                } else {
19634                    parser.parse_comma_separated(Parser::parse_expr)?
19635                },
19636                closing_token: parser.expect_token(&Token::RParen)?.into(),
19637            })
19638        })?;
19639        Ok(Values {
19640            explicit_row,
19641            rows,
19642            value_keyword,
19643        })
19644    }
19645
19646    /// Parse a 'START TRANSACTION' statement
19647    pub fn parse_start_transaction(&mut self) -> Result<Statement, ParserError> {
19648        self.expect_keyword_is(Keyword::TRANSACTION)?;
19649        Ok(Statement::StartTransaction {
19650            modes: self.parse_transaction_modes()?,
19651            begin: false,
19652            transaction: Some(BeginTransactionKind::Transaction),
19653            modifier: None,
19654            statements: vec![],
19655            exception: None,
19656            has_end_keyword: false,
19657        })
19658    }
19659
19660    /// Parse a transaction modifier keyword that can follow a `BEGIN` statement.
19661    pub(crate) fn parse_transaction_modifier(&mut self) -> Option<TransactionModifier> {
19662        if !self.dialect.supports_start_transaction_modifier() {
19663            None
19664        } else if self.parse_keyword(Keyword::DEFERRED) {
19665            Some(TransactionModifier::Deferred)
19666        } else if self.parse_keyword(Keyword::IMMEDIATE) {
19667            Some(TransactionModifier::Immediate)
19668        } else if self.parse_keyword(Keyword::EXCLUSIVE) {
19669            Some(TransactionModifier::Exclusive)
19670        } else if self.parse_keyword(Keyword::TRY) {
19671            Some(TransactionModifier::Try)
19672        } else if self.parse_keyword(Keyword::CATCH) {
19673            Some(TransactionModifier::Catch)
19674        } else {
19675            None
19676        }
19677    }
19678
19679    /// Parse a 'BEGIN' statement
19680    pub fn parse_begin(&mut self) -> Result<Statement, ParserError> {
19681        let modifier = self.parse_transaction_modifier();
19682        let transaction =
19683            match self.parse_one_of_keywords(&[Keyword::TRANSACTION, Keyword::WORK, Keyword::TRAN])
19684            {
19685                Some(Keyword::TRANSACTION) => Some(BeginTransactionKind::Transaction),
19686                Some(Keyword::WORK) => Some(BeginTransactionKind::Work),
19687                Some(Keyword::TRAN) => Some(BeginTransactionKind::Tran),
19688                _ => None,
19689            };
19690        Ok(Statement::StartTransaction {
19691            modes: self.parse_transaction_modes()?,
19692            begin: true,
19693            transaction,
19694            modifier,
19695            statements: vec![],
19696            exception: None,
19697            has_end_keyword: false,
19698        })
19699    }
19700
19701    /// Parse a 'BEGIN ... EXCEPTION ... END' block
19702    pub fn parse_begin_exception_end(&mut self) -> Result<Statement, ParserError> {
19703        let statements = self.parse_statement_list(&[Keyword::EXCEPTION, Keyword::END])?;
19704
19705        let exception = if self.parse_keyword(Keyword::EXCEPTION) {
19706            let mut when = Vec::new();
19707
19708            // We can have multiple `WHEN` arms so we consume all cases until `END`
19709            while !self.peek_keyword(Keyword::END) {
19710                self.expect_keyword(Keyword::WHEN)?;
19711
19712                // Each `WHEN` case can have one or more conditions, e.g.
19713                // WHEN EXCEPTION_1 [OR EXCEPTION_2] THEN
19714                // So we parse identifiers until the `THEN` keyword.
19715                let mut idents = Vec::new();
19716
19717                while !self.parse_keyword(Keyword::THEN) {
19718                    let ident = self.parse_identifier()?;
19719                    idents.push(ident);
19720
19721                    self.maybe_parse(|p| p.expect_keyword(Keyword::OR))?;
19722                }
19723
19724                let statements = self.parse_statement_list(&[Keyword::WHEN, Keyword::END])?;
19725
19726                when.push(ExceptionWhen { idents, statements });
19727            }
19728
19729            Some(when)
19730        } else {
19731            None
19732        };
19733
19734        self.expect_keyword(Keyword::END)?;
19735
19736        Ok(Statement::StartTransaction {
19737            begin: true,
19738            statements,
19739            exception,
19740            has_end_keyword: true,
19741            transaction: None,
19742            modifier: None,
19743            modes: Default::default(),
19744        })
19745    }
19746
19747    /// Parse an 'END' statement
19748    pub fn parse_end(&mut self) -> Result<Statement, ParserError> {
19749        let modifier = if !self.dialect.supports_end_transaction_modifier() {
19750            None
19751        } else if self.parse_keyword(Keyword::TRY) {
19752            Some(TransactionModifier::Try)
19753        } else if self.parse_keyword(Keyword::CATCH) {
19754            Some(TransactionModifier::Catch)
19755        } else {
19756            None
19757        };
19758        Ok(Statement::Commit {
19759            chain: self.parse_commit_rollback_chain()?,
19760            end: true,
19761            modifier,
19762        })
19763    }
19764
19765    /// Parse a list of transaction modes
19766    pub fn parse_transaction_modes(&mut self) -> Result<Vec<TransactionMode>, ParserError> {
19767        let mut modes = vec![];
19768        let mut required = false;
19769        loop {
19770            let mode = if self.parse_keywords(&[Keyword::ISOLATION, Keyword::LEVEL]) {
19771                let iso_level = if self.parse_keywords(&[Keyword::READ, Keyword::UNCOMMITTED]) {
19772                    TransactionIsolationLevel::ReadUncommitted
19773                } else if self.parse_keywords(&[Keyword::READ, Keyword::COMMITTED]) {
19774                    TransactionIsolationLevel::ReadCommitted
19775                } else if self.parse_keywords(&[Keyword::REPEATABLE, Keyword::READ]) {
19776                    TransactionIsolationLevel::RepeatableRead
19777                } else if self.parse_keyword(Keyword::SERIALIZABLE) {
19778                    TransactionIsolationLevel::Serializable
19779                } else if self.parse_keyword(Keyword::SNAPSHOT) {
19780                    TransactionIsolationLevel::Snapshot
19781                } else {
19782                    self.expected_ref("isolation level", self.peek_token_ref())?
19783                };
19784                TransactionMode::IsolationLevel(iso_level)
19785            } else if self.parse_keywords(&[Keyword::READ, Keyword::ONLY]) {
19786                TransactionMode::AccessMode(TransactionAccessMode::ReadOnly)
19787            } else if self.parse_keywords(&[Keyword::READ, Keyword::WRITE]) {
19788                TransactionMode::AccessMode(TransactionAccessMode::ReadWrite)
19789            } else if required {
19790                self.expected_ref("transaction mode", self.peek_token_ref())?
19791            } else {
19792                break;
19793            };
19794            modes.push(mode);
19795            // ANSI requires a comma after each transaction mode, but
19796            // PostgreSQL, for historical reasons, does not. We follow
19797            // PostgreSQL in making the comma optional, since that is strictly
19798            // more general.
19799            required = self.consume_token(&Token::Comma);
19800        }
19801        Ok(modes)
19802    }
19803
19804    /// Parse a 'COMMIT' statement
19805    pub fn parse_commit(&mut self) -> Result<Statement, ParserError> {
19806        Ok(Statement::Commit {
19807            chain: self.parse_commit_rollback_chain()?,
19808            end: false,
19809            modifier: None,
19810        })
19811    }
19812
19813    /// Parse a 'ROLLBACK' statement
19814    pub fn parse_rollback(&mut self) -> Result<Statement, ParserError> {
19815        let chain = self.parse_commit_rollback_chain()?;
19816        let savepoint = self.parse_rollback_savepoint()?;
19817
19818        Ok(Statement::Rollback { chain, savepoint })
19819    }
19820
19821    /// Parse an 'ABORT' statement
19822    ///
19823    /// ```sql
19824    /// ABORT [ TRANSACTION | WORK ] [ AND [ NO ] CHAIN ]
19825    /// ```
19826    pub fn parse_abort(&mut self) -> Result<Statement, ParserError> {
19827        let chain = self.parse_commit_rollback_chain()?;
19828
19829        Ok(Statement::Rollback {
19830            chain,
19831            savepoint: None,
19832        })
19833    }
19834
19835    /// Parse an optional `AND [NO] CHAIN` clause for `COMMIT` and `ROLLBACK` statements
19836    pub fn parse_commit_rollback_chain(&mut self) -> Result<bool, ParserError> {
19837        let _ = self.parse_one_of_keywords(&[Keyword::TRANSACTION, Keyword::WORK, Keyword::TRAN]);
19838        if self.parse_keyword(Keyword::AND) {
19839            let chain = !self.parse_keyword(Keyword::NO);
19840            self.expect_keyword_is(Keyword::CHAIN)?;
19841            Ok(chain)
19842        } else {
19843            Ok(false)
19844        }
19845    }
19846
19847    /// Parse an optional 'TO SAVEPOINT savepoint_name' clause for ROLLBACK statements
19848    pub fn parse_rollback_savepoint(&mut self) -> Result<Option<Ident>, ParserError> {
19849        if self.parse_keyword(Keyword::TO) {
19850            let _ = self.parse_keyword(Keyword::SAVEPOINT);
19851            let savepoint = self.parse_identifier()?;
19852
19853            Ok(Some(savepoint))
19854        } else {
19855            Ok(None)
19856        }
19857    }
19858
19859    /// Parse a 'RAISERROR' statement
19860    pub fn parse_raiserror(&mut self) -> Result<Statement, ParserError> {
19861        self.expect_token(&Token::LParen)?;
19862        let message = Box::new(self.parse_expr()?);
19863        self.expect_token(&Token::Comma)?;
19864        let severity = Box::new(self.parse_expr()?);
19865        self.expect_token(&Token::Comma)?;
19866        let state = Box::new(self.parse_expr()?);
19867        let arguments = if self.consume_token(&Token::Comma) {
19868            self.parse_comma_separated(Parser::parse_expr)?
19869        } else {
19870            vec![]
19871        };
19872        self.expect_token(&Token::RParen)?;
19873        let options = if self.parse_keyword(Keyword::WITH) {
19874            self.parse_comma_separated(Parser::parse_raiserror_option)?
19875        } else {
19876            vec![]
19877        };
19878        Ok(Statement::RaisError {
19879            message,
19880            severity,
19881            state,
19882            arguments,
19883            options,
19884        })
19885    }
19886
19887    /// Parse a single `RAISERROR` option
19888    pub fn parse_raiserror_option(&mut self) -> Result<RaisErrorOption, ParserError> {
19889        match self.expect_one_of_keywords(&[Keyword::LOG, Keyword::NOWAIT, Keyword::SETERROR])? {
19890            Keyword::LOG => Ok(RaisErrorOption::Log),
19891            Keyword::NOWAIT => Ok(RaisErrorOption::NoWait),
19892            Keyword::SETERROR => Ok(RaisErrorOption::SetError),
19893            _ => self.expected_ref(
19894                "LOG, NOWAIT OR SETERROR raiserror option",
19895                self.peek_token_ref(),
19896            ),
19897        }
19898    }
19899
19900    /// Parse a MSSQL `THROW` statement.
19901    ///
19902    /// See [Statement::Throw]
19903    pub fn parse_throw(&mut self) -> Result<ThrowStatement, ParserError> {
19904        self.expect_keyword_is(Keyword::THROW)?;
19905
19906        let error_number = self.maybe_parse(|p| p.parse_expr().map(Box::new))?;
19907        let (message, state) = if error_number.is_some() {
19908            self.expect_token(&Token::Comma)?;
19909            let message = Box::new(self.parse_expr()?);
19910            self.expect_token(&Token::Comma)?;
19911            let state = Box::new(self.parse_expr()?);
19912            (Some(message), Some(state))
19913        } else {
19914            (None, None)
19915        };
19916
19917        Ok(ThrowStatement {
19918            error_number,
19919            message,
19920            state,
19921        })
19922    }
19923
19924    /// Parse a SQL `DEALLOCATE` statement
19925    pub fn parse_deallocate(&mut self) -> Result<Statement, ParserError> {
19926        let prepare = self.parse_keyword(Keyword::PREPARE);
19927        let name = self.parse_identifier()?;
19928        Ok(Statement::Deallocate { name, prepare })
19929    }
19930
19931    /// Parse a SQL `EXECUTE` statement
19932    pub fn parse_execute(&mut self) -> Result<Statement, ParserError> {
19933        let immediate =
19934            self.dialect.supports_execute_immediate() && self.parse_keyword(Keyword::IMMEDIATE);
19935
19936        // When `EXEC` is immediately followed by `(`, the content is a dynamic-SQL
19937        // expression — e.g. `EXEC (@sql)`, `EXEC ('SELECT ...')`, or
19938        // `EXEC ('SELECT ... FROM ' + @tbl + ' WHERE ...')`.
19939        // Skip name parsing; the expression ends up in `parameters` via the
19940        // `has_parentheses` path below, consistent with `EXECUTE IMMEDIATE <expr>`.
19941        let name = if immediate || matches!(self.peek_token_ref().token, Token::LParen) {
19942            None
19943        } else {
19944            Some(self.parse_object_name(false)?)
19945        };
19946
19947        let has_parentheses = self.consume_token(&Token::LParen);
19948
19949        let end_kws = &[Keyword::USING, Keyword::OUTPUT, Keyword::DEFAULT];
19950        let end_token = match (has_parentheses, self.peek_token().token) {
19951            (true, _) => Token::RParen,
19952            (false, Token::EOF) => Token::EOF,
19953            (false, Token::Word(w)) if end_kws.contains(&w.keyword) => Token::Word(w),
19954            (false, _) => Token::SemiColon,
19955        };
19956
19957        let parameters = self.parse_comma_separated0(Parser::parse_expr, end_token)?;
19958
19959        if has_parentheses {
19960            self.expect_token(&Token::RParen)?;
19961        }
19962
19963        let into = if self.parse_keyword(Keyword::INTO) {
19964            self.parse_comma_separated(Self::parse_identifier)?
19965        } else {
19966            vec![]
19967        };
19968
19969        let using = if self.parse_keyword(Keyword::USING) {
19970            self.parse_comma_separated(Self::parse_expr_with_alias)?
19971        } else {
19972            vec![]
19973        };
19974
19975        let output = self.parse_keyword(Keyword::OUTPUT);
19976
19977        let default = self.parse_keyword(Keyword::DEFAULT);
19978
19979        Ok(Statement::Execute {
19980            immediate,
19981            name,
19982            parameters,
19983            has_parentheses,
19984            into,
19985            using,
19986            output,
19987            default,
19988        })
19989    }
19990
19991    /// Parse a SQL `PREPARE` statement
19992    pub fn parse_prepare(&mut self) -> Result<Statement, ParserError> {
19993        let name = self.parse_identifier()?;
19994
19995        let mut data_types = vec![];
19996        if self.consume_token(&Token::LParen) {
19997            data_types = self.parse_comma_separated(Parser::parse_data_type)?;
19998            self.expect_token(&Token::RParen)?;
19999        }
20000
20001        self.expect_keyword_is(Keyword::AS)?;
20002        let statement = Box::new(self.parse_statement()?);
20003        Ok(Statement::Prepare {
20004            name,
20005            data_types,
20006            statement,
20007        })
20008    }
20009
20010    /// Parse a SQL `UNLOAD` statement
20011    pub fn parse_unload(&mut self) -> Result<Statement, ParserError> {
20012        self.expect_keyword(Keyword::UNLOAD)?;
20013        self.expect_token(&Token::LParen)?;
20014        let (query, query_text) =
20015            if matches!(self.peek_token_ref().token, Token::SingleQuotedString(_)) {
20016                (None, Some(self.parse_literal_string()?))
20017            } else {
20018                (Some(self.parse_query()?), None)
20019            };
20020        self.expect_token(&Token::RParen)?;
20021
20022        self.expect_keyword_is(Keyword::TO)?;
20023        let to = self.parse_identifier()?;
20024        let auth = if self.parse_keyword(Keyword::IAM_ROLE) {
20025            Some(self.parse_iam_role_kind()?)
20026        } else {
20027            None
20028        };
20029        let with = self.parse_options(Keyword::WITH)?;
20030        let mut options = vec![];
20031        while let Some(opt) = self.maybe_parse(|parser| parser.parse_copy_legacy_option())? {
20032            options.push(opt);
20033        }
20034        Ok(Statement::Unload {
20035            query,
20036            query_text,
20037            to,
20038            auth,
20039            with,
20040            options,
20041        })
20042    }
20043
20044    fn parse_select_into(&mut self) -> Result<SelectInto, ParserError> {
20045        let temporary = self
20046            .parse_one_of_keywords(&[Keyword::TEMP, Keyword::TEMPORARY])
20047            .is_some();
20048        let unlogged = self.parse_keyword(Keyword::UNLOGGED);
20049        let table = self.parse_keyword(Keyword::TABLE);
20050        let targets = self.parse_comma_separated(Parser::parse_expr)?;
20051
20052        Ok(SelectInto {
20053            temporary,
20054            unlogged,
20055            table,
20056            targets,
20057        })
20058    }
20059
20060    fn parse_pragma_value(&mut self) -> Result<ValueWithSpan, ParserError> {
20061        let v = self.parse_value()?;
20062        match &v.value {
20063            Value::SingleQuotedString(_) => Ok(v),
20064            Value::DoubleQuotedString(_) => Ok(v),
20065            Value::Number(_, _) => Ok(v),
20066            Value::Placeholder(_) => Ok(v),
20067            _ => {
20068                self.prev_token();
20069                self.expected_ref("number or string or ? placeholder", self.peek_token_ref())
20070            }
20071        }
20072    }
20073
20074    /// PRAGMA [schema-name '.'] pragma-name [('=' pragma-value) | '(' pragma-value ')']
20075    pub fn parse_pragma(&mut self) -> Result<Statement, ParserError> {
20076        let name = self.parse_object_name(false)?;
20077        if self.consume_token(&Token::LParen) {
20078            let value = self.parse_pragma_value()?;
20079            self.expect_token(&Token::RParen)?;
20080            Ok(Statement::Pragma {
20081                name,
20082                value: Some(value),
20083                is_eq: false,
20084            })
20085        } else if self.consume_token(&Token::Eq) {
20086            Ok(Statement::Pragma {
20087                name,
20088                value: Some(self.parse_pragma_value()?),
20089                is_eq: true,
20090            })
20091        } else {
20092            Ok(Statement::Pragma {
20093                name,
20094                value: None,
20095                is_eq: false,
20096            })
20097        }
20098    }
20099
20100    /// `INSTALL [extension_name]`
20101    pub fn parse_install(&mut self) -> Result<Statement, ParserError> {
20102        let extension_name = self.parse_identifier()?;
20103
20104        Ok(Statement::Install { extension_name })
20105    }
20106
20107    /// Parse a SQL LOAD statement
20108    pub fn parse_load(&mut self) -> Result<Statement, ParserError> {
20109        if self.dialect.supports_load_extension() {
20110            let extension_name = self.parse_identifier()?;
20111            Ok(Statement::Load { extension_name })
20112        } else if self.parse_keyword(Keyword::DATA) && self.dialect.supports_load_data() {
20113            let local = self.parse_one_of_keywords(&[Keyword::LOCAL]).is_some();
20114            self.expect_keyword_is(Keyword::INPATH)?;
20115            let inpath = self.parse_literal_string()?;
20116            let overwrite = self.parse_one_of_keywords(&[Keyword::OVERWRITE]).is_some();
20117            self.expect_keyword_is(Keyword::INTO)?;
20118            self.expect_keyword_is(Keyword::TABLE)?;
20119            let table_name = self.parse_object_name(false)?;
20120            let partitioned = self.parse_insert_partition()?;
20121            let table_format = self.parse_load_data_table_format()?;
20122            Ok(Statement::LoadData {
20123                local,
20124                inpath,
20125                overwrite,
20126                table_name,
20127                partitioned,
20128                table_format,
20129            })
20130        } else {
20131            self.expected_ref(
20132                "`DATA` or an extension name after `LOAD`",
20133                self.peek_token_ref(),
20134            )
20135        }
20136    }
20137
20138    /// ClickHouse:
20139    /// ```sql
20140    /// OPTIMIZE TABLE [db.]name [ON CLUSTER cluster] [PARTITION partition | PARTITION ID 'partition_id'] [FINAL] [DEDUPLICATE [BY expression]]
20141    /// ```
20142    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/optimize)
20143    ///
20144    /// Databricks:
20145    /// ```sql
20146    /// OPTIMIZE table_name [WHERE predicate] [ZORDER BY (col_name1 [, ...])]
20147    /// ```
20148    /// [Databricks](https://docs.databricks.com/en/sql/language-manual/delta-optimize.html)
20149    pub fn parse_optimize_table(&mut self) -> Result<Statement, ParserError> {
20150        let has_table_keyword = self.parse_keyword(Keyword::TABLE);
20151
20152        let name = self.parse_object_name(false)?;
20153
20154        // ClickHouse-specific options
20155        let on_cluster = self.parse_optional_on_cluster()?;
20156
20157        let partition = if self.parse_keyword(Keyword::PARTITION) {
20158            if self.parse_keyword(Keyword::ID) {
20159                Some(Partition::Identifier(self.parse_identifier()?))
20160            } else {
20161                Some(Partition::Expr(self.parse_expr()?))
20162            }
20163        } else {
20164            None
20165        };
20166
20167        let include_final = self.parse_keyword(Keyword::FINAL);
20168
20169        let deduplicate = if self.parse_keyword(Keyword::DEDUPLICATE) {
20170            if self.parse_keyword(Keyword::BY) {
20171                Some(Deduplicate::ByExpression(self.parse_expr()?))
20172            } else {
20173                Some(Deduplicate::All)
20174            }
20175        } else {
20176            None
20177        };
20178
20179        // Databricks-specific options
20180        let predicate = if self.parse_keyword(Keyword::WHERE) {
20181            Some(self.parse_expr()?)
20182        } else {
20183            None
20184        };
20185
20186        let zorder = if self.parse_keywords(&[Keyword::ZORDER, Keyword::BY]) {
20187            self.expect_token(&Token::LParen)?;
20188            let columns = self.parse_comma_separated(|p| p.parse_expr())?;
20189            self.expect_token(&Token::RParen)?;
20190            Some(columns)
20191        } else {
20192            None
20193        };
20194
20195        Ok(Statement::OptimizeTable {
20196            name,
20197            has_table_keyword,
20198            on_cluster,
20199            partition,
20200            include_final,
20201            deduplicate,
20202            predicate,
20203            zorder,
20204        })
20205    }
20206
20207    /// ```sql
20208    /// CREATE [ { TEMPORARY | TEMP } ] SEQUENCE [ IF NOT EXISTS ] <sequence_name>
20209    /// ```
20210    ///
20211    /// See [Postgres docs](https://www.postgresql.org/docs/current/sql-createsequence.html) for more details.
20212    pub fn parse_create_sequence(&mut self, temporary: bool) -> Result<Statement, ParserError> {
20213        //[ IF NOT EXISTS ]
20214        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
20215        //name
20216        let name = self.parse_object_name(false)?;
20217        //[ AS data_type ]
20218        let mut data_type: Option<DataType> = None;
20219        if self.parse_keywords(&[Keyword::AS]) {
20220            data_type = Some(self.parse_data_type()?)
20221        }
20222        let sequence_options = self.parse_create_sequence_options()?;
20223        // [ OWNED BY { table_name.column_name | NONE } ]
20224        let owned_by = if self.parse_keywords(&[Keyword::OWNED, Keyword::BY]) {
20225            if self.parse_keywords(&[Keyword::NONE]) {
20226                Some(ObjectName::from(vec![Ident::new("NONE")]))
20227            } else {
20228                Some(self.parse_object_name(false)?)
20229            }
20230        } else {
20231            None
20232        };
20233        Ok(Statement::CreateSequence {
20234            temporary,
20235            if_not_exists,
20236            name,
20237            data_type,
20238            sequence_options,
20239            owned_by,
20240        })
20241    }
20242
20243    fn parse_create_sequence_options(&mut self) -> Result<Vec<SequenceOptions>, ParserError> {
20244        let mut sequence_options = vec![];
20245        //[ INCREMENT [ BY ] increment ]
20246        if self.parse_keywords(&[Keyword::INCREMENT]) {
20247            if self.parse_keywords(&[Keyword::BY]) {
20248                sequence_options.push(SequenceOptions::IncrementBy(self.parse_number()?, true));
20249            } else {
20250                sequence_options.push(SequenceOptions::IncrementBy(self.parse_number()?, false));
20251            }
20252        }
20253        //[ MINVALUE minvalue | NO MINVALUE ]
20254        if self.parse_keyword(Keyword::MINVALUE) {
20255            sequence_options.push(SequenceOptions::MinValue(Some(self.parse_number()?)));
20256        } else if self.parse_keywords(&[Keyword::NO, Keyword::MINVALUE]) {
20257            sequence_options.push(SequenceOptions::MinValue(None));
20258        }
20259        //[ MAXVALUE maxvalue | NO MAXVALUE ]
20260        if self.parse_keywords(&[Keyword::MAXVALUE]) {
20261            sequence_options.push(SequenceOptions::MaxValue(Some(self.parse_number()?)));
20262        } else if self.parse_keywords(&[Keyword::NO, Keyword::MAXVALUE]) {
20263            sequence_options.push(SequenceOptions::MaxValue(None));
20264        }
20265
20266        //[ START [ WITH ] start ]
20267        if self.parse_keywords(&[Keyword::START]) {
20268            if self.parse_keywords(&[Keyword::WITH]) {
20269                sequence_options.push(SequenceOptions::StartWith(self.parse_number()?, true));
20270            } else {
20271                sequence_options.push(SequenceOptions::StartWith(self.parse_number()?, false));
20272            }
20273        }
20274        //[ CACHE cache ]
20275        if self.parse_keywords(&[Keyword::CACHE]) {
20276            sequence_options.push(SequenceOptions::Cache(self.parse_number()?));
20277        }
20278        // [ [ NO ] CYCLE ]
20279        if self.parse_keywords(&[Keyword::NO, Keyword::CYCLE]) {
20280            sequence_options.push(SequenceOptions::Cycle(true));
20281        } else if self.parse_keywords(&[Keyword::CYCLE]) {
20282            sequence_options.push(SequenceOptions::Cycle(false));
20283        }
20284
20285        Ok(sequence_options)
20286    }
20287
20288    ///   Parse a `CREATE SERVER` statement.
20289    ///
20290    ///  See [Statement::CreateServer]
20291    pub fn parse_pg_create_server(&mut self) -> Result<Statement, ParserError> {
20292        let ine = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
20293        let name = self.parse_object_name(false)?;
20294
20295        let server_type = if self.parse_keyword(Keyword::TYPE) {
20296            Some(self.parse_identifier()?)
20297        } else {
20298            None
20299        };
20300
20301        let version = if self.parse_keyword(Keyword::VERSION) {
20302            Some(self.parse_identifier()?)
20303        } else {
20304            None
20305        };
20306
20307        self.expect_keywords(&[Keyword::FOREIGN, Keyword::DATA, Keyword::WRAPPER])?;
20308        let foreign_data_wrapper = self.parse_object_name(false)?;
20309
20310        let mut options = None;
20311        if self.parse_keyword(Keyword::OPTIONS) {
20312            self.expect_token(&Token::LParen)?;
20313            options = Some(self.parse_comma_separated(|p| {
20314                let key = p.parse_identifier()?;
20315                let value = p.parse_identifier()?;
20316                Ok(CreateServerOption { key, value })
20317            })?);
20318            self.expect_token(&Token::RParen)?;
20319        }
20320
20321        Ok(Statement::CreateServer(CreateServerStatement {
20322            name,
20323            if_not_exists: ine,
20324            server_type,
20325            version,
20326            foreign_data_wrapper,
20327            options,
20328        }))
20329    }
20330
20331    /// The index of the first unprocessed token.
20332    pub fn index(&self) -> usize {
20333        self.index
20334    }
20335
20336    /// Parse a named window definition.
20337    pub fn parse_named_window(&mut self) -> Result<NamedWindowDefinition, ParserError> {
20338        let ident = self.parse_identifier()?;
20339        self.expect_keyword_is(Keyword::AS)?;
20340
20341        let window_expr = if self.consume_token(&Token::LParen) {
20342            NamedWindowExpr::WindowSpec(self.parse_window_spec()?)
20343        } else if self.dialect.supports_window_clause_named_window_reference() {
20344            NamedWindowExpr::NamedWindow(self.parse_identifier()?)
20345        } else {
20346            return self.expected_ref("(", self.peek_token_ref());
20347        };
20348
20349        Ok(NamedWindowDefinition(ident, window_expr))
20350    }
20351
20352    /// Parse `CREATE PROCEDURE` statement.
20353    pub fn parse_create_procedure(&mut self, or_alter: bool) -> Result<Statement, ParserError> {
20354        let name = self.parse_object_name(false)?;
20355        let params = self.parse_optional_procedure_parameters()?;
20356
20357        let language = if self.parse_keyword(Keyword::LANGUAGE) {
20358            Some(self.parse_identifier()?)
20359        } else {
20360            None
20361        };
20362
20363        self.expect_keyword_is(Keyword::AS)?;
20364
20365        let body = self.parse_conditional_statements(&[Keyword::END])?;
20366
20367        Ok(Statement::CreateProcedure {
20368            name,
20369            or_alter,
20370            params,
20371            language,
20372            body,
20373        })
20374    }
20375
20376    /// Parse a window specification.
20377    pub fn parse_window_spec(&mut self) -> Result<WindowSpec, ParserError> {
20378        let window_name = match &self.peek_token_ref().token {
20379            Token::Word(word) if word.keyword == Keyword::NoKeyword => {
20380                self.parse_optional_ident()?
20381            }
20382            _ => None,
20383        };
20384
20385        let partition_by = if self.parse_keywords(&[Keyword::PARTITION, Keyword::BY]) {
20386            self.parse_comma_separated(Parser::parse_expr)?
20387        } else {
20388            vec![]
20389        };
20390        let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
20391            self.parse_comma_separated(Parser::parse_order_by_expr)?
20392        } else {
20393            vec![]
20394        };
20395
20396        let window_frame = if !self.consume_token(&Token::RParen) {
20397            let window_frame = self.parse_window_frame()?;
20398            self.expect_token(&Token::RParen)?;
20399            Some(window_frame)
20400        } else {
20401            None
20402        };
20403        Ok(WindowSpec {
20404            window_name,
20405            partition_by,
20406            order_by,
20407            window_frame,
20408        })
20409    }
20410
20411    /// Parse `CREATE TYPE` statement.
20412    pub fn parse_create_type(&mut self) -> Result<Statement, ParserError> {
20413        let name = self.parse_object_name(false)?;
20414
20415        // Check if we have AS keyword
20416        let has_as = self.parse_keyword(Keyword::AS);
20417
20418        if !has_as {
20419            // Two cases: CREATE TYPE name; or CREATE TYPE name (options);
20420            if self.consume_token(&Token::LParen) {
20421                // CREATE TYPE name (options) - SQL definition without AS
20422                let options = self.parse_create_type_sql_definition_options()?;
20423                self.expect_token(&Token::RParen)?;
20424                return Ok(Statement::CreateType {
20425                    name,
20426                    representation: Some(UserDefinedTypeRepresentation::SqlDefinition { options }),
20427                });
20428            }
20429
20430            // CREATE TYPE name; - no representation
20431            return Ok(Statement::CreateType {
20432                name,
20433                representation: None,
20434            });
20435        }
20436
20437        // We have AS keyword
20438        if self.parse_keyword(Keyword::ENUM) {
20439            // CREATE TYPE name AS ENUM (labels)
20440            self.parse_create_type_enum(name)
20441        } else if self.parse_keyword(Keyword::RANGE) {
20442            // CREATE TYPE name AS RANGE (options)
20443            self.parse_create_type_range(name)
20444        } else if self.consume_token(&Token::LParen) {
20445            // CREATE TYPE name AS (attributes) - Composite
20446            self.parse_create_type_composite(name)
20447        } else {
20448            self.expected_ref("ENUM, RANGE, or '(' after AS", self.peek_token_ref())
20449        }
20450    }
20451
20452    /// Parse remainder of `CREATE TYPE AS (attributes)` statement (composite type)
20453    ///
20454    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtype.html)
20455    fn parse_create_type_composite(&mut self, name: ObjectName) -> Result<Statement, ParserError> {
20456        if self.consume_token(&Token::RParen) {
20457            // Empty composite type
20458            return Ok(Statement::CreateType {
20459                name,
20460                representation: Some(UserDefinedTypeRepresentation::Composite {
20461                    attributes: vec![],
20462                }),
20463            });
20464        }
20465
20466        let mut attributes = vec![];
20467        loop {
20468            let attr_name = self.parse_identifier()?;
20469            let attr_data_type = self.parse_data_type()?;
20470            let attr_collation = if self.parse_keyword(Keyword::COLLATE) {
20471                Some(self.parse_object_name(false)?)
20472            } else {
20473                None
20474            };
20475            attributes.push(UserDefinedTypeCompositeAttributeDef {
20476                name: attr_name,
20477                data_type: attr_data_type,
20478                collation: attr_collation,
20479            });
20480
20481            if !self.consume_token(&Token::Comma) {
20482                break;
20483            }
20484        }
20485        self.expect_token(&Token::RParen)?;
20486
20487        Ok(Statement::CreateType {
20488            name,
20489            representation: Some(UserDefinedTypeRepresentation::Composite { attributes }),
20490        })
20491    }
20492
20493    /// Parse remainder of `CREATE TYPE AS ENUM` statement (see [Statement::CreateType] and [Self::parse_create_type])
20494    ///
20495    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtype.html)
20496    pub fn parse_create_type_enum(&mut self, name: ObjectName) -> Result<Statement, ParserError> {
20497        self.expect_token(&Token::LParen)?;
20498        let labels = self.parse_comma_separated0(|p| p.parse_identifier(), Token::RParen)?;
20499        self.expect_token(&Token::RParen)?;
20500
20501        Ok(Statement::CreateType {
20502            name,
20503            representation: Some(UserDefinedTypeRepresentation::Enum { labels }),
20504        })
20505    }
20506
20507    /// Parse remainder of `CREATE TYPE AS RANGE` statement
20508    ///
20509    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtype.html)
20510    fn parse_create_type_range(&mut self, name: ObjectName) -> Result<Statement, ParserError> {
20511        self.expect_token(&Token::LParen)?;
20512        let options = self.parse_comma_separated0(|p| p.parse_range_option(), Token::RParen)?;
20513        self.expect_token(&Token::RParen)?;
20514
20515        Ok(Statement::CreateType {
20516            name,
20517            representation: Some(UserDefinedTypeRepresentation::Range { options }),
20518        })
20519    }
20520
20521    /// Parse a single range option for a `CREATE TYPE AS RANGE` statement
20522    fn parse_range_option(&mut self) -> Result<UserDefinedTypeRangeOption, ParserError> {
20523        let keyword = self.parse_one_of_keywords(&[
20524            Keyword::SUBTYPE,
20525            Keyword::SUBTYPE_OPCLASS,
20526            Keyword::COLLATION,
20527            Keyword::CANONICAL,
20528            Keyword::SUBTYPE_DIFF,
20529            Keyword::MULTIRANGE_TYPE_NAME,
20530        ]);
20531
20532        match keyword {
20533            Some(Keyword::SUBTYPE) => {
20534                self.expect_token(&Token::Eq)?;
20535                let data_type = self.parse_data_type()?;
20536                Ok(UserDefinedTypeRangeOption::Subtype(data_type))
20537            }
20538            Some(Keyword::SUBTYPE_OPCLASS) => {
20539                self.expect_token(&Token::Eq)?;
20540                let name = self.parse_object_name(false)?;
20541                Ok(UserDefinedTypeRangeOption::SubtypeOpClass(name))
20542            }
20543            Some(Keyword::COLLATION) => {
20544                self.expect_token(&Token::Eq)?;
20545                let name = self.parse_object_name(false)?;
20546                Ok(UserDefinedTypeRangeOption::Collation(name))
20547            }
20548            Some(Keyword::CANONICAL) => {
20549                self.expect_token(&Token::Eq)?;
20550                let name = self.parse_object_name(false)?;
20551                Ok(UserDefinedTypeRangeOption::Canonical(name))
20552            }
20553            Some(Keyword::SUBTYPE_DIFF) => {
20554                self.expect_token(&Token::Eq)?;
20555                let name = self.parse_object_name(false)?;
20556                Ok(UserDefinedTypeRangeOption::SubtypeDiff(name))
20557            }
20558            Some(Keyword::MULTIRANGE_TYPE_NAME) => {
20559                self.expect_token(&Token::Eq)?;
20560                let name = self.parse_object_name(false)?;
20561                Ok(UserDefinedTypeRangeOption::MultirangeTypeName(name))
20562            }
20563            _ => self.expected_ref("range option keyword", self.peek_token_ref()),
20564        }
20565    }
20566
20567    /// Parse SQL definition options for CREATE TYPE (options)
20568    fn parse_create_type_sql_definition_options(
20569        &mut self,
20570    ) -> Result<Vec<UserDefinedTypeSqlDefinitionOption>, ParserError> {
20571        self.parse_comma_separated0(|p| p.parse_sql_definition_option(), Token::RParen)
20572    }
20573
20574    /// Parse a single SQL definition option for CREATE TYPE (options)
20575    fn parse_sql_definition_option(
20576        &mut self,
20577    ) -> Result<UserDefinedTypeSqlDefinitionOption, ParserError> {
20578        let keyword = self.parse_one_of_keywords(&[
20579            Keyword::INPUT,
20580            Keyword::OUTPUT,
20581            Keyword::RECEIVE,
20582            Keyword::SEND,
20583            Keyword::TYPMOD_IN,
20584            Keyword::TYPMOD_OUT,
20585            Keyword::ANALYZE,
20586            Keyword::SUBSCRIPT,
20587            Keyword::INTERNALLENGTH,
20588            Keyword::PASSEDBYVALUE,
20589            Keyword::ALIGNMENT,
20590            Keyword::STORAGE,
20591            Keyword::LIKE,
20592            Keyword::CATEGORY,
20593            Keyword::PREFERRED,
20594            Keyword::DEFAULT,
20595            Keyword::ELEMENT,
20596            Keyword::DELIMITER,
20597            Keyword::COLLATABLE,
20598        ]);
20599
20600        match keyword {
20601            Some(Keyword::INPUT) => {
20602                self.expect_token(&Token::Eq)?;
20603                let name = self.parse_object_name(false)?;
20604                Ok(UserDefinedTypeSqlDefinitionOption::Input(name))
20605            }
20606            Some(Keyword::OUTPUT) => {
20607                self.expect_token(&Token::Eq)?;
20608                let name = self.parse_object_name(false)?;
20609                Ok(UserDefinedTypeSqlDefinitionOption::Output(name))
20610            }
20611            Some(Keyword::RECEIVE) => {
20612                self.expect_token(&Token::Eq)?;
20613                let name = self.parse_object_name(false)?;
20614                Ok(UserDefinedTypeSqlDefinitionOption::Receive(name))
20615            }
20616            Some(Keyword::SEND) => {
20617                self.expect_token(&Token::Eq)?;
20618                let name = self.parse_object_name(false)?;
20619                Ok(UserDefinedTypeSqlDefinitionOption::Send(name))
20620            }
20621            Some(Keyword::TYPMOD_IN) => {
20622                self.expect_token(&Token::Eq)?;
20623                let name = self.parse_object_name(false)?;
20624                Ok(UserDefinedTypeSqlDefinitionOption::TypmodIn(name))
20625            }
20626            Some(Keyword::TYPMOD_OUT) => {
20627                self.expect_token(&Token::Eq)?;
20628                let name = self.parse_object_name(false)?;
20629                Ok(UserDefinedTypeSqlDefinitionOption::TypmodOut(name))
20630            }
20631            Some(Keyword::ANALYZE) => {
20632                self.expect_token(&Token::Eq)?;
20633                let name = self.parse_object_name(false)?;
20634                Ok(UserDefinedTypeSqlDefinitionOption::Analyze(name))
20635            }
20636            Some(Keyword::SUBSCRIPT) => {
20637                self.expect_token(&Token::Eq)?;
20638                let name = self.parse_object_name(false)?;
20639                Ok(UserDefinedTypeSqlDefinitionOption::Subscript(name))
20640            }
20641            Some(Keyword::INTERNALLENGTH) => {
20642                self.expect_token(&Token::Eq)?;
20643                if self.parse_keyword(Keyword::VARIABLE) {
20644                    Ok(UserDefinedTypeSqlDefinitionOption::InternalLength(
20645                        UserDefinedTypeInternalLength::Variable,
20646                    ))
20647                } else {
20648                    let value = self.parse_literal_uint()?;
20649                    Ok(UserDefinedTypeSqlDefinitionOption::InternalLength(
20650                        UserDefinedTypeInternalLength::Fixed(value),
20651                    ))
20652                }
20653            }
20654            Some(Keyword::PASSEDBYVALUE) => Ok(UserDefinedTypeSqlDefinitionOption::PassedByValue),
20655            Some(Keyword::ALIGNMENT) => {
20656                self.expect_token(&Token::Eq)?;
20657                let align_keyword = self.parse_one_of_keywords(&[
20658                    Keyword::CHAR,
20659                    Keyword::INT2,
20660                    Keyword::INT4,
20661                    Keyword::DOUBLE,
20662                ]);
20663                match align_keyword {
20664                    Some(Keyword::CHAR) => Ok(UserDefinedTypeSqlDefinitionOption::Alignment(
20665                        Alignment::Char,
20666                    )),
20667                    Some(Keyword::INT2) => Ok(UserDefinedTypeSqlDefinitionOption::Alignment(
20668                        Alignment::Int2,
20669                    )),
20670                    Some(Keyword::INT4) => Ok(UserDefinedTypeSqlDefinitionOption::Alignment(
20671                        Alignment::Int4,
20672                    )),
20673                    Some(Keyword::DOUBLE) => Ok(UserDefinedTypeSqlDefinitionOption::Alignment(
20674                        Alignment::Double,
20675                    )),
20676                    _ => self.expected_ref(
20677                        "alignment value (char, int2, int4, or double)",
20678                        self.peek_token_ref(),
20679                    ),
20680                }
20681            }
20682            Some(Keyword::STORAGE) => {
20683                self.expect_token(&Token::Eq)?;
20684                let storage_keyword = self.parse_one_of_keywords(&[
20685                    Keyword::PLAIN,
20686                    Keyword::EXTERNAL,
20687                    Keyword::EXTENDED,
20688                    Keyword::MAIN,
20689                ]);
20690                match storage_keyword {
20691                    Some(Keyword::PLAIN) => Ok(UserDefinedTypeSqlDefinitionOption::Storage(
20692                        UserDefinedTypeStorage::Plain,
20693                    )),
20694                    Some(Keyword::EXTERNAL) => Ok(UserDefinedTypeSqlDefinitionOption::Storage(
20695                        UserDefinedTypeStorage::External,
20696                    )),
20697                    Some(Keyword::EXTENDED) => Ok(UserDefinedTypeSqlDefinitionOption::Storage(
20698                        UserDefinedTypeStorage::Extended,
20699                    )),
20700                    Some(Keyword::MAIN) => Ok(UserDefinedTypeSqlDefinitionOption::Storage(
20701                        UserDefinedTypeStorage::Main,
20702                    )),
20703                    _ => self.expected_ref(
20704                        "storage value (plain, external, extended, or main)",
20705                        self.peek_token_ref(),
20706                    ),
20707                }
20708            }
20709            Some(Keyword::LIKE) => {
20710                self.expect_token(&Token::Eq)?;
20711                let name = self.parse_object_name(false)?;
20712                Ok(UserDefinedTypeSqlDefinitionOption::Like(name))
20713            }
20714            Some(Keyword::CATEGORY) => {
20715                self.expect_token(&Token::Eq)?;
20716                let category_str = self.parse_literal_string()?;
20717                let category_char = category_str.chars().next().ok_or_else(|| {
20718                    ParserError::ParserError(
20719                        "CATEGORY value must be a single character".to_string(),
20720                    )
20721                })?;
20722                Ok(UserDefinedTypeSqlDefinitionOption::Category(category_char))
20723            }
20724            Some(Keyword::PREFERRED) => {
20725                self.expect_token(&Token::Eq)?;
20726                let value =
20727                    self.parse_keyword(Keyword::TRUE) || !self.parse_keyword(Keyword::FALSE);
20728                Ok(UserDefinedTypeSqlDefinitionOption::Preferred(value))
20729            }
20730            Some(Keyword::DEFAULT) => {
20731                self.expect_token(&Token::Eq)?;
20732                let expr = self.parse_expr()?;
20733                Ok(UserDefinedTypeSqlDefinitionOption::Default(expr))
20734            }
20735            Some(Keyword::ELEMENT) => {
20736                self.expect_token(&Token::Eq)?;
20737                let data_type = self.parse_data_type()?;
20738                Ok(UserDefinedTypeSqlDefinitionOption::Element(data_type))
20739            }
20740            Some(Keyword::DELIMITER) => {
20741                self.expect_token(&Token::Eq)?;
20742                let delimiter = self.parse_literal_string()?;
20743                Ok(UserDefinedTypeSqlDefinitionOption::Delimiter(delimiter))
20744            }
20745            Some(Keyword::COLLATABLE) => {
20746                self.expect_token(&Token::Eq)?;
20747                let value =
20748                    self.parse_keyword(Keyword::TRUE) || !self.parse_keyword(Keyword::FALSE);
20749                Ok(UserDefinedTypeSqlDefinitionOption::Collatable(value))
20750            }
20751            _ => self.expected_ref("SQL definition option keyword", self.peek_token_ref()),
20752        }
20753    }
20754
20755    fn parse_parenthesized_identifiers(&mut self) -> Result<Vec<Ident>, ParserError> {
20756        self.expect_token(&Token::LParen)?;
20757        let idents = self.parse_comma_separated0(|p| p.parse_identifier(), Token::RParen)?;
20758        self.expect_token(&Token::RParen)?;
20759        Ok(idents)
20760    }
20761
20762    fn parse_column_position(&mut self) -> Result<Option<MySQLColumnPosition>, ParserError> {
20763        if dialect_of!(self is MySqlDialect | GenericDialect) {
20764            if self.parse_keyword(Keyword::FIRST) {
20765                Ok(Some(MySQLColumnPosition::First))
20766            } else if self.parse_keyword(Keyword::AFTER) {
20767                let ident = self.parse_identifier()?;
20768                Ok(Some(MySQLColumnPosition::After(ident)))
20769            } else {
20770                Ok(None)
20771            }
20772        } else {
20773            Ok(None)
20774        }
20775    }
20776
20777    /// Parse [Statement::Print]
20778    fn parse_print(&mut self) -> Result<Statement, ParserError> {
20779        Ok(Statement::Print(PrintStatement {
20780            message: Box::new(self.parse_expr()?),
20781        }))
20782    }
20783
20784    /// Parse [Statement::WaitFor]
20785    ///
20786    /// See: <https://learn.microsoft.com/en-us/sql/t-sql/language-elements/waitfor-transact-sql>
20787    fn parse_waitfor(&mut self) -> Result<Statement, ParserError> {
20788        let wait_type = if self.parse_keyword(Keyword::DELAY) {
20789            WaitForType::Delay
20790        } else if self.parse_keyword(Keyword::TIME) {
20791            WaitForType::Time
20792        } else {
20793            return self.expected_ref("DELAY or TIME", self.peek_token_ref());
20794        };
20795        let expr = self.parse_expr()?;
20796        Ok(Statement::WaitFor(WaitForStatement { wait_type, expr }))
20797    }
20798
20799    /// Parse [Statement::Return]
20800    fn parse_return(&mut self) -> Result<Statement, ParserError> {
20801        match self.maybe_parse(|p| p.parse_expr())? {
20802            Some(expr) => Ok(Statement::Return(ReturnStatement {
20803                value: Some(ReturnStatementValue::Expr(expr)),
20804            })),
20805            None => Ok(Statement::Return(ReturnStatement { value: None })),
20806        }
20807    }
20808
20809    /// /// Parse a `EXPORT DATA` statement.
20810    ///
20811    /// See [Statement::ExportData]
20812    fn parse_export_data(&mut self) -> Result<Statement, ParserError> {
20813        self.expect_keywords(&[Keyword::EXPORT, Keyword::DATA])?;
20814
20815        let connection = if self.parse_keywords(&[Keyword::WITH, Keyword::CONNECTION]) {
20816            Some(self.parse_object_name(false)?)
20817        } else {
20818            None
20819        };
20820        self.expect_keyword(Keyword::OPTIONS)?;
20821        self.expect_token(&Token::LParen)?;
20822        let options = self.parse_comma_separated(|p| p.parse_sql_option())?;
20823        self.expect_token(&Token::RParen)?;
20824        self.expect_keyword(Keyword::AS)?;
20825        let query = self.parse_query()?;
20826        Ok(Statement::ExportData(ExportData {
20827            options,
20828            query,
20829            connection,
20830        }))
20831    }
20832
20833    fn parse_vacuum(&mut self) -> Result<Statement, ParserError> {
20834        self.expect_keyword(Keyword::VACUUM)?;
20835        let full = self.parse_keyword(Keyword::FULL);
20836        let sort_only = self.parse_keywords(&[Keyword::SORT, Keyword::ONLY]);
20837        let delete_only = self.parse_keywords(&[Keyword::DELETE, Keyword::ONLY]);
20838        let reindex = self.parse_keyword(Keyword::REINDEX);
20839        let recluster = self.parse_keyword(Keyword::RECLUSTER);
20840        let (table_name, threshold, boost) =
20841            match self.maybe_parse(|p| p.parse_object_name(false))? {
20842                Some(table_name) => {
20843                    let threshold = if self.parse_keyword(Keyword::TO) {
20844                        let value = self.parse_value()?;
20845                        self.expect_keyword(Keyword::PERCENT)?;
20846                        Some(value)
20847                    } else {
20848                        None
20849                    };
20850                    let boost = self.parse_keyword(Keyword::BOOST);
20851                    (Some(table_name), threshold, boost)
20852                }
20853                _ => (None, None, false),
20854            };
20855        Ok(Statement::Vacuum(VacuumStatement {
20856            full,
20857            sort_only,
20858            delete_only,
20859            reindex,
20860            recluster,
20861            table_name,
20862            threshold,
20863            boost,
20864        }))
20865    }
20866
20867    /// Consume the parser and return its underlying token buffer
20868    pub fn into_tokens(self) -> Vec<TokenWithSpan> {
20869        self.tokens
20870    }
20871
20872    /// Returns true if the next keyword indicates a sub query, i.e. SELECT or WITH
20873    fn peek_sub_query(&mut self) -> bool {
20874        self.peek_one_of_keywords(&[Keyword::SELECT, Keyword::WITH])
20875            .is_some()
20876    }
20877
20878    pub(crate) fn parse_show_stmt_options(&mut self) -> Result<ShowStatementOptions, ParserError> {
20879        let show_in;
20880        let mut filter_position = None;
20881        if self.dialect.supports_show_like_before_in() {
20882            if let Some(filter) = self.parse_show_statement_filter()? {
20883                filter_position = Some(ShowStatementFilterPosition::Infix(filter));
20884            }
20885            show_in = self.maybe_parse_show_stmt_in()?;
20886        } else {
20887            show_in = self.maybe_parse_show_stmt_in()?;
20888            if let Some(filter) = self.parse_show_statement_filter()? {
20889                filter_position = Some(ShowStatementFilterPosition::Suffix(filter));
20890            }
20891        }
20892        let starts_with = self.maybe_parse_show_stmt_starts_with()?;
20893        let limit = self.maybe_parse_show_stmt_limit()?;
20894        let from = self.maybe_parse_show_stmt_from()?;
20895        Ok(ShowStatementOptions {
20896            filter_position,
20897            show_in,
20898            starts_with,
20899            limit,
20900            limit_from: from,
20901        })
20902    }
20903
20904    fn maybe_parse_show_stmt_in(&mut self) -> Result<Option<ShowStatementIn>, ParserError> {
20905        let clause = match self.parse_one_of_keywords(&[Keyword::FROM, Keyword::IN]) {
20906            Some(Keyword::FROM) => ShowStatementInClause::FROM,
20907            Some(Keyword::IN) => ShowStatementInClause::IN,
20908            None => return Ok(None),
20909            _ => return self.expected_ref("FROM or IN", self.peek_token_ref()),
20910        };
20911
20912        let (parent_type, parent_name) = match self.parse_one_of_keywords(&[
20913            Keyword::ACCOUNT,
20914            Keyword::DATABASE,
20915            Keyword::SCHEMA,
20916            Keyword::TABLE,
20917            Keyword::VIEW,
20918        ]) {
20919            // If we see these next keywords it means we don't have a parent name
20920            Some(Keyword::DATABASE)
20921                if self.peek_keywords(&[Keyword::STARTS, Keyword::WITH])
20922                    | self.peek_keyword(Keyword::LIMIT) =>
20923            {
20924                (Some(ShowStatementInParentType::Database), None)
20925            }
20926            Some(Keyword::SCHEMA)
20927                if self.peek_keywords(&[Keyword::STARTS, Keyword::WITH])
20928                    | self.peek_keyword(Keyword::LIMIT) =>
20929            {
20930                (Some(ShowStatementInParentType::Schema), None)
20931            }
20932            Some(parent_kw) => {
20933                // The parent name here is still optional, for example:
20934                // SHOW TABLES IN ACCOUNT, so parsing the object name
20935                // may fail because the statement ends.
20936                let parent_name = self.maybe_parse(|p| p.parse_object_name(false))?;
20937                match parent_kw {
20938                    Keyword::ACCOUNT => (Some(ShowStatementInParentType::Account), parent_name),
20939                    Keyword::DATABASE => (Some(ShowStatementInParentType::Database), parent_name),
20940                    Keyword::SCHEMA => (Some(ShowStatementInParentType::Schema), parent_name),
20941                    Keyword::TABLE => (Some(ShowStatementInParentType::Table), parent_name),
20942                    Keyword::VIEW => (Some(ShowStatementInParentType::View), parent_name),
20943                    _ => {
20944                        return self.expected_ref(
20945                            "one of ACCOUNT, DATABASE, SCHEMA, TABLE or VIEW",
20946                            self.peek_token_ref(),
20947                        )
20948                    }
20949                }
20950            }
20951            None => {
20952                // Parsing MySQL style FROM tbl_name FROM db_name
20953                // which is equivalent to FROM tbl_name.db_name
20954                let mut parent_name = self.parse_object_name(false)?;
20955                if self
20956                    .parse_one_of_keywords(&[Keyword::FROM, Keyword::IN])
20957                    .is_some()
20958                {
20959                    parent_name
20960                        .0
20961                        .insert(0, ObjectNamePart::Identifier(self.parse_identifier()?));
20962                }
20963                (None, Some(parent_name))
20964            }
20965        };
20966
20967        Ok(Some(ShowStatementIn {
20968            clause,
20969            parent_type,
20970            parent_name,
20971        }))
20972    }
20973
20974    fn maybe_parse_show_stmt_starts_with(&mut self) -> Result<Option<ValueWithSpan>, ParserError> {
20975        if self.parse_keywords(&[Keyword::STARTS, Keyword::WITH]) {
20976            Ok(Some(self.parse_value()?))
20977        } else {
20978            Ok(None)
20979        }
20980    }
20981
20982    fn maybe_parse_show_stmt_limit(&mut self) -> Result<Option<Expr>, ParserError> {
20983        if self.parse_keyword(Keyword::LIMIT) {
20984            Ok(self.parse_limit()?)
20985        } else {
20986            Ok(None)
20987        }
20988    }
20989
20990    fn maybe_parse_show_stmt_from(&mut self) -> Result<Option<ValueWithSpan>, ParserError> {
20991        if self.parse_keyword(Keyword::FROM) {
20992            Ok(Some(self.parse_value()?))
20993        } else {
20994            Ok(None)
20995        }
20996    }
20997
20998    pub(crate) fn in_column_definition_state(&self) -> bool {
20999        matches!(self.state, ColumnDefinition)
21000    }
21001
21002    /// Parses options provided in key-value format.
21003    ///
21004    /// * `parenthesized` - true if the options are enclosed in parenthesis
21005    /// * `end_words` - a list of keywords that any of them indicates the end of the options section
21006    pub(crate) fn parse_key_value_options(
21007        &mut self,
21008        parenthesized: bool,
21009        end_words: &[Keyword],
21010    ) -> Result<KeyValueOptions, ParserError> {
21011        let mut options: Vec<KeyValueOption> = Vec::new();
21012        let mut delimiter = KeyValueOptionsDelimiter::Space;
21013        if parenthesized {
21014            self.expect_token(&Token::LParen)?;
21015        }
21016        loop {
21017            match self.next_token().token {
21018                Token::RParen => {
21019                    if parenthesized {
21020                        break;
21021                    } else {
21022                        return self.expected_ref(" another option or EOF", self.peek_token_ref());
21023                    }
21024                }
21025                Token::EOF => break,
21026                Token::SemiColon => {
21027                    self.prev_token();
21028                    break;
21029                }
21030                Token::Comma => {
21031                    delimiter = KeyValueOptionsDelimiter::Comma;
21032                    continue;
21033                }
21034                Token::Word(w) if !end_words.contains(&w.keyword) => {
21035                    options.push(self.parse_key_value_option(&w)?)
21036                }
21037                Token::Word(w) if end_words.contains(&w.keyword) => {
21038                    self.prev_token();
21039                    break;
21040                }
21041                _ => {
21042                    return self.expected_ref(
21043                        "another option, EOF, SemiColon, Comma or ')'",
21044                        self.peek_token_ref(),
21045                    )
21046                }
21047            };
21048        }
21049
21050        Ok(KeyValueOptions { delimiter, options })
21051    }
21052
21053    /// Parses a `KEY = VALUE` construct based on the specified key
21054    pub(crate) fn parse_key_value_option(
21055        &mut self,
21056        key: &Word,
21057    ) -> Result<KeyValueOption, ParserError> {
21058        self.expect_token(&Token::Eq)?;
21059        let peeked_token = self.peek_token();
21060        match peeked_token.token {
21061            Token::SingleQuotedString(_) => Ok(KeyValueOption {
21062                option_name: key.value.clone(),
21063                option_value: KeyValueOptionKind::Single(self.parse_value()?),
21064            }),
21065            Token::Word(word)
21066                if word.keyword == Keyword::TRUE || word.keyword == Keyword::FALSE =>
21067            {
21068                Ok(KeyValueOption {
21069                    option_name: key.value.clone(),
21070                    option_value: KeyValueOptionKind::Single(self.parse_value()?),
21071                })
21072            }
21073            Token::Number(..) => Ok(KeyValueOption {
21074                option_name: key.value.clone(),
21075                option_value: KeyValueOptionKind::Single(self.parse_value()?),
21076            }),
21077            Token::Word(word) => {
21078                self.next_token();
21079                Ok(KeyValueOption {
21080                    option_name: key.value.clone(),
21081                    option_value: KeyValueOptionKind::Single(
21082                        Value::Placeholder(word.value.clone()).with_span(peeked_token.span),
21083                    ),
21084                })
21085            }
21086            Token::LParen => {
21087                // Can be a list of values or a list of key value properties.
21088                // Try to parse a list of values and if that fails, try to parse
21089                // a list of key-value properties.
21090                match self.maybe_parse(|parser| {
21091                    parser.expect_token(&Token::LParen)?;
21092                    let values = parser.parse_comma_separated0(|p| p.parse_value(), Token::RParen);
21093                    parser.expect_token(&Token::RParen)?;
21094                    values
21095                })? {
21096                    Some(values) => Ok(KeyValueOption {
21097                        option_name: key.value.clone(),
21098                        option_value: KeyValueOptionKind::Multi(values),
21099                    }),
21100                    None => Ok(KeyValueOption {
21101                        option_name: key.value.clone(),
21102                        option_value: KeyValueOptionKind::KeyValueOptions(Box::new(
21103                            self.parse_key_value_options(true, &[])?,
21104                        )),
21105                    }),
21106                }
21107            }
21108            _ => self.expected_ref("expected option value", self.peek_token_ref()),
21109        }
21110    }
21111
21112    /// Parses a RESET statement
21113    fn parse_reset(&mut self) -> Result<ResetStatement, ParserError> {
21114        if self.parse_keyword(Keyword::ALL) {
21115            return Ok(ResetStatement { reset: Reset::ALL });
21116        }
21117
21118        let obj = self.parse_object_name(false)?;
21119        Ok(ResetStatement {
21120            reset: Reset::ConfigurationParameter(obj),
21121        })
21122    }
21123}
21124
21125fn maybe_prefixed_expr(expr: Expr, prefix: Option<Ident>) -> Expr {
21126    if let Some(prefix) = prefix {
21127        Expr::Prefixed {
21128            prefix,
21129            value: Box::new(expr),
21130        }
21131    } else {
21132        expr
21133    }
21134}
21135
21136impl Word {
21137    /// Convert a reference to this word into an [`Ident`] by cloning the value.
21138    ///
21139    /// Use this method when you need to keep the original `Word` around.
21140    /// If you can consume the `Word`, prefer [`into_ident`](Self::into_ident) instead
21141    /// to avoid cloning.
21142    pub fn to_ident(&self, span: Span) -> Ident {
21143        Ident {
21144            value: self.value.clone(),
21145            quote_style: self.quote_style,
21146            span,
21147        }
21148    }
21149
21150    /// Convert this word into an [`Ident`] identifier, consuming the `Word`.
21151    ///
21152    /// This avoids cloning the string value. If you need to keep the original
21153    /// `Word`, use [`to_ident`](Self::to_ident) instead.
21154    pub fn into_ident(self, span: Span) -> Ident {
21155        Ident {
21156            value: self.value,
21157            quote_style: self.quote_style,
21158            span,
21159        }
21160    }
21161}
21162
21163#[cfg(test)]
21164mod tests {
21165    use crate::test_utils::{all_dialects, TestedDialects};
21166
21167    use super::*;
21168
21169    #[test]
21170    fn test_prev_index() {
21171        let sql = "SELECT version";
21172        all_dialects().run_parser_method(sql, |parser| {
21173            assert_eq!(parser.peek_token(), Token::make_keyword("SELECT"));
21174            assert_eq!(parser.next_token(), Token::make_keyword("SELECT"));
21175            parser.prev_token();
21176            assert_eq!(parser.next_token(), Token::make_keyword("SELECT"));
21177            assert_eq!(parser.next_token(), Token::make_word("version", None));
21178            parser.prev_token();
21179            assert_eq!(parser.peek_token(), Token::make_word("version", None));
21180            assert_eq!(parser.next_token(), Token::make_word("version", None));
21181            assert_eq!(parser.peek_token(), Token::EOF);
21182            parser.prev_token();
21183            assert_eq!(parser.next_token(), Token::make_word("version", None));
21184            assert_eq!(parser.next_token(), Token::EOF);
21185            assert_eq!(parser.next_token(), Token::EOF);
21186            parser.prev_token();
21187        });
21188    }
21189
21190    #[test]
21191    fn test_peek_tokens() {
21192        all_dialects().run_parser_method("SELECT foo AS bar FROM baz", |parser| {
21193            assert!(matches!(
21194                parser.peek_tokens(),
21195                [Token::Word(Word {
21196                    keyword: Keyword::SELECT,
21197                    ..
21198                })]
21199            ));
21200
21201            assert!(matches!(
21202                parser.peek_tokens(),
21203                [
21204                    Token::Word(Word {
21205                        keyword: Keyword::SELECT,
21206                        ..
21207                    }),
21208                    Token::Word(_),
21209                    Token::Word(Word {
21210                        keyword: Keyword::AS,
21211                        ..
21212                    }),
21213                ]
21214            ));
21215
21216            for _ in 0..4 {
21217                parser.next_token();
21218            }
21219
21220            assert!(matches!(
21221                parser.peek_tokens(),
21222                [
21223                    Token::Word(Word {
21224                        keyword: Keyword::FROM,
21225                        ..
21226                    }),
21227                    Token::Word(_),
21228                    Token::EOF,
21229                    Token::EOF,
21230                ]
21231            ))
21232        })
21233    }
21234
21235    #[cfg(test)]
21236    mod test_parse_data_type {
21237        use crate::ast::{
21238            CharLengthUnits, CharacterLength, DataType, ExactNumberInfo, ObjectName, TimezoneInfo,
21239        };
21240        use crate::dialect::{AnsiDialect, GenericDialect, PostgreSqlDialect};
21241        use crate::test_utils::TestedDialects;
21242
21243        macro_rules! test_parse_data_type {
21244            ($dialect:expr, $input:expr, $expected_type:expr $(,)?) => {{
21245                $dialect.run_parser_method(&*$input, |parser| {
21246                    let data_type = parser.parse_data_type().unwrap();
21247                    assert_eq!($expected_type, data_type);
21248                    assert_eq!($input.to_string(), data_type.to_string());
21249                });
21250            }};
21251        }
21252
21253        #[test]
21254        fn test_ansii_character_string_types() {
21255            // Character string types: <https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#character-string-type>
21256            let dialect =
21257                TestedDialects::new(vec![Box::new(GenericDialect {}), Box::new(AnsiDialect {})]);
21258
21259            test_parse_data_type!(dialect, "CHARACTER", DataType::Character(None));
21260
21261            test_parse_data_type!(
21262                dialect,
21263                "CHARACTER(20)",
21264                DataType::Character(Some(CharacterLength::IntegerLength {
21265                    length: 20,
21266                    unit: None
21267                }))
21268            );
21269
21270            test_parse_data_type!(
21271                dialect,
21272                "CHARACTER(20 CHARACTERS)",
21273                DataType::Character(Some(CharacterLength::IntegerLength {
21274                    length: 20,
21275                    unit: Some(CharLengthUnits::Characters)
21276                }))
21277            );
21278
21279            test_parse_data_type!(
21280                dialect,
21281                "CHARACTER(20 OCTETS)",
21282                DataType::Character(Some(CharacterLength::IntegerLength {
21283                    length: 20,
21284                    unit: Some(CharLengthUnits::Octets)
21285                }))
21286            );
21287
21288            test_parse_data_type!(dialect, "CHAR", DataType::Char(None));
21289
21290            test_parse_data_type!(
21291                dialect,
21292                "CHAR(20)",
21293                DataType::Char(Some(CharacterLength::IntegerLength {
21294                    length: 20,
21295                    unit: None
21296                }))
21297            );
21298
21299            test_parse_data_type!(
21300                dialect,
21301                "CHAR(20 CHARACTERS)",
21302                DataType::Char(Some(CharacterLength::IntegerLength {
21303                    length: 20,
21304                    unit: Some(CharLengthUnits::Characters)
21305                }))
21306            );
21307
21308            test_parse_data_type!(
21309                dialect,
21310                "CHAR(20 OCTETS)",
21311                DataType::Char(Some(CharacterLength::IntegerLength {
21312                    length: 20,
21313                    unit: Some(CharLengthUnits::Octets)
21314                }))
21315            );
21316
21317            test_parse_data_type!(
21318                dialect,
21319                "CHARACTER VARYING(20)",
21320                DataType::CharacterVarying(Some(CharacterLength::IntegerLength {
21321                    length: 20,
21322                    unit: None
21323                }))
21324            );
21325
21326            test_parse_data_type!(
21327                dialect,
21328                "CHARACTER VARYING(20 CHARACTERS)",
21329                DataType::CharacterVarying(Some(CharacterLength::IntegerLength {
21330                    length: 20,
21331                    unit: Some(CharLengthUnits::Characters)
21332                }))
21333            );
21334
21335            test_parse_data_type!(
21336                dialect,
21337                "CHARACTER VARYING(20 OCTETS)",
21338                DataType::CharacterVarying(Some(CharacterLength::IntegerLength {
21339                    length: 20,
21340                    unit: Some(CharLengthUnits::Octets)
21341                }))
21342            );
21343
21344            test_parse_data_type!(
21345                dialect,
21346                "CHAR VARYING(20)",
21347                DataType::CharVarying(Some(CharacterLength::IntegerLength {
21348                    length: 20,
21349                    unit: None
21350                }))
21351            );
21352
21353            test_parse_data_type!(
21354                dialect,
21355                "CHAR VARYING(20 CHARACTERS)",
21356                DataType::CharVarying(Some(CharacterLength::IntegerLength {
21357                    length: 20,
21358                    unit: Some(CharLengthUnits::Characters)
21359                }))
21360            );
21361
21362            test_parse_data_type!(
21363                dialect,
21364                "CHAR VARYING(20 OCTETS)",
21365                DataType::CharVarying(Some(CharacterLength::IntegerLength {
21366                    length: 20,
21367                    unit: Some(CharLengthUnits::Octets)
21368                }))
21369            );
21370
21371            test_parse_data_type!(
21372                dialect,
21373                "VARCHAR(20)",
21374                DataType::Varchar(Some(CharacterLength::IntegerLength {
21375                    length: 20,
21376                    unit: None
21377                }))
21378            );
21379        }
21380
21381        #[test]
21382        fn test_ansii_character_large_object_types() {
21383            // Character large object types: <https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#character-large-object-length>
21384            let dialect =
21385                TestedDialects::new(vec![Box::new(GenericDialect {}), Box::new(AnsiDialect {})]);
21386
21387            test_parse_data_type!(
21388                dialect,
21389                "CHARACTER LARGE OBJECT",
21390                DataType::CharacterLargeObject(None)
21391            );
21392            test_parse_data_type!(
21393                dialect,
21394                "CHARACTER LARGE OBJECT(20)",
21395                DataType::CharacterLargeObject(Some(20))
21396            );
21397
21398            test_parse_data_type!(
21399                dialect,
21400                "CHAR LARGE OBJECT",
21401                DataType::CharLargeObject(None)
21402            );
21403            test_parse_data_type!(
21404                dialect,
21405                "CHAR LARGE OBJECT(20)",
21406                DataType::CharLargeObject(Some(20))
21407            );
21408
21409            test_parse_data_type!(dialect, "CLOB", DataType::Clob(None));
21410            test_parse_data_type!(dialect, "CLOB(20)", DataType::Clob(Some(20)));
21411        }
21412
21413        #[test]
21414        fn test_parse_custom_types() {
21415            let dialect =
21416                TestedDialects::new(vec![Box::new(GenericDialect {}), Box::new(AnsiDialect {})]);
21417
21418            test_parse_data_type!(
21419                dialect,
21420                "GEOMETRY",
21421                DataType::Custom(ObjectName::from(vec!["GEOMETRY".into()]), vec![])
21422            );
21423
21424            test_parse_data_type!(
21425                dialect,
21426                "GEOMETRY(POINT)",
21427                DataType::Custom(
21428                    ObjectName::from(vec!["GEOMETRY".into()]),
21429                    vec!["POINT".to_string()]
21430                )
21431            );
21432
21433            test_parse_data_type!(
21434                dialect,
21435                "GEOMETRY(POINT, 4326)",
21436                DataType::Custom(
21437                    ObjectName::from(vec!["GEOMETRY".into()]),
21438                    vec!["POINT".to_string(), "4326".to_string()]
21439                )
21440            );
21441        }
21442
21443        #[test]
21444        fn test_ansii_exact_numeric_types() {
21445            // Exact numeric types: <https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#exact-numeric-type>
21446            let dialect = TestedDialects::new(vec![
21447                Box::new(GenericDialect {}),
21448                Box::new(AnsiDialect {}),
21449                Box::new(PostgreSqlDialect {}),
21450            ]);
21451
21452            test_parse_data_type!(dialect, "NUMERIC", DataType::Numeric(ExactNumberInfo::None));
21453
21454            test_parse_data_type!(
21455                dialect,
21456                "NUMERIC(2)",
21457                DataType::Numeric(ExactNumberInfo::Precision(2))
21458            );
21459
21460            test_parse_data_type!(
21461                dialect,
21462                "NUMERIC(2,10)",
21463                DataType::Numeric(ExactNumberInfo::PrecisionAndScale(2, 10))
21464            );
21465
21466            test_parse_data_type!(dialect, "DECIMAL", DataType::Decimal(ExactNumberInfo::None));
21467
21468            test_parse_data_type!(
21469                dialect,
21470                "DECIMAL(2)",
21471                DataType::Decimal(ExactNumberInfo::Precision(2))
21472            );
21473
21474            test_parse_data_type!(
21475                dialect,
21476                "DECIMAL(2,10)",
21477                DataType::Decimal(ExactNumberInfo::PrecisionAndScale(2, 10))
21478            );
21479
21480            test_parse_data_type!(dialect, "DEC", DataType::Dec(ExactNumberInfo::None));
21481
21482            test_parse_data_type!(
21483                dialect,
21484                "DEC(2)",
21485                DataType::Dec(ExactNumberInfo::Precision(2))
21486            );
21487
21488            test_parse_data_type!(
21489                dialect,
21490                "DEC(2,10)",
21491                DataType::Dec(ExactNumberInfo::PrecisionAndScale(2, 10))
21492            );
21493
21494            // Test negative scale values.
21495            test_parse_data_type!(
21496                dialect,
21497                "NUMERIC(10,-2)",
21498                DataType::Numeric(ExactNumberInfo::PrecisionAndScale(10, -2))
21499            );
21500
21501            test_parse_data_type!(
21502                dialect,
21503                "DECIMAL(1000,-10)",
21504                DataType::Decimal(ExactNumberInfo::PrecisionAndScale(1000, -10))
21505            );
21506
21507            test_parse_data_type!(
21508                dialect,
21509                "DEC(5,-1000)",
21510                DataType::Dec(ExactNumberInfo::PrecisionAndScale(5, -1000))
21511            );
21512
21513            test_parse_data_type!(
21514                dialect,
21515                "NUMERIC(10,-5)",
21516                DataType::Numeric(ExactNumberInfo::PrecisionAndScale(10, -5))
21517            );
21518
21519            test_parse_data_type!(
21520                dialect,
21521                "DECIMAL(20,-10)",
21522                DataType::Decimal(ExactNumberInfo::PrecisionAndScale(20, -10))
21523            );
21524
21525            test_parse_data_type!(
21526                dialect,
21527                "DEC(5,-2)",
21528                DataType::Dec(ExactNumberInfo::PrecisionAndScale(5, -2))
21529            );
21530
21531            dialect.run_parser_method("NUMERIC(10,+5)", |parser| {
21532                let data_type = parser.parse_data_type().unwrap();
21533                assert_eq!(
21534                    DataType::Numeric(ExactNumberInfo::PrecisionAndScale(10, 5)),
21535                    data_type
21536                );
21537                // Note: Explicit '+' sign is not preserved in output, which is correct
21538                assert_eq!("NUMERIC(10,5)", data_type.to_string());
21539            });
21540        }
21541
21542        #[test]
21543        fn test_ansii_date_type() {
21544            // Datetime types: <https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#datetime-type>
21545            let dialect =
21546                TestedDialects::new(vec![Box::new(GenericDialect {}), Box::new(AnsiDialect {})]);
21547
21548            test_parse_data_type!(dialect, "DATE", DataType::Date);
21549
21550            test_parse_data_type!(dialect, "TIME", DataType::Time(None, TimezoneInfo::None));
21551
21552            test_parse_data_type!(
21553                dialect,
21554                "TIME(6)",
21555                DataType::Time(Some(6), TimezoneInfo::None)
21556            );
21557
21558            test_parse_data_type!(
21559                dialect,
21560                "TIME WITH TIME ZONE",
21561                DataType::Time(None, TimezoneInfo::WithTimeZone)
21562            );
21563
21564            test_parse_data_type!(
21565                dialect,
21566                "TIME(6) WITH TIME ZONE",
21567                DataType::Time(Some(6), TimezoneInfo::WithTimeZone)
21568            );
21569
21570            test_parse_data_type!(
21571                dialect,
21572                "TIME WITHOUT TIME ZONE",
21573                DataType::Time(None, TimezoneInfo::WithoutTimeZone)
21574            );
21575
21576            test_parse_data_type!(
21577                dialect,
21578                "TIME(6) WITHOUT TIME ZONE",
21579                DataType::Time(Some(6), TimezoneInfo::WithoutTimeZone)
21580            );
21581
21582            test_parse_data_type!(
21583                dialect,
21584                "TIMESTAMP",
21585                DataType::Timestamp(None, TimezoneInfo::None)
21586            );
21587
21588            test_parse_data_type!(
21589                dialect,
21590                "TIMESTAMP(22)",
21591                DataType::Timestamp(Some(22), TimezoneInfo::None)
21592            );
21593
21594            test_parse_data_type!(
21595                dialect,
21596                "TIMESTAMP(22) WITH TIME ZONE",
21597                DataType::Timestamp(Some(22), TimezoneInfo::WithTimeZone)
21598            );
21599
21600            test_parse_data_type!(
21601                dialect,
21602                "TIMESTAMP(33) WITHOUT TIME ZONE",
21603                DataType::Timestamp(Some(33), TimezoneInfo::WithoutTimeZone)
21604            );
21605        }
21606    }
21607
21608    #[test]
21609    fn test_parse_schema_name() {
21610        // The expected name should be identical as the input name, that's why I don't receive both
21611        macro_rules! test_parse_schema_name {
21612            ($input:expr, $expected_name:expr $(,)?) => {{
21613                all_dialects().run_parser_method(&*$input, |parser| {
21614                    let schema_name = parser.parse_schema_name().unwrap();
21615                    // Validate that the structure is the same as expected
21616                    assert_eq!(schema_name, $expected_name);
21617                    // Validate that the input and the expected structure serialization are the same
21618                    assert_eq!(schema_name.to_string(), $input.to_string());
21619                });
21620            }};
21621        }
21622
21623        let dummy_name = ObjectName::from(vec![Ident::new("dummy_name")]);
21624        let dummy_authorization = Ident::new("dummy_authorization");
21625
21626        test_parse_schema_name!(
21627            format!("{dummy_name}"),
21628            SchemaName::Simple(dummy_name.clone())
21629        );
21630
21631        test_parse_schema_name!(
21632            format!("AUTHORIZATION {dummy_authorization}"),
21633            SchemaName::UnnamedAuthorization(dummy_authorization.clone()),
21634        );
21635        test_parse_schema_name!(
21636            format!("{dummy_name} AUTHORIZATION {dummy_authorization}"),
21637            SchemaName::NamedAuthorization(dummy_name.clone(), dummy_authorization.clone()),
21638        );
21639    }
21640
21641    #[test]
21642    fn mysql_parse_index_table_constraint() {
21643        macro_rules! test_parse_table_constraint {
21644            ($dialect:expr, $input:expr, $expected:expr $(,)?) => {{
21645                $dialect.run_parser_method(&*$input, |parser| {
21646                    let constraint = parser.parse_optional_table_constraint().unwrap().unwrap();
21647                    // Validate that the structure is the same as expected
21648                    assert_eq!(constraint, $expected);
21649                    // Validate that the input and the expected structure serialization are the same
21650                    assert_eq!(constraint.to_string(), $input.to_string());
21651                });
21652            }};
21653        }
21654
21655        fn mk_expected_col(name: &str) -> IndexColumn {
21656            IndexColumn {
21657                column: OrderByExpr {
21658                    expr: Expr::Identifier(name.into()),
21659                    options: OrderByOptions {
21660                        sort: None,
21661                        nulls_first: None,
21662                    },
21663                    with_fill: None,
21664                },
21665                operator_class: None,
21666            }
21667        }
21668
21669        let dialect =
21670            TestedDialects::new(vec![Box::new(GenericDialect {}), Box::new(MySqlDialect {})]);
21671
21672        test_parse_table_constraint!(
21673            dialect,
21674            "INDEX (c1)",
21675            IndexConstraint {
21676                display_as_key: false,
21677                name: None,
21678                index_type: None,
21679                columns: vec![mk_expected_col("c1")],
21680                index_options: vec![],
21681            }
21682            .into()
21683        );
21684
21685        test_parse_table_constraint!(
21686            dialect,
21687            "KEY (c1)",
21688            IndexConstraint {
21689                display_as_key: true,
21690                name: None,
21691                index_type: None,
21692                columns: vec![mk_expected_col("c1")],
21693                index_options: vec![],
21694            }
21695            .into()
21696        );
21697
21698        test_parse_table_constraint!(
21699            dialect,
21700            "INDEX 'index' (c1, c2)",
21701            TableConstraint::Index(IndexConstraint {
21702                display_as_key: false,
21703                name: Some(Ident::with_quote('\'', "index")),
21704                index_type: None,
21705                columns: vec![mk_expected_col("c1"), mk_expected_col("c2")],
21706                index_options: vec![],
21707            })
21708        );
21709
21710        test_parse_table_constraint!(
21711            dialect,
21712            "INDEX USING BTREE (c1)",
21713            IndexConstraint {
21714                display_as_key: false,
21715                name: None,
21716                index_type: Some(IndexType::BTree),
21717                columns: vec![mk_expected_col("c1")],
21718                index_options: vec![],
21719            }
21720            .into()
21721        );
21722
21723        test_parse_table_constraint!(
21724            dialect,
21725            "INDEX USING HASH (c1)",
21726            IndexConstraint {
21727                display_as_key: false,
21728                name: None,
21729                index_type: Some(IndexType::Hash),
21730                columns: vec![mk_expected_col("c1")],
21731                index_options: vec![],
21732            }
21733            .into()
21734        );
21735
21736        test_parse_table_constraint!(
21737            dialect,
21738            "INDEX idx_name USING BTREE (c1)",
21739            IndexConstraint {
21740                display_as_key: false,
21741                name: Some(Ident::new("idx_name")),
21742                index_type: Some(IndexType::BTree),
21743                columns: vec![mk_expected_col("c1")],
21744                index_options: vec![],
21745            }
21746            .into()
21747        );
21748
21749        test_parse_table_constraint!(
21750            dialect,
21751            "INDEX idx_name USING HASH (c1)",
21752            IndexConstraint {
21753                display_as_key: false,
21754                name: Some(Ident::new("idx_name")),
21755                index_type: Some(IndexType::Hash),
21756                columns: vec![mk_expected_col("c1")],
21757                index_options: vec![],
21758            }
21759            .into()
21760        );
21761    }
21762
21763    #[test]
21764    fn test_tokenizer_error_loc() {
21765        let sql = "foo '";
21766        let ast = Parser::parse_sql(&GenericDialect, sql);
21767        assert_eq!(
21768            ast,
21769            Err(ParserError::TokenizerError(
21770                "Unterminated string literal at Line: 1, Column: 5".to_string()
21771            ))
21772        );
21773    }
21774
21775    #[test]
21776    fn test_parser_error_loc() {
21777        let sql = "SELECT this is a syntax error";
21778        let ast = Parser::parse_sql(&GenericDialect, sql);
21779        assert_eq!(
21780            ast,
21781            Err(ParserError::ParserError(
21782                "Expected: [NOT] NULL | TRUE | FALSE | DISTINCT | [form] NORMALIZED FROM after IS, found: a at Line: 1, Column: 16"
21783                    .to_string()
21784            ))
21785        );
21786    }
21787
21788    #[test]
21789    fn test_nested_explain_error() {
21790        let sql = "EXPLAIN EXPLAIN SELECT 1";
21791        let ast = Parser::parse_sql(&GenericDialect, sql);
21792        assert_eq!(
21793            ast,
21794            Err(ParserError::ParserError(
21795                "Explain must be root of the plan".to_string()
21796            ))
21797        );
21798    }
21799
21800    #[test]
21801    fn test_parse_multipart_identifier_positive() {
21802        let dialect = TestedDialects::new(vec![Box::new(GenericDialect {})]);
21803
21804        // parse multipart with quotes
21805        let expected = vec![
21806            Ident {
21807                value: "CATALOG".to_string(),
21808                quote_style: None,
21809                span: Span::empty(),
21810            },
21811            Ident {
21812                value: "F(o)o. \"bar".to_string(),
21813                quote_style: Some('"'),
21814                span: Span::empty(),
21815            },
21816            Ident {
21817                value: "table".to_string(),
21818                quote_style: None,
21819                span: Span::empty(),
21820            },
21821        ];
21822        dialect.run_parser_method(r#"CATALOG."F(o)o. ""bar".table"#, |parser| {
21823            let actual = parser.parse_multipart_identifier().unwrap();
21824            assert_eq!(expected, actual);
21825        });
21826
21827        // allow whitespace between ident parts
21828        let expected = vec![
21829            Ident {
21830                value: "CATALOG".to_string(),
21831                quote_style: None,
21832                span: Span::empty(),
21833            },
21834            Ident {
21835                value: "table".to_string(),
21836                quote_style: None,
21837                span: Span::empty(),
21838            },
21839        ];
21840        dialect.run_parser_method("CATALOG . table", |parser| {
21841            let actual = parser.parse_multipart_identifier().unwrap();
21842            assert_eq!(expected, actual);
21843        });
21844    }
21845
21846    #[test]
21847    fn test_parse_multipart_identifier_negative() {
21848        macro_rules! test_parse_multipart_identifier_error {
21849            ($input:expr, $expected_err:expr $(,)?) => {{
21850                all_dialects().run_parser_method(&*$input, |parser| {
21851                    let actual_err = parser.parse_multipart_identifier().unwrap_err();
21852                    assert_eq!(actual_err.to_string(), $expected_err);
21853                });
21854            }};
21855        }
21856
21857        test_parse_multipart_identifier_error!(
21858            "",
21859            "sql parser error: Empty input when parsing identifier",
21860        );
21861
21862        test_parse_multipart_identifier_error!(
21863            "*schema.table",
21864            "sql parser error: Unexpected token in identifier: *",
21865        );
21866
21867        test_parse_multipart_identifier_error!(
21868            "schema.table*",
21869            "sql parser error: Unexpected token in identifier: *",
21870        );
21871
21872        test_parse_multipart_identifier_error!(
21873            "schema.table.",
21874            "sql parser error: Trailing period in identifier",
21875        );
21876
21877        test_parse_multipart_identifier_error!(
21878            "schema.*",
21879            "sql parser error: Unexpected token following period in identifier: *",
21880        );
21881    }
21882
21883    #[test]
21884    fn test_mysql_partition_selection() {
21885        let sql = "SELECT * FROM employees PARTITION (p0, p2)";
21886        let expected = vec!["p0", "p2"];
21887
21888        let ast: Vec<Statement> = Parser::parse_sql(&MySqlDialect {}, sql).unwrap();
21889        assert_eq!(ast.len(), 1);
21890        if let Statement::Query(v) = &ast[0] {
21891            if let SetExpr::Select(select) = &*v.body {
21892                assert_eq!(select.from.len(), 1);
21893                let from: &TableWithJoins = &select.from[0];
21894                let table_factor = &from.relation;
21895                if let TableFactor::Table { partitions, .. } = table_factor {
21896                    let actual: Vec<&str> = partitions
21897                        .iter()
21898                        .map(|ident| ident.value.as_str())
21899                        .collect();
21900                    assert_eq!(expected, actual);
21901                }
21902            }
21903        } else {
21904            panic!("fail to parse mysql partition selection");
21905        }
21906    }
21907
21908    #[test]
21909    fn test_replace_into_placeholders() {
21910        let sql = "REPLACE INTO t (a) VALUES (&a)";
21911
21912        assert!(Parser::parse_sql(&GenericDialect {}, sql).is_err());
21913    }
21914
21915    #[test]
21916    fn test_replace_into_set_placeholder() {
21917        let sql = "REPLACE INTO t SET ?";
21918
21919        assert!(Parser::parse_sql(&GenericDialect {}, sql).is_err());
21920    }
21921
21922    #[test]
21923    fn test_replace_incomplete() {
21924        let sql = r#"REPLACE"#;
21925
21926        assert!(Parser::parse_sql(&MySqlDialect {}, sql).is_err());
21927    }
21928
21929    #[test]
21930    fn test_placeholder_invalid_whitespace() {
21931        for w in ["  ", "/*invalid*/"] {
21932            let sql = format!("\nSELECT\n  :{w}fooBar");
21933            assert!(Parser::parse_sql(&GenericDialect, &sql).is_err());
21934        }
21935    }
21936}