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
10263                Ok(Some(
10264                    FullTextOrSpatialConstraint {
10265                        fulltext,
10266                        index_type_display,
10267                        opt_index_name,
10268                        columns,
10269                    }
10270                    .into(),
10271                ))
10272            }
10273            Token::Word(w)
10274                if w.keyword == Keyword::EXCLUDE && self.dialect.supports_exclude_constraint() =>
10275            {
10276                // `EXCLUDE` is a non-reserved keyword in PostgreSQL, so it is a
10277                // valid column name. Only treat it as an exclusion constraint
10278                // when it begins one (named, or followed by `USING` / `(`);
10279                // otherwise backtrack and let it parse as a column.
10280                if name.is_some()
10281                    || self.peek_keyword(Keyword::USING)
10282                    || self.peek_token_ref().token == Token::LParen
10283                {
10284                    Ok(Some(self.parse_exclude_constraint(name)?.into()))
10285                } else {
10286                    self.prev_token();
10287                    Ok(None)
10288                }
10289            }
10290            _ => {
10291                if name.is_some() {
10292                    self.expected("PRIMARY, UNIQUE, FOREIGN, CHECK, or EXCLUDE", next_token)
10293                } else {
10294                    self.prev_token();
10295                    Ok(None)
10296                }
10297            }
10298        }
10299    }
10300
10301    // The leading `EXCLUDE` keyword is already consumed by the caller.
10302    fn parse_exclude_constraint(
10303        &mut self,
10304        name: Option<Ident>,
10305    ) -> Result<ExcludeConstraint, ParserError> {
10306        let index_method = if self.parse_keyword(Keyword::USING) {
10307            Some(self.parse_identifier()?)
10308        } else {
10309            None
10310        };
10311
10312        self.expect_token(&Token::LParen)?;
10313        let elements = self.parse_comma_separated(|p| p.parse_exclude_constraint_element())?;
10314        self.expect_token(&Token::RParen)?;
10315
10316        let include = if self.parse_keyword(Keyword::INCLUDE) {
10317            self.expect_token(&Token::LParen)?;
10318            let cols = self.parse_comma_separated(|p| p.parse_identifier())?;
10319            self.expect_token(&Token::RParen)?;
10320            cols
10321        } else {
10322            vec![]
10323        };
10324
10325        let where_clause = if self.parse_keyword(Keyword::WHERE) {
10326            self.expect_token(&Token::LParen)?;
10327            let predicate = self.parse_expr()?;
10328            self.expect_token(&Token::RParen)?;
10329            Some(Box::new(predicate))
10330        } else {
10331            None
10332        };
10333
10334        let characteristics = self.parse_constraint_characteristics()?;
10335
10336        Ok(ExcludeConstraint {
10337            name,
10338            index_method,
10339            elements,
10340            include,
10341            where_clause,
10342            characteristics,
10343        })
10344    }
10345
10346    fn parse_exclude_constraint_element(
10347        &mut self,
10348    ) -> Result<ExcludeConstraintElement, ParserError> {
10349        let column = self.parse_create_index_expr()?;
10350        self.expect_keyword_is(Keyword::WITH)?;
10351        let operator = self.parse_exclude_constraint_operator()?;
10352        Ok(ExcludeConstraintElement { column, operator })
10353    }
10354
10355    /// Parse the operator that follows `WITH` in an `EXCLUDE` element.
10356    fn parse_exclude_constraint_operator(
10357        &mut self,
10358    ) -> Result<ExcludeConstraintOperator, ParserError> {
10359        if self.parse_keyword(Keyword::OPERATOR) {
10360            return Ok(ExcludeConstraintOperator::PGOperator(
10361                self.parse_pg_operator_ident_parts()?,
10362            ));
10363        }
10364
10365        let operator_token = self.next_token();
10366        Ok(ExcludeConstraintOperator::Token(
10367            operator_token.token.to_string(),
10368        ))
10369    }
10370
10371    /// Parse the body of a Postgres `OPERATOR(schema.op)` form: the
10372    /// parenthesized `.`-separated path of name parts after the `OPERATOR`
10373    /// keyword. Shared between binary expression parsing and exclusion
10374    /// constraint parsing.
10375    fn parse_pg_operator_ident_parts(&mut self) -> Result<Vec<String>, ParserError> {
10376        self.expect_token(&Token::LParen)?;
10377        if self.peek_token_ref().token == Token::RParen {
10378            let token = self.next_token();
10379            return self.expected("operator name", token);
10380        }
10381        let mut idents = vec![];
10382        loop {
10383            self.advance_token();
10384            idents.push(self.get_current_token().to_string());
10385            if !self.consume_token(&Token::Period) {
10386                break;
10387            }
10388        }
10389        self.expect_token(&Token::RParen)?;
10390        Ok(idents)
10391    }
10392
10393    fn parse_optional_nulls_distinct(&mut self) -> Result<NullsDistinctOption, ParserError> {
10394        Ok(if self.parse_keyword(Keyword::NULLS) {
10395            let not = self.parse_keyword(Keyword::NOT);
10396            self.expect_keyword_is(Keyword::DISTINCT)?;
10397            if not {
10398                NullsDistinctOption::NotDistinct
10399            } else {
10400                NullsDistinctOption::Distinct
10401            }
10402        } else {
10403            NullsDistinctOption::None
10404        })
10405    }
10406
10407    /// Optionally parse a parenthesized list of `SqlOption`s introduced by `keyword`.
10408    pub fn maybe_parse_options(
10409        &mut self,
10410        keyword: Keyword,
10411    ) -> Result<Option<Vec<SqlOption>>, ParserError> {
10412        if let Token::Word(word) = &self.peek_token_ref().token {
10413            if word.keyword == keyword {
10414                return Ok(Some(self.parse_options(keyword)?));
10415            }
10416        };
10417        Ok(None)
10418    }
10419
10420    /// Parse a parenthesized list of `SqlOption`s following `keyword`, or return an empty vec.
10421    pub fn parse_options(&mut self, keyword: Keyword) -> Result<Vec<SqlOption>, ParserError> {
10422        if self.parse_keyword(keyword) {
10423            self.expect_token(&Token::LParen)?;
10424            let options = self.parse_comma_separated0(Parser::parse_sql_option, Token::RParen)?;
10425            self.expect_token(&Token::RParen)?;
10426            Ok(options)
10427        } else {
10428            Ok(vec![])
10429        }
10430    }
10431
10432    /// Parse options introduced by one of `keywords` followed by a parenthesized list.
10433    pub fn parse_options_with_keywords(
10434        &mut self,
10435        keywords: &[Keyword],
10436    ) -> Result<Vec<SqlOption>, ParserError> {
10437        if self.parse_keywords(keywords) {
10438            self.expect_token(&Token::LParen)?;
10439            let options = self.parse_comma_separated(Parser::parse_sql_option)?;
10440            self.expect_token(&Token::RParen)?;
10441            Ok(options)
10442        } else {
10443            Ok(vec![])
10444        }
10445    }
10446
10447    /// Parse an index type token (e.g. `BTREE`, `HASH`, or a custom identifier).
10448    pub fn parse_index_type(&mut self) -> Result<IndexType, ParserError> {
10449        Ok(if self.parse_keyword(Keyword::BTREE) {
10450            IndexType::BTree
10451        } else if self.parse_keyword(Keyword::HASH) {
10452            IndexType::Hash
10453        } else if self.parse_keyword(Keyword::GIN) {
10454            IndexType::GIN
10455        } else if self.parse_keyword(Keyword::GIST) {
10456            IndexType::GiST
10457        } else if self.parse_keyword(Keyword::SPGIST) {
10458            IndexType::SPGiST
10459        } else if self.parse_keyword(Keyword::BRIN) {
10460            IndexType::BRIN
10461        } else if self.parse_keyword(Keyword::BLOOM) {
10462            IndexType::Bloom
10463        } else {
10464            IndexType::Custom(self.parse_identifier()?)
10465        })
10466    }
10467
10468    /// Optionally parse the `USING` keyword, followed by an [IndexType]
10469    /// Example:
10470    /// ```sql
10471    //// USING BTREE (name, age DESC)
10472    /// ```
10473    /// Optionally parse `USING <index_type>` and return the parsed `IndexType` if present.
10474    pub fn parse_optional_using_then_index_type(
10475        &mut self,
10476    ) -> Result<Option<IndexType>, ParserError> {
10477        if self.parse_keyword(Keyword::USING) {
10478            Ok(Some(self.parse_index_type()?))
10479        } else {
10480            Ok(None)
10481        }
10482    }
10483
10484    /// Parse `[ident]`, mostly `ident` is name, like:
10485    /// `window_name`, `index_name`, ...
10486    /// Parse an optional identifier, returning `Some(Ident)` if present.
10487    pub fn parse_optional_ident(&mut self) -> Result<Option<Ident>, ParserError> {
10488        self.maybe_parse(|parser| parser.parse_identifier())
10489    }
10490
10491    #[must_use]
10492    /// Parse optional `KEY` or `INDEX` display tokens used in index/constraint declarations.
10493    pub fn parse_index_type_display(&mut self) -> KeyOrIndexDisplay {
10494        if self.parse_keyword(Keyword::KEY) {
10495            KeyOrIndexDisplay::Key
10496        } else if self.parse_keyword(Keyword::INDEX) {
10497            KeyOrIndexDisplay::Index
10498        } else {
10499            KeyOrIndexDisplay::None
10500        }
10501    }
10502
10503    /// Parse an optional index option such as `USING <type>` or `COMMENT <string>`.
10504    pub fn parse_optional_index_option(&mut self) -> Result<Option<IndexOption>, ParserError> {
10505        if let Some(index_type) = self.parse_optional_using_then_index_type()? {
10506            Ok(Some(IndexOption::Using(index_type)))
10507        } else if self.parse_keyword(Keyword::COMMENT) {
10508            let s = self.parse_literal_string()?;
10509            Ok(Some(IndexOption::Comment(s)))
10510        } else if self.parse_keywords(&[Keyword::WITH, Keyword::PARSER]) {
10511            // MySQL: `WITH PARSER parser_name` (used by FULLTEXT indexes, e.g. ngram).
10512            let name = self.parse_identifier()?;
10513            Ok(Some(IndexOption::WithParser(name)))
10514        } else if self.parse_keyword(Keyword::VISIBLE) {
10515            Ok(Some(IndexOption::Visible))
10516        } else if self.parse_keyword(Keyword::INVISIBLE) {
10517            Ok(Some(IndexOption::Invisible))
10518        } else {
10519            Ok(None)
10520        }
10521    }
10522
10523    /// Parse zero or more index options and return them as a vector.
10524    pub fn parse_index_options(&mut self) -> Result<Vec<IndexOption>, ParserError> {
10525        let mut options = Vec::new();
10526
10527        loop {
10528            match self.parse_optional_index_option()? {
10529                Some(index_option) => options.push(index_option),
10530                None => return Ok(options),
10531            }
10532        }
10533    }
10534
10535    /// Parse a single `SqlOption` used by various dialect-specific DDL statements.
10536    pub fn parse_sql_option(&mut self) -> Result<SqlOption, ParserError> {
10537        let is_mssql = dialect_of!(self is MsSqlDialect|GenericDialect);
10538
10539        match &self.peek_token_ref().token {
10540            Token::Word(w) if w.keyword == Keyword::HEAP && is_mssql => {
10541                Ok(SqlOption::Ident(self.parse_identifier()?))
10542            }
10543            Token::Word(w) if w.keyword == Keyword::PARTITION && is_mssql => {
10544                self.parse_option_partition()
10545            }
10546            Token::Word(w) if w.keyword == Keyword::CLUSTERED && is_mssql => {
10547                self.parse_option_clustered()
10548            }
10549            _ => {
10550                let name = self.parse_identifier()?;
10551                self.expect_token(&Token::Eq)?;
10552                let value = self.parse_expr()?;
10553
10554                Ok(SqlOption::KeyValue { key: name, value })
10555            }
10556        }
10557    }
10558
10559    /// Parse a `CLUSTERED` table option (MSSQL-specific syntaxes supported).
10560    pub fn parse_option_clustered(&mut self) -> Result<SqlOption, ParserError> {
10561        if self.parse_keywords(&[
10562            Keyword::CLUSTERED,
10563            Keyword::COLUMNSTORE,
10564            Keyword::INDEX,
10565            Keyword::ORDER,
10566        ]) {
10567            Ok(SqlOption::Clustered(
10568                TableOptionsClustered::ColumnstoreIndexOrder(
10569                    self.parse_parenthesized_column_list(IsOptional::Mandatory, false)?,
10570                ),
10571            ))
10572        } else if self.parse_keywords(&[Keyword::CLUSTERED, Keyword::COLUMNSTORE, Keyword::INDEX]) {
10573            Ok(SqlOption::Clustered(
10574                TableOptionsClustered::ColumnstoreIndex,
10575            ))
10576        } else if self.parse_keywords(&[Keyword::CLUSTERED, Keyword::INDEX]) {
10577            self.expect_token(&Token::LParen)?;
10578
10579            let columns = self.parse_comma_separated(|p| {
10580                let name = p.parse_identifier()?;
10581                let asc = p.parse_asc_desc();
10582
10583                Ok(ClusteredIndex { name, asc })
10584            })?;
10585
10586            self.expect_token(&Token::RParen)?;
10587
10588            Ok(SqlOption::Clustered(TableOptionsClustered::Index(columns)))
10589        } else {
10590            Err(ParserError::ParserError(
10591                "invalid CLUSTERED sequence".to_string(),
10592            ))
10593        }
10594    }
10595
10596    /// Parse a `PARTITION(...) FOR VALUES(...)` table option.
10597    pub fn parse_option_partition(&mut self) -> Result<SqlOption, ParserError> {
10598        self.expect_keyword_is(Keyword::PARTITION)?;
10599        self.expect_token(&Token::LParen)?;
10600        let column_name = self.parse_identifier()?;
10601
10602        self.expect_keyword_is(Keyword::RANGE)?;
10603        let range_direction = if self.parse_keyword(Keyword::LEFT) {
10604            Some(PartitionRangeDirection::Left)
10605        } else if self.parse_keyword(Keyword::RIGHT) {
10606            Some(PartitionRangeDirection::Right)
10607        } else {
10608            None
10609        };
10610
10611        self.expect_keywords(&[Keyword::FOR, Keyword::VALUES])?;
10612        self.expect_token(&Token::LParen)?;
10613
10614        let for_values = self.parse_comma_separated(Parser::parse_expr)?;
10615
10616        self.expect_token(&Token::RParen)?;
10617        self.expect_token(&Token::RParen)?;
10618
10619        Ok(SqlOption::Partition {
10620            column_name,
10621            range_direction,
10622            for_values,
10623        })
10624    }
10625
10626    /// Parse a parenthesized list of partition expressions and return a `Partition` value.
10627    pub fn parse_partition(&mut self) -> Result<Partition, ParserError> {
10628        self.expect_token(&Token::LParen)?;
10629        let partitions = self.parse_comma_separated(Parser::parse_expr)?;
10630        self.expect_token(&Token::RParen)?;
10631        Ok(Partition::Partitions(partitions))
10632    }
10633
10634    /// Parse a parenthesized `SELECT` projection used for projection-based operations.
10635    pub fn parse_projection_select(&mut self) -> Result<ProjectionSelect, ParserError> {
10636        self.expect_token(&Token::LParen)?;
10637        self.expect_keyword_is(Keyword::SELECT)?;
10638        let projection = self.parse_projection()?;
10639        let group_by = self.parse_optional_group_by()?;
10640        let order_by = self.parse_optional_order_by()?;
10641        self.expect_token(&Token::RParen)?;
10642        Ok(ProjectionSelect {
10643            projection,
10644            group_by,
10645            order_by,
10646        })
10647    }
10648    /// Parse `ALTER TABLE ... ADD PROJECTION ...` operation.
10649    pub fn parse_alter_table_add_projection(&mut self) -> Result<AlterTableOperation, ParserError> {
10650        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
10651        let name = self.parse_identifier()?;
10652        let query = self.parse_projection_select()?;
10653        Ok(AlterTableOperation::AddProjection {
10654            if_not_exists,
10655            name,
10656            select: query,
10657        })
10658    }
10659
10660    /// Parse Redshift `ALTER SORTKEY (column_list)`.
10661    ///
10662    /// See <https://docs.aws.amazon.com/redshift/latest/dg/r_ALTER_TABLE.html>
10663    fn parse_alter_sort_key(&mut self) -> Result<AlterTableOperation, ParserError> {
10664        self.expect_keyword_is(Keyword::ALTER)?;
10665        self.expect_keyword_is(Keyword::SORTKEY)?;
10666        self.expect_token(&Token::LParen)?;
10667        let columns = self.parse_comma_separated(|p| p.parse_expr())?;
10668        self.expect_token(&Token::RParen)?;
10669        Ok(AlterTableOperation::AlterSortKey { columns })
10670    }
10671
10672    /// Parse a single `ALTER TABLE` operation and return an `AlterTableOperation`.
10673    pub fn parse_alter_table_operation(&mut self) -> Result<AlterTableOperation, ParserError> {
10674        let operation = if self.parse_keyword(Keyword::ADD) {
10675            if let Some(constraint) = self.parse_optional_table_constraint()? {
10676                let not_valid = self.parse_keywords(&[Keyword::NOT, Keyword::VALID]);
10677                AlterTableOperation::AddConstraint {
10678                    constraint,
10679                    not_valid,
10680                }
10681            } else if dialect_of!(self is ClickHouseDialect|GenericDialect)
10682                && self.parse_keyword(Keyword::PROJECTION)
10683            {
10684                return self.parse_alter_table_add_projection();
10685            } else {
10686                let if_not_exists =
10687                    self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
10688                let mut new_partitions = vec![];
10689                loop {
10690                    if self.parse_keyword(Keyword::PARTITION) {
10691                        new_partitions.push(self.parse_partition()?);
10692                    } else {
10693                        break;
10694                    }
10695                }
10696                if !new_partitions.is_empty() {
10697                    AlterTableOperation::AddPartitions {
10698                        if_not_exists,
10699                        new_partitions,
10700                    }
10701                } else {
10702                    let column_keyword = self.parse_keyword(Keyword::COLUMN);
10703
10704                    let if_not_exists = if dialect_of!(self is PostgreSqlDialect | BigQueryDialect | DuckDbDialect | GenericDialect)
10705                    {
10706                        self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS])
10707                            || if_not_exists
10708                    } else {
10709                        false
10710                    };
10711
10712                    let column_def = self.parse_column_def()?;
10713
10714                    let column_position = self.parse_column_position()?;
10715
10716                    AlterTableOperation::AddColumn {
10717                        column_keyword,
10718                        if_not_exists,
10719                        column_def,
10720                        column_position,
10721                    }
10722                }
10723            }
10724        } else if self.parse_keyword(Keyword::RENAME) {
10725            if dialect_of!(self is PostgreSqlDialect) && self.parse_keyword(Keyword::CONSTRAINT) {
10726                let old_name = self.parse_identifier()?;
10727                self.expect_keyword_is(Keyword::TO)?;
10728                let new_name = self.parse_identifier()?;
10729                AlterTableOperation::RenameConstraint { old_name, new_name }
10730            } else if self.parse_keyword(Keyword::TO) {
10731                let table_name = self.parse_object_name(false)?;
10732                AlterTableOperation::RenameTable {
10733                    table_name: RenameTableNameKind::To(table_name),
10734                }
10735            } else if self.parse_keyword(Keyword::AS) {
10736                let table_name = self.parse_object_name(false)?;
10737                AlterTableOperation::RenameTable {
10738                    table_name: RenameTableNameKind::As(table_name),
10739                }
10740            } else {
10741                let _ = self.parse_keyword(Keyword::COLUMN); // [ COLUMN ]
10742                let old_column_name = self.parse_identifier()?;
10743                self.expect_keyword_is(Keyword::TO)?;
10744                let new_column_name = self.parse_identifier()?;
10745                AlterTableOperation::RenameColumn {
10746                    old_column_name,
10747                    new_column_name,
10748                }
10749            }
10750        } else if self.parse_keyword(Keyword::DISABLE) {
10751            if self.parse_keywords(&[Keyword::ROW, Keyword::LEVEL, Keyword::SECURITY]) {
10752                AlterTableOperation::DisableRowLevelSecurity {}
10753            } else if self.parse_keyword(Keyword::RULE) {
10754                let name = self.parse_identifier()?;
10755                AlterTableOperation::DisableRule { name }
10756            } else if self.parse_keyword(Keyword::TRIGGER) {
10757                let name = self.parse_identifier()?;
10758                AlterTableOperation::DisableTrigger { name }
10759            } else {
10760                return self.expected_ref(
10761                    "ROW LEVEL SECURITY, RULE, or TRIGGER after DISABLE",
10762                    self.peek_token_ref(),
10763                );
10764            }
10765        } else if self.parse_keyword(Keyword::ENABLE) {
10766            if self.parse_keywords(&[Keyword::ALWAYS, Keyword::RULE]) {
10767                let name = self.parse_identifier()?;
10768                AlterTableOperation::EnableAlwaysRule { name }
10769            } else if self.parse_keywords(&[Keyword::ALWAYS, Keyword::TRIGGER]) {
10770                let name = self.parse_identifier()?;
10771                AlterTableOperation::EnableAlwaysTrigger { name }
10772            } else if self.parse_keywords(&[Keyword::ROW, Keyword::LEVEL, Keyword::SECURITY]) {
10773                AlterTableOperation::EnableRowLevelSecurity {}
10774            } else if self.parse_keywords(&[Keyword::REPLICA, Keyword::RULE]) {
10775                let name = self.parse_identifier()?;
10776                AlterTableOperation::EnableReplicaRule { name }
10777            } else if self.parse_keywords(&[Keyword::REPLICA, Keyword::TRIGGER]) {
10778                let name = self.parse_identifier()?;
10779                AlterTableOperation::EnableReplicaTrigger { name }
10780            } else if self.parse_keyword(Keyword::RULE) {
10781                let name = self.parse_identifier()?;
10782                AlterTableOperation::EnableRule { name }
10783            } else if self.parse_keyword(Keyword::TRIGGER) {
10784                let name = self.parse_identifier()?;
10785                AlterTableOperation::EnableTrigger { name }
10786            } else {
10787                return self.expected_ref(
10788                    "ALWAYS, REPLICA, ROW LEVEL SECURITY, RULE, or TRIGGER after ENABLE",
10789                    self.peek_token_ref(),
10790                );
10791            }
10792        } else if self.parse_keywords(&[
10793            Keyword::FORCE,
10794            Keyword::ROW,
10795            Keyword::LEVEL,
10796            Keyword::SECURITY,
10797        ]) {
10798            AlterTableOperation::ForceRowLevelSecurity
10799        } else if self.parse_keywords(&[
10800            Keyword::NO,
10801            Keyword::FORCE,
10802            Keyword::ROW,
10803            Keyword::LEVEL,
10804            Keyword::SECURITY,
10805        ]) {
10806            AlterTableOperation::NoForceRowLevelSecurity
10807        } else if self.parse_keywords(&[Keyword::CLEAR, Keyword::PROJECTION])
10808            && dialect_of!(self is ClickHouseDialect|GenericDialect)
10809        {
10810            let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
10811            let name = self.parse_identifier()?;
10812            let partition = if self.parse_keywords(&[Keyword::IN, Keyword::PARTITION]) {
10813                Some(self.parse_identifier()?)
10814            } else {
10815                None
10816            };
10817            AlterTableOperation::ClearProjection {
10818                if_exists,
10819                name,
10820                partition,
10821            }
10822        } else if self.parse_keywords(&[Keyword::MATERIALIZE, Keyword::PROJECTION])
10823            && dialect_of!(self is ClickHouseDialect|GenericDialect)
10824        {
10825            let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
10826            let name = self.parse_identifier()?;
10827            let partition = if self.parse_keywords(&[Keyword::IN, Keyword::PARTITION]) {
10828                Some(self.parse_identifier()?)
10829            } else {
10830                None
10831            };
10832            AlterTableOperation::MaterializeProjection {
10833                if_exists,
10834                name,
10835                partition,
10836            }
10837        } else if self.parse_keyword(Keyword::DROP) {
10838            if self.parse_keywords(&[Keyword::IF, Keyword::EXISTS, Keyword::PARTITION]) {
10839                self.expect_token(&Token::LParen)?;
10840                let partitions = self.parse_comma_separated(Parser::parse_expr)?;
10841                self.expect_token(&Token::RParen)?;
10842                AlterTableOperation::DropPartitions {
10843                    partitions,
10844                    if_exists: true,
10845                }
10846            } else if self.parse_keyword(Keyword::PARTITION) {
10847                self.expect_token(&Token::LParen)?;
10848                let partitions = self.parse_comma_separated(Parser::parse_expr)?;
10849                self.expect_token(&Token::RParen)?;
10850                AlterTableOperation::DropPartitions {
10851                    partitions,
10852                    if_exists: false,
10853                }
10854            } else if self.parse_keyword(Keyword::CONSTRAINT) {
10855                let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
10856                let name = self.parse_identifier()?;
10857                let drop_behavior = self.parse_optional_drop_behavior();
10858                AlterTableOperation::DropConstraint {
10859                    if_exists,
10860                    name,
10861                    drop_behavior,
10862                }
10863            } else if self.parse_keywords(&[Keyword::PRIMARY, Keyword::KEY]) {
10864                let drop_behavior = self.parse_optional_drop_behavior();
10865                AlterTableOperation::DropPrimaryKey { drop_behavior }
10866            } else if self.parse_keywords(&[Keyword::FOREIGN, Keyword::KEY]) {
10867                let name = self.parse_identifier()?;
10868                let drop_behavior = self.parse_optional_drop_behavior();
10869                AlterTableOperation::DropForeignKey {
10870                    name,
10871                    drop_behavior,
10872                }
10873            } else if self.parse_keyword(Keyword::INDEX) {
10874                let name = self.parse_identifier()?;
10875                AlterTableOperation::DropIndex { name }
10876            } else if self.parse_keyword(Keyword::PROJECTION)
10877                && dialect_of!(self is ClickHouseDialect|GenericDialect)
10878            {
10879                let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
10880                let name = self.parse_identifier()?;
10881                AlterTableOperation::DropProjection { if_exists, name }
10882            } else if self.parse_keywords(&[Keyword::CLUSTERING, Keyword::KEY]) {
10883                AlterTableOperation::DropClusteringKey
10884            } else {
10885                let has_column_keyword = self.parse_keyword(Keyword::COLUMN); // [ COLUMN ]
10886                let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
10887                let column_names = if self.dialect.supports_comma_separated_drop_column_list() {
10888                    self.parse_comma_separated(Parser::parse_identifier)?
10889                } else {
10890                    vec![self.parse_identifier()?]
10891                };
10892                let drop_behavior = self.parse_optional_drop_behavior();
10893                AlterTableOperation::DropColumn {
10894                    has_column_keyword,
10895                    column_names,
10896                    if_exists,
10897                    drop_behavior,
10898                }
10899            }
10900        } else if self.parse_keyword(Keyword::PARTITION) {
10901            self.expect_token(&Token::LParen)?;
10902            let before = self.parse_comma_separated(Parser::parse_expr)?;
10903            self.expect_token(&Token::RParen)?;
10904            self.expect_keyword_is(Keyword::RENAME)?;
10905            self.expect_keywords(&[Keyword::TO, Keyword::PARTITION])?;
10906            self.expect_token(&Token::LParen)?;
10907            let renames = self.parse_comma_separated(Parser::parse_expr)?;
10908            self.expect_token(&Token::RParen)?;
10909            AlterTableOperation::RenamePartitions {
10910                old_partitions: before,
10911                new_partitions: renames,
10912            }
10913        } else if self.parse_keyword(Keyword::CHANGE) {
10914            let _ = self.parse_keyword(Keyword::COLUMN); // [ COLUMN ]
10915            let old_name = self.parse_identifier()?;
10916            let new_name = self.parse_identifier()?;
10917            let data_type = self.parse_data_type()?;
10918            let mut options = vec![];
10919            while let Some(option) = self.parse_optional_column_option()? {
10920                options.push(option);
10921            }
10922
10923            let column_position = self.parse_column_position()?;
10924
10925            AlterTableOperation::ChangeColumn {
10926                old_name,
10927                new_name,
10928                data_type,
10929                options,
10930                column_position,
10931            }
10932        } else if self.parse_keyword(Keyword::MODIFY) {
10933            let _ = self.parse_keyword(Keyword::COLUMN); // [ COLUMN ]
10934            let col_name = self.parse_identifier()?;
10935            let data_type = self.parse_data_type()?;
10936            let mut options = vec![];
10937            while let Some(option) = self.parse_optional_column_option()? {
10938                options.push(option);
10939            }
10940
10941            let column_position = self.parse_column_position()?;
10942
10943            AlterTableOperation::ModifyColumn {
10944                col_name,
10945                data_type,
10946                options,
10947                column_position,
10948            }
10949        } else if self.parse_keyword(Keyword::ALTER) {
10950            if self.peek_keyword(Keyword::SORTKEY) {
10951                self.prev_token();
10952                return self.parse_alter_sort_key();
10953            }
10954
10955            let _ = self.parse_keyword(Keyword::COLUMN); // [ COLUMN ]
10956            let column_name = self.parse_identifier()?;
10957            let is_postgresql = dialect_of!(self is PostgreSqlDialect);
10958
10959            let op: AlterColumnOperation = if self.parse_keywords(&[
10960                Keyword::SET,
10961                Keyword::NOT,
10962                Keyword::NULL,
10963            ]) {
10964                AlterColumnOperation::SetNotNull {}
10965            } else if self.parse_keywords(&[Keyword::DROP, Keyword::NOT, Keyword::NULL]) {
10966                AlterColumnOperation::DropNotNull {}
10967            } else if self.parse_keywords(&[Keyword::SET, Keyword::DEFAULT]) {
10968                AlterColumnOperation::SetDefault {
10969                    value: self.parse_expr()?,
10970                }
10971            } else if self.parse_keywords(&[Keyword::DROP, Keyword::DEFAULT]) {
10972                AlterColumnOperation::DropDefault {}
10973            } else if self.parse_keywords(&[Keyword::SET, Keyword::DATA, Keyword::TYPE]) {
10974                self.parse_set_data_type(true)?
10975            } else if self.parse_keyword(Keyword::TYPE) {
10976                self.parse_set_data_type(false)?
10977            } else if self.parse_keywords(&[Keyword::ADD, Keyword::GENERATED]) {
10978                let generated_as = if self.parse_keyword(Keyword::ALWAYS) {
10979                    Some(GeneratedAs::Always)
10980                } else if self.parse_keywords(&[Keyword::BY, Keyword::DEFAULT]) {
10981                    Some(GeneratedAs::ByDefault)
10982                } else {
10983                    None
10984                };
10985
10986                self.expect_keywords(&[Keyword::AS, Keyword::IDENTITY])?;
10987
10988                let mut sequence_options: Option<Vec<SequenceOptions>> = None;
10989
10990                if self.peek_token_ref().token == Token::LParen {
10991                    self.expect_token(&Token::LParen)?;
10992                    sequence_options = Some(self.parse_create_sequence_options()?);
10993                    self.expect_token(&Token::RParen)?;
10994                }
10995
10996                AlterColumnOperation::AddGenerated {
10997                    generated_as,
10998                    sequence_options,
10999                }
11000            } else {
11001                let message = if is_postgresql {
11002                    "SET/DROP NOT NULL, SET DEFAULT, SET DATA TYPE, or ADD GENERATED after ALTER COLUMN"
11003                } else {
11004                    "SET/DROP NOT NULL, SET DEFAULT, or SET DATA TYPE after ALTER COLUMN"
11005                };
11006
11007                return self.expected_ref(message, self.peek_token_ref());
11008            };
11009            AlterTableOperation::AlterColumn { column_name, op }
11010        } else if self.parse_keyword(Keyword::SWAP) {
11011            self.expect_keyword_is(Keyword::WITH)?;
11012            let table_name = self.parse_object_name(false)?;
11013            AlterTableOperation::SwapWith { table_name }
11014        } else if dialect_of!(self is PostgreSqlDialect | GenericDialect)
11015            && self.parse_keywords(&[Keyword::OWNER, Keyword::TO])
11016        {
11017            let new_owner = self.parse_owner()?;
11018            AlterTableOperation::OwnerTo { new_owner }
11019        } else if dialect_of!(self is ClickHouseDialect|GenericDialect)
11020            && self.parse_keyword(Keyword::ATTACH)
11021        {
11022            AlterTableOperation::AttachPartition {
11023                partition: self.parse_part_or_partition()?,
11024            }
11025        } else if dialect_of!(self is ClickHouseDialect|GenericDialect)
11026            && self.parse_keyword(Keyword::DETACH)
11027        {
11028            AlterTableOperation::DetachPartition {
11029                partition: self.parse_part_or_partition()?,
11030            }
11031        } else if dialect_of!(self is ClickHouseDialect|GenericDialect)
11032            && self.parse_keyword(Keyword::FREEZE)
11033        {
11034            let partition = self.parse_part_or_partition()?;
11035            let with_name = if self.parse_keyword(Keyword::WITH) {
11036                self.expect_keyword_is(Keyword::NAME)?;
11037                Some(self.parse_identifier()?)
11038            } else {
11039                None
11040            };
11041            AlterTableOperation::FreezePartition {
11042                partition,
11043                with_name,
11044            }
11045        } else if dialect_of!(self is ClickHouseDialect|GenericDialect)
11046            && self.parse_keyword(Keyword::UNFREEZE)
11047        {
11048            let partition = self.parse_part_or_partition()?;
11049            let with_name = if self.parse_keyword(Keyword::WITH) {
11050                self.expect_keyword_is(Keyword::NAME)?;
11051                Some(self.parse_identifier()?)
11052            } else {
11053                None
11054            };
11055            AlterTableOperation::UnfreezePartition {
11056                partition,
11057                with_name,
11058            }
11059        } else if self.parse_keywords(&[Keyword::CLUSTER, Keyword::BY]) {
11060            self.expect_token(&Token::LParen)?;
11061            let exprs = self.parse_comma_separated(|parser| parser.parse_expr())?;
11062            self.expect_token(&Token::RParen)?;
11063            AlterTableOperation::ClusterBy { exprs }
11064        } else if self.parse_keywords(&[Keyword::SUSPEND, Keyword::RECLUSTER]) {
11065            AlterTableOperation::SuspendRecluster
11066        } else if self.parse_keywords(&[Keyword::RESUME, Keyword::RECLUSTER]) {
11067            AlterTableOperation::ResumeRecluster
11068        } else if self.parse_keyword(Keyword::LOCK) {
11069            let equals = self.consume_token(&Token::Eq);
11070            let lock = match self.parse_one_of_keywords(&[
11071                Keyword::DEFAULT,
11072                Keyword::EXCLUSIVE,
11073                Keyword::NONE,
11074                Keyword::SHARED,
11075            ]) {
11076                Some(Keyword::DEFAULT) => AlterTableLock::Default,
11077                Some(Keyword::EXCLUSIVE) => AlterTableLock::Exclusive,
11078                Some(Keyword::NONE) => AlterTableLock::None,
11079                Some(Keyword::SHARED) => AlterTableLock::Shared,
11080                _ => self.expected_ref(
11081                    "DEFAULT, EXCLUSIVE, NONE or SHARED after LOCK [=]",
11082                    self.peek_token_ref(),
11083                )?,
11084            };
11085            AlterTableOperation::Lock { equals, lock }
11086        } else if self.parse_keyword(Keyword::ALGORITHM) {
11087            let equals = self.consume_token(&Token::Eq);
11088            let algorithm = match self.parse_one_of_keywords(&[
11089                Keyword::DEFAULT,
11090                Keyword::INSTANT,
11091                Keyword::INPLACE,
11092                Keyword::COPY,
11093            ]) {
11094                Some(Keyword::DEFAULT) => AlterTableAlgorithm::Default,
11095                Some(Keyword::INSTANT) => AlterTableAlgorithm::Instant,
11096                Some(Keyword::INPLACE) => AlterTableAlgorithm::Inplace,
11097                Some(Keyword::COPY) => AlterTableAlgorithm::Copy,
11098                _ => self.expected_ref(
11099                    "DEFAULT, INSTANT, INPLACE, or COPY after ALGORITHM [=]",
11100                    self.peek_token_ref(),
11101                )?,
11102            };
11103            AlterTableOperation::Algorithm { equals, algorithm }
11104        } else if self.parse_keyword(Keyword::AUTO_INCREMENT) {
11105            let equals = self.consume_token(&Token::Eq);
11106            let value = self.parse_number_value()?;
11107            AlterTableOperation::AutoIncrement { equals, value }
11108        } else if self.parse_keywords(&[Keyword::REPLICA, Keyword::IDENTITY]) {
11109            let identity = if self.parse_keyword(Keyword::NOTHING) {
11110                ReplicaIdentity::Nothing
11111            } else if self.parse_keyword(Keyword::FULL) {
11112                ReplicaIdentity::Full
11113            } else if self.parse_keyword(Keyword::DEFAULT) {
11114                ReplicaIdentity::Default
11115            } else if self.parse_keywords(&[Keyword::USING, Keyword::INDEX]) {
11116                ReplicaIdentity::Index(self.parse_identifier()?)
11117            } else {
11118                return self.expected_ref(
11119                    "NOTHING, FULL, DEFAULT, or USING INDEX index_name after REPLICA IDENTITY",
11120                    self.peek_token_ref(),
11121                );
11122            };
11123
11124            AlterTableOperation::ReplicaIdentity { identity }
11125        } else if self.parse_keywords(&[Keyword::VALIDATE, Keyword::CONSTRAINT]) {
11126            let name = self.parse_identifier()?;
11127            AlterTableOperation::ValidateConstraint { name }
11128        } else if self.parse_keywords(&[Keyword::SET, Keyword::LOGGED]) {
11129            AlterTableOperation::SetLogged
11130        } else if self.parse_keywords(&[Keyword::SET, Keyword::UNLOGGED]) {
11131            AlterTableOperation::SetUnlogged
11132        } else {
11133            let mut options =
11134                self.parse_options_with_keywords(&[Keyword::SET, Keyword::TBLPROPERTIES])?;
11135            if !options.is_empty() {
11136                AlterTableOperation::SetTblProperties {
11137                    table_properties: options,
11138                }
11139            } else {
11140                options = self.parse_options(Keyword::SET)?;
11141                if !options.is_empty() {
11142                    AlterTableOperation::SetOptionsParens { options }
11143                } else {
11144                    return self.expected_ref(
11145                    "ADD, RENAME, PARTITION, SWAP, DROP, REPLICA IDENTITY, SET, or SET TBLPROPERTIES after ALTER TABLE",
11146                    self.peek_token_ref(),
11147                  );
11148                }
11149            }
11150        };
11151        Ok(operation)
11152    }
11153
11154    fn parse_set_data_type(&mut self, had_set: bool) -> Result<AlterColumnOperation, ParserError> {
11155        let data_type = self.parse_data_type()?;
11156        let using = if self.dialect.supports_alter_column_type_using()
11157            && self.parse_keyword(Keyword::USING)
11158        {
11159            Some(self.parse_expr()?)
11160        } else {
11161            None
11162        };
11163        Ok(AlterColumnOperation::SetDataType {
11164            data_type,
11165            using,
11166            had_set,
11167        })
11168    }
11169
11170    fn parse_part_or_partition(&mut self) -> Result<Partition, ParserError> {
11171        let keyword = self.expect_one_of_keywords(&[Keyword::PART, Keyword::PARTITION])?;
11172        match keyword {
11173            Keyword::PART => Ok(Partition::Part(self.parse_expr()?)),
11174            Keyword::PARTITION => Ok(Partition::Expr(self.parse_expr()?)),
11175            // unreachable because expect_one_of_keywords used above
11176            unexpected_keyword => Err(ParserError::ParserError(
11177                format!("Internal parser error: expected any of {{PART, PARTITION}}, got {unexpected_keyword:?}"),
11178            )),
11179        }
11180    }
11181
11182    /// Parse an `ALTER <object>` statement and dispatch to the appropriate alter handler.
11183    pub fn parse_alter(&mut self) -> Result<Statement, ParserError> {
11184        if self.peek_keywords(&[Keyword::TEXT, Keyword::SEARCH]) {
11185            return self.parse_alter_text_search().map(Into::into);
11186        }
11187
11188        let object_type = self.expect_one_of_keywords(&[
11189            Keyword::VIEW,
11190            Keyword::TYPE,
11191            Keyword::COLLATION,
11192            Keyword::TABLE,
11193            Keyword::INDEX,
11194            Keyword::FUNCTION,
11195            Keyword::AGGREGATE,
11196            Keyword::ROLE,
11197            Keyword::POLICY,
11198            Keyword::CONNECTOR,
11199            Keyword::ICEBERG,
11200            Keyword::SCHEMA,
11201            Keyword::USER,
11202            Keyword::OPERATOR,
11203        ])?;
11204        match object_type {
11205            Keyword::SCHEMA => {
11206                self.prev_token();
11207                self.prev_token();
11208                self.parse_alter_schema()
11209            }
11210            Keyword::VIEW => self.parse_alter_view(),
11211            Keyword::TYPE => self.parse_alter_type(),
11212            Keyword::COLLATION => self.parse_alter_collation().map(Into::into),
11213            Keyword::TABLE => self.parse_alter_table(false),
11214            Keyword::ICEBERG => {
11215                self.expect_keyword(Keyword::TABLE)?;
11216                self.parse_alter_table(true)
11217            }
11218            Keyword::INDEX => {
11219                let index_name = self.parse_object_name(false)?;
11220                let operation = if self.parse_keyword(Keyword::RENAME) {
11221                    if self.parse_keyword(Keyword::TO) {
11222                        let index_name = self.parse_object_name(false)?;
11223                        AlterIndexOperation::RenameIndex { index_name }
11224                    } else {
11225                        return self.expected_ref("TO after RENAME", self.peek_token_ref());
11226                    }
11227                } else {
11228                    return self.expected_ref("RENAME after ALTER INDEX", self.peek_token_ref());
11229                };
11230
11231                Ok(Statement::AlterIndex {
11232                    name: index_name,
11233                    operation,
11234                })
11235            }
11236            Keyword::FUNCTION => self.parse_alter_function(AlterFunctionKind::Function),
11237            Keyword::AGGREGATE => self.parse_alter_function(AlterFunctionKind::Aggregate),
11238            Keyword::OPERATOR => {
11239                if self.parse_keyword(Keyword::FAMILY) {
11240                    self.parse_alter_operator_family().map(Into::into)
11241                } else if self.parse_keyword(Keyword::CLASS) {
11242                    self.parse_alter_operator_class().map(Into::into)
11243                } else {
11244                    self.parse_alter_operator().map(Into::into)
11245                }
11246            }
11247            Keyword::ROLE => self.parse_alter_role(),
11248            Keyword::POLICY => self.parse_alter_policy().map(Into::into),
11249            Keyword::CONNECTOR => self.parse_alter_connector(),
11250            Keyword::USER if self.dialect.supports_alter_user_as_alter_role() => {
11251                self.parse_alter_role()
11252            }
11253            Keyword::USER => self.parse_alter_user().map(Into::into),
11254            // unreachable because expect_one_of_keywords used above
11255            unexpected_keyword => Err(ParserError::ParserError(
11256                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:?}"),
11257            )),
11258        }
11259    }
11260
11261    fn parse_alter_aggregate_signature(
11262        &mut self,
11263    ) -> Result<(FunctionDesc, bool, Option<Vec<OperateFunctionArg>>), ParserError> {
11264        let name = self.parse_object_name(false)?;
11265        self.expect_token(&Token::LParen)?;
11266
11267        if self.consume_token(&Token::Mul) {
11268            self.expect_token(&Token::RParen)?;
11269            return Ok((
11270                FunctionDesc {
11271                    name,
11272                    args: Some(vec![]),
11273                },
11274                true,
11275                None,
11276            ));
11277        }
11278
11279        let args =
11280            if self.peek_keyword(Keyword::ORDER) || self.peek_token_ref().token == Token::RParen {
11281                vec![]
11282            } else {
11283                self.parse_comma_separated(Parser::parse_aggregate_function_arg)?
11284            };
11285
11286        let aggregate_order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
11287            Some(self.parse_comma_separated(Parser::parse_aggregate_function_arg)?)
11288        } else {
11289            None
11290        };
11291
11292        self.expect_token(&Token::RParen)?;
11293        Ok((
11294            FunctionDesc {
11295                name,
11296                args: Some(args),
11297            },
11298            false,
11299            aggregate_order_by,
11300        ))
11301    }
11302
11303    fn parse_alter_function_action(&mut self) -> Result<Option<AlterFunctionAction>, ParserError> {
11304        let action = if self.parse_keywords(&[
11305            Keyword::CALLED,
11306            Keyword::ON,
11307            Keyword::NULL,
11308            Keyword::INPUT,
11309        ]) {
11310            Some(AlterFunctionAction::CalledOnNull(
11311                FunctionCalledOnNull::CalledOnNullInput,
11312            ))
11313        } else if self.parse_keywords(&[
11314            Keyword::RETURNS,
11315            Keyword::NULL,
11316            Keyword::ON,
11317            Keyword::NULL,
11318            Keyword::INPUT,
11319        ]) {
11320            Some(AlterFunctionAction::CalledOnNull(
11321                FunctionCalledOnNull::ReturnsNullOnNullInput,
11322            ))
11323        } else if self.parse_keyword(Keyword::STRICT) {
11324            Some(AlterFunctionAction::CalledOnNull(
11325                FunctionCalledOnNull::Strict,
11326            ))
11327        } else if self.parse_keyword(Keyword::IMMUTABLE) {
11328            Some(AlterFunctionAction::Behavior(FunctionBehavior::Immutable))
11329        } else if self.parse_keyword(Keyword::STABLE) {
11330            Some(AlterFunctionAction::Behavior(FunctionBehavior::Stable))
11331        } else if self.parse_keyword(Keyword::VOLATILE) {
11332            Some(AlterFunctionAction::Behavior(FunctionBehavior::Volatile))
11333        } else if self.parse_keyword(Keyword::NOT) {
11334            self.expect_keyword(Keyword::LEAKPROOF)?;
11335            Some(AlterFunctionAction::Leakproof(false))
11336        } else if self.parse_keyword(Keyword::LEAKPROOF) {
11337            Some(AlterFunctionAction::Leakproof(true))
11338        } else if self.parse_keyword(Keyword::EXTERNAL) {
11339            self.expect_keyword(Keyword::SECURITY)?;
11340            let security = if self.parse_keyword(Keyword::DEFINER) {
11341                FunctionSecurity::Definer
11342            } else if self.parse_keyword(Keyword::INVOKER) {
11343                FunctionSecurity::Invoker
11344            } else {
11345                return self.expected_ref("DEFINER or INVOKER", self.peek_token_ref());
11346            };
11347            Some(AlterFunctionAction::Security {
11348                external: true,
11349                security,
11350            })
11351        } else if self.parse_keyword(Keyword::SECURITY) {
11352            let security = if self.parse_keyword(Keyword::DEFINER) {
11353                FunctionSecurity::Definer
11354            } else if self.parse_keyword(Keyword::INVOKER) {
11355                FunctionSecurity::Invoker
11356            } else {
11357                return self.expected_ref("DEFINER or INVOKER", self.peek_token_ref());
11358            };
11359            Some(AlterFunctionAction::Security {
11360                external: false,
11361                security,
11362            })
11363        } else if self.parse_keyword(Keyword::PARALLEL) {
11364            let parallel = if self.parse_keyword(Keyword::UNSAFE) {
11365                FunctionParallel::Unsafe
11366            } else if self.parse_keyword(Keyword::RESTRICTED) {
11367                FunctionParallel::Restricted
11368            } else if self.parse_keyword(Keyword::SAFE) {
11369                FunctionParallel::Safe
11370            } else {
11371                return self
11372                    .expected_ref("one of UNSAFE | RESTRICTED | SAFE", self.peek_token_ref());
11373            };
11374            Some(AlterFunctionAction::Parallel(parallel))
11375        } else if self.parse_keyword(Keyword::COST) {
11376            Some(AlterFunctionAction::Cost(self.parse_number()?))
11377        } else if self.parse_keyword(Keyword::ROWS) {
11378            Some(AlterFunctionAction::Rows(self.parse_number()?))
11379        } else if self.parse_keyword(Keyword::SUPPORT) {
11380            Some(AlterFunctionAction::Support(self.parse_object_name(false)?))
11381        } else if self.parse_keyword(Keyword::SET) {
11382            let name = self.parse_object_name(false)?;
11383            let value = if self.parse_keywords(&[Keyword::FROM, Keyword::CURRENT]) {
11384                FunctionSetValue::FromCurrent
11385            } else {
11386                if !self.consume_token(&Token::Eq) && !self.parse_keyword(Keyword::TO) {
11387                    return self.expected_ref("= or TO", self.peek_token_ref());
11388                }
11389                if self.parse_keyword(Keyword::DEFAULT) {
11390                    FunctionSetValue::Default
11391                } else {
11392                    FunctionSetValue::Values(self.parse_comma_separated(Parser::parse_expr)?)
11393                }
11394            };
11395            Some(AlterFunctionAction::Set(FunctionDefinitionSetParam {
11396                name,
11397                value,
11398            }))
11399        } else if self.parse_keyword(Keyword::RESET) {
11400            let reset_config = if self.parse_keyword(Keyword::ALL) {
11401                ResetConfig::ALL
11402            } else {
11403                ResetConfig::ConfigName(self.parse_object_name(false)?)
11404            };
11405            Some(AlterFunctionAction::Reset(reset_config))
11406        } else {
11407            None
11408        };
11409
11410        Ok(action)
11411    }
11412
11413    fn parse_alter_function_actions(
11414        &mut self,
11415    ) -> Result<(Vec<AlterFunctionAction>, bool), ParserError> {
11416        let mut actions = vec![];
11417        while let Some(action) = self.parse_alter_function_action()? {
11418            actions.push(action);
11419        }
11420        if actions.is_empty() {
11421            return self.expected_ref("at least one ALTER FUNCTION action", self.peek_token_ref());
11422        }
11423        let restrict = self.parse_keyword(Keyword::RESTRICT);
11424        Ok((actions, restrict))
11425    }
11426
11427    /// Parse an `ALTER FUNCTION` or `ALTER AGGREGATE` statement.
11428    pub fn parse_alter_function(
11429        &mut self,
11430        kind: AlterFunctionKind,
11431    ) -> Result<Statement, ParserError> {
11432        let (function, aggregate_star, aggregate_order_by) = match kind {
11433            AlterFunctionKind::Function => (self.parse_function_desc()?, false, None),
11434            AlterFunctionKind::Aggregate => self.parse_alter_aggregate_signature()?,
11435        };
11436
11437        let operation = if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
11438            let new_name = self.parse_identifier()?;
11439            AlterFunctionOperation::RenameTo { new_name }
11440        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
11441            AlterFunctionOperation::OwnerTo(self.parse_owner()?)
11442        } else if self.parse_keywords(&[Keyword::SET, Keyword::SCHEMA]) {
11443            AlterFunctionOperation::SetSchema {
11444                schema_name: self.parse_object_name(false)?,
11445            }
11446        } else if matches!(kind, AlterFunctionKind::Function) && self.parse_keyword(Keyword::NO) {
11447            if !self.parse_keyword(Keyword::DEPENDS) {
11448                return self.expected_ref("DEPENDS after NO", self.peek_token_ref());
11449            }
11450            self.expect_keywords(&[Keyword::ON, Keyword::EXTENSION])?;
11451            AlterFunctionOperation::DependsOnExtension {
11452                no: true,
11453                extension_name: self.parse_object_name(false)?,
11454            }
11455        } else if matches!(kind, AlterFunctionKind::Function)
11456            && self.parse_keyword(Keyword::DEPENDS)
11457        {
11458            self.expect_keywords(&[Keyword::ON, Keyword::EXTENSION])?;
11459            AlterFunctionOperation::DependsOnExtension {
11460                no: false,
11461                extension_name: self.parse_object_name(false)?,
11462            }
11463        } else if matches!(kind, AlterFunctionKind::Function) {
11464            let (actions, restrict) = self.parse_alter_function_actions()?;
11465            AlterFunctionOperation::Actions { actions, restrict }
11466        } else {
11467            return self.expected_ref(
11468                "RENAME TO, OWNER TO, or SET SCHEMA after ALTER AGGREGATE",
11469                self.peek_token_ref(),
11470            );
11471        };
11472
11473        Ok(Statement::AlterFunction(AlterFunction {
11474            kind,
11475            function,
11476            aggregate_order_by,
11477            aggregate_star,
11478            operation,
11479        }))
11480    }
11481
11482    /// Parse a [Statement::AlterTable]
11483    pub fn parse_alter_table(&mut self, iceberg: bool) -> Result<Statement, ParserError> {
11484        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
11485        let only = self.parse_keyword(Keyword::ONLY); // [ ONLY ]
11486        let table_name = self.parse_object_name(false)?;
11487        let on_cluster = self.parse_optional_on_cluster()?;
11488        let operations = self.parse_comma_separated(Parser::parse_alter_table_operation)?;
11489
11490        let mut location = None;
11491        if self.parse_keyword(Keyword::LOCATION) {
11492            location = Some(HiveSetLocation {
11493                has_set: false,
11494                location: self.parse_identifier()?,
11495            });
11496        } else if self.parse_keywords(&[Keyword::SET, Keyword::LOCATION]) {
11497            location = Some(HiveSetLocation {
11498                has_set: true,
11499                location: self.parse_identifier()?,
11500            });
11501        }
11502
11503        let end_token = if self.peek_token_ref().token == Token::SemiColon {
11504            self.peek_token_ref().clone()
11505        } else {
11506            self.get_current_token().clone()
11507        };
11508
11509        Ok(AlterTable {
11510            name: table_name,
11511            if_exists,
11512            only,
11513            operations,
11514            location,
11515            on_cluster,
11516            table_type: if iceberg {
11517                Some(AlterTableType::Iceberg)
11518            } else {
11519                None
11520            },
11521            end_token: AttachedToken(end_token),
11522        }
11523        .into())
11524    }
11525
11526    /// Parse an `ALTER VIEW` statement.
11527    pub fn parse_alter_view(&mut self) -> Result<Statement, ParserError> {
11528        let name = self.parse_object_name(false)?;
11529        let columns = self.parse_parenthesized_column_list(Optional, false)?;
11530
11531        let with_options = self.parse_options(Keyword::WITH)?;
11532
11533        self.expect_keyword_is(Keyword::AS)?;
11534        let query = self.parse_query()?;
11535
11536        Ok(Statement::AlterView {
11537            name,
11538            columns,
11539            query,
11540            with_options,
11541        })
11542    }
11543
11544    /// Parse a [Statement::AlterType]
11545    pub fn parse_alter_type(&mut self) -> Result<Statement, ParserError> {
11546        let name = self.parse_object_name(false)?;
11547
11548        if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
11549            let new_name = self.parse_identifier()?;
11550            Ok(Statement::AlterType(AlterType {
11551                name,
11552                operation: AlterTypeOperation::Rename(AlterTypeRename { new_name }),
11553            }))
11554        } else if self.parse_keywords(&[Keyword::ADD, Keyword::VALUE]) {
11555            let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
11556            let new_enum_value = self.parse_identifier()?;
11557            let position = if self.parse_keyword(Keyword::BEFORE) {
11558                Some(AlterTypeAddValuePosition::Before(self.parse_identifier()?))
11559            } else if self.parse_keyword(Keyword::AFTER) {
11560                Some(AlterTypeAddValuePosition::After(self.parse_identifier()?))
11561            } else {
11562                None
11563            };
11564
11565            Ok(Statement::AlterType(AlterType {
11566                name,
11567                operation: AlterTypeOperation::AddValue(AlterTypeAddValue {
11568                    if_not_exists,
11569                    value: new_enum_value,
11570                    position,
11571                }),
11572            }))
11573        } else if self.parse_keywords(&[Keyword::RENAME, Keyword::VALUE]) {
11574            let existing_enum_value = self.parse_identifier()?;
11575            self.expect_keyword(Keyword::TO)?;
11576            let new_enum_value = self.parse_identifier()?;
11577
11578            Ok(Statement::AlterType(AlterType {
11579                name,
11580                operation: AlterTypeOperation::RenameValue(AlterTypeRenameValue {
11581                    from: existing_enum_value,
11582                    to: new_enum_value,
11583                }),
11584            }))
11585        } else {
11586            self.expected_ref(
11587                "{RENAME TO | { RENAME | ADD } VALUE}",
11588                self.peek_token_ref(),
11589            )
11590        }
11591    }
11592
11593    /// Parse a [Statement::AlterCollation].
11594    ///
11595    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-altercollation.html)
11596    pub fn parse_alter_collation(&mut self) -> Result<AlterCollation, ParserError> {
11597        let name = self.parse_object_name(false)?;
11598        let operation = if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
11599            AlterCollationOperation::RenameTo {
11600                new_name: self.parse_identifier()?,
11601            }
11602        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
11603            AlterCollationOperation::OwnerTo(self.parse_owner()?)
11604        } else if self.parse_keywords(&[Keyword::SET, Keyword::SCHEMA]) {
11605            AlterCollationOperation::SetSchema {
11606                schema_name: self.parse_object_name(false)?,
11607            }
11608        } else if self.parse_keywords(&[Keyword::REFRESH, Keyword::VERSION]) {
11609            AlterCollationOperation::RefreshVersion
11610        } else {
11611            return self.expected_ref(
11612                "RENAME TO, OWNER TO, SET SCHEMA, or REFRESH VERSION after ALTER COLLATION",
11613                self.peek_token_ref(),
11614            );
11615        };
11616
11617        Ok(AlterCollation { name, operation })
11618    }
11619
11620    /// Parse a [Statement::AlterOperator]
11621    ///
11622    /// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-alteroperator.html)
11623    pub fn parse_alter_operator(&mut self) -> Result<AlterOperator, ParserError> {
11624        let name = self.parse_operator_name()?;
11625
11626        // Parse (left_type, right_type)
11627        self.expect_token(&Token::LParen)?;
11628
11629        let left_type = if self.parse_keyword(Keyword::NONE) {
11630            None
11631        } else {
11632            Some(self.parse_data_type()?)
11633        };
11634
11635        self.expect_token(&Token::Comma)?;
11636        let right_type = self.parse_data_type()?;
11637        self.expect_token(&Token::RParen)?;
11638
11639        // Parse the operation
11640        let operation = if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
11641            let owner = if self.parse_keyword(Keyword::CURRENT_ROLE) {
11642                Owner::CurrentRole
11643            } else if self.parse_keyword(Keyword::CURRENT_USER) {
11644                Owner::CurrentUser
11645            } else if self.parse_keyword(Keyword::SESSION_USER) {
11646                Owner::SessionUser
11647            } else {
11648                Owner::Ident(self.parse_identifier()?)
11649            };
11650            AlterOperatorOperation::OwnerTo(owner)
11651        } else if self.parse_keywords(&[Keyword::SET, Keyword::SCHEMA]) {
11652            let schema_name = self.parse_object_name(false)?;
11653            AlterOperatorOperation::SetSchema { schema_name }
11654        } else if self.parse_keyword(Keyword::SET) {
11655            self.expect_token(&Token::LParen)?;
11656
11657            let mut options = Vec::new();
11658            loop {
11659                let keyword = self.expect_one_of_keywords(&[
11660                    Keyword::RESTRICT,
11661                    Keyword::JOIN,
11662                    Keyword::COMMUTATOR,
11663                    Keyword::NEGATOR,
11664                    Keyword::HASHES,
11665                    Keyword::MERGES,
11666                ])?;
11667
11668                match keyword {
11669                    Keyword::RESTRICT => {
11670                        self.expect_token(&Token::Eq)?;
11671                        let proc_name = if self.parse_keyword(Keyword::NONE) {
11672                            None
11673                        } else {
11674                            Some(self.parse_object_name(false)?)
11675                        };
11676                        options.push(OperatorOption::Restrict(proc_name));
11677                    }
11678                    Keyword::JOIN => {
11679                        self.expect_token(&Token::Eq)?;
11680                        let proc_name = if self.parse_keyword(Keyword::NONE) {
11681                            None
11682                        } else {
11683                            Some(self.parse_object_name(false)?)
11684                        };
11685                        options.push(OperatorOption::Join(proc_name));
11686                    }
11687                    Keyword::COMMUTATOR => {
11688                        self.expect_token(&Token::Eq)?;
11689                        let op_name = self.parse_operator_name()?;
11690                        options.push(OperatorOption::Commutator(op_name));
11691                    }
11692                    Keyword::NEGATOR => {
11693                        self.expect_token(&Token::Eq)?;
11694                        let op_name = self.parse_operator_name()?;
11695                        options.push(OperatorOption::Negator(op_name));
11696                    }
11697                    Keyword::HASHES => {
11698                        options.push(OperatorOption::Hashes);
11699                    }
11700                    Keyword::MERGES => {
11701                        options.push(OperatorOption::Merges);
11702                    }
11703                    unexpected_keyword => return Err(ParserError::ParserError(
11704                        format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in operator option"),
11705                    )),
11706                }
11707
11708                if !self.consume_token(&Token::Comma) {
11709                    break;
11710                }
11711            }
11712
11713            self.expect_token(&Token::RParen)?;
11714            AlterOperatorOperation::Set { options }
11715        } else {
11716            return self.expected_ref(
11717                "OWNER TO, SET SCHEMA, or SET after ALTER OPERATOR",
11718                self.peek_token_ref(),
11719            );
11720        };
11721
11722        Ok(AlterOperator {
11723            name,
11724            left_type,
11725            right_type,
11726            operation,
11727        })
11728    }
11729
11730    /// Parse an operator item for ALTER OPERATOR FAMILY ADD operations
11731    fn parse_operator_family_add_operator(&mut self) -> Result<OperatorFamilyItem, ParserError> {
11732        let strategy_number = self.parse_literal_uint()?;
11733        let operator_name = self.parse_operator_name()?;
11734
11735        // Operator argument types (required for ALTER OPERATOR FAMILY)
11736        self.expect_token(&Token::LParen)?;
11737        let op_types = self.parse_comma_separated(Parser::parse_data_type)?;
11738        self.expect_token(&Token::RParen)?;
11739
11740        // Optional purpose
11741        let purpose = if self.parse_keyword(Keyword::FOR) {
11742            if self.parse_keyword(Keyword::SEARCH) {
11743                Some(OperatorPurpose::ForSearch)
11744            } else if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
11745                let sort_family = self.parse_object_name(false)?;
11746                Some(OperatorPurpose::ForOrderBy { sort_family })
11747            } else {
11748                return self.expected_ref("SEARCH or ORDER BY after FOR", self.peek_token_ref());
11749            }
11750        } else {
11751            None
11752        };
11753
11754        Ok(OperatorFamilyItem::Operator {
11755            strategy_number,
11756            operator_name,
11757            op_types,
11758            purpose,
11759        })
11760    }
11761
11762    /// Parse a function item for ALTER OPERATOR FAMILY ADD operations
11763    fn parse_operator_family_add_function(&mut self) -> Result<OperatorFamilyItem, ParserError> {
11764        let support_number = self.parse_literal_uint()?;
11765
11766        // Optional operator types
11767        let op_types =
11768            if self.consume_token(&Token::LParen) && self.peek_token_ref().token != Token::RParen {
11769                let types = self.parse_comma_separated(Parser::parse_data_type)?;
11770                self.expect_token(&Token::RParen)?;
11771                Some(types)
11772            } else if self.consume_token(&Token::LParen) {
11773                self.expect_token(&Token::RParen)?;
11774                Some(vec![])
11775            } else {
11776                None
11777            };
11778
11779        let function_name = self.parse_object_name(false)?;
11780
11781        // Function argument types
11782        let argument_types = if self.consume_token(&Token::LParen) {
11783            if self.peek_token_ref().token == Token::RParen {
11784                self.expect_token(&Token::RParen)?;
11785                vec![]
11786            } else {
11787                let types = self.parse_comma_separated(Parser::parse_data_type)?;
11788                self.expect_token(&Token::RParen)?;
11789                types
11790            }
11791        } else {
11792            vec![]
11793        };
11794
11795        Ok(OperatorFamilyItem::Function {
11796            support_number,
11797            op_types,
11798            function_name,
11799            argument_types,
11800        })
11801    }
11802
11803    /// Parse an operator item for ALTER OPERATOR FAMILY DROP operations
11804    fn parse_operator_family_drop_operator(
11805        &mut self,
11806    ) -> Result<OperatorFamilyDropItem, ParserError> {
11807        let strategy_number = self.parse_literal_uint()?;
11808
11809        // Operator argument types (required for DROP)
11810        self.expect_token(&Token::LParen)?;
11811        let op_types = self.parse_comma_separated(Parser::parse_data_type)?;
11812        self.expect_token(&Token::RParen)?;
11813
11814        Ok(OperatorFamilyDropItem::Operator {
11815            strategy_number,
11816            op_types,
11817        })
11818    }
11819
11820    /// Parse a function item for ALTER OPERATOR FAMILY DROP operations
11821    fn parse_operator_family_drop_function(
11822        &mut self,
11823    ) -> Result<OperatorFamilyDropItem, ParserError> {
11824        let support_number = self.parse_literal_uint()?;
11825
11826        // Operator types (required for DROP)
11827        self.expect_token(&Token::LParen)?;
11828        let op_types = self.parse_comma_separated(Parser::parse_data_type)?;
11829        self.expect_token(&Token::RParen)?;
11830
11831        Ok(OperatorFamilyDropItem::Function {
11832            support_number,
11833            op_types,
11834        })
11835    }
11836
11837    /// Parse an operator family item for ADD operations (dispatches to operator or function parsing)
11838    fn parse_operator_family_add_item(&mut self) -> Result<OperatorFamilyItem, ParserError> {
11839        if self.parse_keyword(Keyword::OPERATOR) {
11840            self.parse_operator_family_add_operator()
11841        } else if self.parse_keyword(Keyword::FUNCTION) {
11842            self.parse_operator_family_add_function()
11843        } else {
11844            self.expected_ref("OPERATOR or FUNCTION", self.peek_token_ref())
11845        }
11846    }
11847
11848    /// Parse an operator family item for DROP operations (dispatches to operator or function parsing)
11849    fn parse_operator_family_drop_item(&mut self) -> Result<OperatorFamilyDropItem, ParserError> {
11850        if self.parse_keyword(Keyword::OPERATOR) {
11851            self.parse_operator_family_drop_operator()
11852        } else if self.parse_keyword(Keyword::FUNCTION) {
11853            self.parse_operator_family_drop_function()
11854        } else {
11855            self.expected_ref("OPERATOR or FUNCTION", self.peek_token_ref())
11856        }
11857    }
11858
11859    /// Parse a [Statement::AlterOperatorFamily]
11860    /// See <https://www.postgresql.org/docs/current/sql-alteropfamily.html>
11861    pub fn parse_alter_operator_family(&mut self) -> Result<AlterOperatorFamily, ParserError> {
11862        let name = self.parse_object_name(false)?;
11863        self.expect_keyword(Keyword::USING)?;
11864        let using = self.parse_identifier()?;
11865
11866        let operation = if self.parse_keyword(Keyword::ADD) {
11867            let items = self.parse_comma_separated(Parser::parse_operator_family_add_item)?;
11868            AlterOperatorFamilyOperation::Add { items }
11869        } else if self.parse_keyword(Keyword::DROP) {
11870            let items = self.parse_comma_separated(Parser::parse_operator_family_drop_item)?;
11871            AlterOperatorFamilyOperation::Drop { items }
11872        } else if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
11873            let new_name = self.parse_object_name(false)?;
11874            AlterOperatorFamilyOperation::RenameTo { new_name }
11875        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
11876            let owner = self.parse_owner()?;
11877            AlterOperatorFamilyOperation::OwnerTo(owner)
11878        } else if self.parse_keywords(&[Keyword::SET, Keyword::SCHEMA]) {
11879            let schema_name = self.parse_object_name(false)?;
11880            AlterOperatorFamilyOperation::SetSchema { schema_name }
11881        } else {
11882            return self.expected_ref(
11883                "ADD, DROP, RENAME TO, OWNER TO, or SET SCHEMA after ALTER OPERATOR FAMILY",
11884                self.peek_token_ref(),
11885            );
11886        };
11887
11888        Ok(AlterOperatorFamily {
11889            name,
11890            using,
11891            operation,
11892        })
11893    }
11894
11895    /// Parse an `ALTER OPERATOR CLASS` statement.
11896    ///
11897    /// Handles operations like `RENAME TO`, `OWNER TO`, and `SET SCHEMA`.
11898    pub fn parse_alter_operator_class(&mut self) -> Result<AlterOperatorClass, ParserError> {
11899        let name = self.parse_object_name(false)?;
11900        self.expect_keyword(Keyword::USING)?;
11901        let using = self.parse_identifier()?;
11902
11903        let operation = if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
11904            let new_name = self.parse_object_name(false)?;
11905            AlterOperatorClassOperation::RenameTo { new_name }
11906        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
11907            let owner = self.parse_owner()?;
11908            AlterOperatorClassOperation::OwnerTo(owner)
11909        } else if self.parse_keywords(&[Keyword::SET, Keyword::SCHEMA]) {
11910            let schema_name = self.parse_object_name(false)?;
11911            AlterOperatorClassOperation::SetSchema { schema_name }
11912        } else {
11913            return self.expected_ref(
11914                "RENAME TO, OWNER TO, or SET SCHEMA after ALTER OPERATOR CLASS",
11915                self.peek_token_ref(),
11916            );
11917        };
11918
11919        Ok(AlterOperatorClass {
11920            name,
11921            using,
11922            operation,
11923        })
11924    }
11925
11926    /// Parse an `ALTER SCHEMA` statement.
11927    ///
11928    /// Supports operations such as setting options, renaming, adding/dropping replicas, and changing owner.
11929    pub fn parse_alter_schema(&mut self) -> Result<Statement, ParserError> {
11930        self.expect_keywords(&[Keyword::ALTER, Keyword::SCHEMA])?;
11931        let if_exists = self.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
11932        let name = self.parse_object_name(false)?;
11933        let operation = if self.parse_keywords(&[Keyword::SET, Keyword::OPTIONS]) {
11934            self.prev_token();
11935            let options = self.parse_options(Keyword::OPTIONS)?;
11936            AlterSchemaOperation::SetOptionsParens { options }
11937        } else if self.parse_keywords(&[Keyword::SET, Keyword::DEFAULT, Keyword::COLLATE]) {
11938            let collate = self.parse_expr()?;
11939            AlterSchemaOperation::SetDefaultCollate { collate }
11940        } else if self.parse_keywords(&[Keyword::ADD, Keyword::REPLICA]) {
11941            let replica = self.parse_identifier()?;
11942            let options = if self.peek_keyword(Keyword::OPTIONS) {
11943                Some(self.parse_options(Keyword::OPTIONS)?)
11944            } else {
11945                None
11946            };
11947            AlterSchemaOperation::AddReplica { replica, options }
11948        } else if self.parse_keywords(&[Keyword::DROP, Keyword::REPLICA]) {
11949            let replica = self.parse_identifier()?;
11950            AlterSchemaOperation::DropReplica { replica }
11951        } else if self.parse_keywords(&[Keyword::RENAME, Keyword::TO]) {
11952            let new_name = self.parse_object_name(false)?;
11953            AlterSchemaOperation::Rename { name: new_name }
11954        } else if self.parse_keywords(&[Keyword::OWNER, Keyword::TO]) {
11955            let owner = self.parse_owner()?;
11956            AlterSchemaOperation::OwnerTo { owner }
11957        } else {
11958            return self.expected_ref("ALTER SCHEMA operation", self.peek_token_ref());
11959        };
11960        Ok(Statement::AlterSchema(AlterSchema {
11961            name,
11962            if_exists,
11963            operations: vec![operation],
11964        }))
11965    }
11966
11967    /// Parse a `CALL procedure_name(arg1, arg2, ...)`
11968    /// or `CALL procedure_name` statement
11969    pub fn parse_call(&mut self) -> Result<Statement, ParserError> {
11970        let object_name = self.parse_object_name(false)?;
11971        if self.peek_token_ref().token == Token::LParen {
11972            match self.parse_function(object_name)? {
11973                Expr::Function(f) => Ok(Statement::Call(f)),
11974                other => parser_err!(
11975                    format!("Expected a simple procedure call but found: {other}"),
11976                    self.peek_token_ref().span.start
11977                ),
11978            }
11979        } else {
11980            Ok(Statement::Call(Function {
11981                name: object_name,
11982                uses_odbc_syntax: false,
11983                parameters: FunctionArguments::None,
11984                args: FunctionArguments::None,
11985                over: None,
11986                filter: None,
11987                null_treatment: None,
11988                within_group: vec![],
11989            }))
11990        }
11991    }
11992
11993    /// Parse a copy statement
11994    pub fn parse_copy(&mut self) -> Result<Statement, ParserError> {
11995        let source;
11996        if self.consume_token(&Token::LParen) {
11997            source = CopySource::Query(self.parse_query()?);
11998            self.expect_token(&Token::RParen)?;
11999        } else {
12000            let table_name = self.parse_object_name(false)?;
12001            let columns = self.parse_parenthesized_column_list(Optional, false)?;
12002            source = CopySource::Table {
12003                table_name,
12004                columns,
12005            };
12006        }
12007        let to = match self.parse_one_of_keywords(&[Keyword::FROM, Keyword::TO]) {
12008            Some(Keyword::FROM) => false,
12009            Some(Keyword::TO) => true,
12010            _ => self.expected_ref("FROM or TO", self.peek_token_ref())?,
12011        };
12012        if !to {
12013            // Use a separate if statement to prevent Rust compiler from complaining about
12014            // "if statement in this position is unstable: https://github.com/rust-lang/rust/issues/53667"
12015            if let CopySource::Query(_) = source {
12016                return Err(ParserError::ParserError(
12017                    "COPY ... FROM does not support query as a source".to_string(),
12018                ));
12019            }
12020        }
12021        let target = if self.parse_keyword(Keyword::STDIN) {
12022            CopyTarget::Stdin
12023        } else if self.parse_keyword(Keyword::STDOUT) {
12024            CopyTarget::Stdout
12025        } else if self.parse_keyword(Keyword::PROGRAM) {
12026            CopyTarget::Program {
12027                command: self.parse_literal_string()?,
12028            }
12029        } else {
12030            CopyTarget::File {
12031                filename: self.parse_literal_string()?,
12032            }
12033        };
12034        let _ = self.parse_keyword(Keyword::WITH); // [ WITH ]
12035        let mut options = vec![];
12036        if self.consume_token(&Token::LParen) {
12037            options = self.parse_comma_separated(Parser::parse_copy_option)?;
12038            self.expect_token(&Token::RParen)?;
12039        }
12040        let mut legacy_options = vec![];
12041        while let Some(opt) = self.maybe_parse(|parser| parser.parse_copy_legacy_option())? {
12042            legacy_options.push(opt);
12043        }
12044        let values =
12045            if matches!(target, CopyTarget::Stdin) && self.peek_token_ref().token != Token::EOF {
12046                self.expect_token(&Token::SemiColon)?;
12047                self.parse_tsv()
12048            } else {
12049                vec![]
12050            };
12051        Ok(Statement::Copy {
12052            source,
12053            to,
12054            target,
12055            options,
12056            legacy_options,
12057            values,
12058        })
12059    }
12060
12061    /// Parse [Statement::Open]
12062    fn parse_open(&mut self) -> Result<Statement, ParserError> {
12063        self.expect_keyword(Keyword::OPEN)?;
12064        Ok(Statement::Open(OpenStatement {
12065            cursor_name: self.parse_identifier()?,
12066        }))
12067    }
12068
12069    /// Parse a `CLOSE` cursor statement.
12070    pub fn parse_close(&mut self) -> Result<Statement, ParserError> {
12071        let cursor = if self.parse_keyword(Keyword::ALL) {
12072            CloseCursor::All
12073        } else {
12074            let name = self.parse_identifier()?;
12075
12076            CloseCursor::Specific { name }
12077        };
12078
12079        Ok(Statement::Close { cursor })
12080    }
12081
12082    fn parse_copy_option(&mut self) -> Result<CopyOption, ParserError> {
12083        let ret = match self.parse_one_of_keywords(&[
12084            Keyword::FORMAT,
12085            Keyword::FREEZE,
12086            Keyword::DELIMITER,
12087            Keyword::NULL,
12088            Keyword::HEADER,
12089            Keyword::QUOTE,
12090            Keyword::ESCAPE,
12091            Keyword::FORCE_QUOTE,
12092            Keyword::FORCE_NOT_NULL,
12093            Keyword::FORCE_NULL,
12094            Keyword::ENCODING,
12095        ]) {
12096            Some(Keyword::FORMAT) => CopyOption::Format(self.parse_identifier()?),
12097            Some(Keyword::FREEZE) => CopyOption::Freeze(!matches!(
12098                self.parse_one_of_keywords(&[Keyword::TRUE, Keyword::FALSE]),
12099                Some(Keyword::FALSE)
12100            )),
12101            Some(Keyword::DELIMITER) => CopyOption::Delimiter(self.parse_literal_char()?),
12102            Some(Keyword::NULL) => CopyOption::Null(self.parse_literal_string()?),
12103            Some(Keyword::HEADER) => CopyOption::Header(!matches!(
12104                self.parse_one_of_keywords(&[Keyword::TRUE, Keyword::FALSE]),
12105                Some(Keyword::FALSE)
12106            )),
12107            Some(Keyword::QUOTE) => CopyOption::Quote(self.parse_literal_char()?),
12108            Some(Keyword::ESCAPE) => CopyOption::Escape(self.parse_literal_char()?),
12109            Some(Keyword::FORCE_QUOTE) => {
12110                CopyOption::ForceQuote(self.parse_parenthesized_column_list(Mandatory, false)?)
12111            }
12112            Some(Keyword::FORCE_NOT_NULL) => {
12113                CopyOption::ForceNotNull(self.parse_parenthesized_column_list(Mandatory, false)?)
12114            }
12115            Some(Keyword::FORCE_NULL) => {
12116                CopyOption::ForceNull(self.parse_parenthesized_column_list(Mandatory, false)?)
12117            }
12118            Some(Keyword::ENCODING) => CopyOption::Encoding(self.parse_literal_string()?),
12119            _ => self.expected_ref("option", self.peek_token_ref())?,
12120        };
12121        Ok(ret)
12122    }
12123
12124    fn parse_copy_legacy_option(&mut self) -> Result<CopyLegacyOption, ParserError> {
12125        // FORMAT \[ AS \] is optional
12126        if self.parse_keyword(Keyword::FORMAT) {
12127            let _ = self.parse_keyword(Keyword::AS);
12128        }
12129
12130        let ret = match self.parse_one_of_keywords(&[
12131            Keyword::ACCEPTANYDATE,
12132            Keyword::ACCEPTINVCHARS,
12133            Keyword::ADDQUOTES,
12134            Keyword::ALLOWOVERWRITE,
12135            Keyword::BINARY,
12136            Keyword::BLANKSASNULL,
12137            Keyword::BZIP2,
12138            Keyword::CLEANPATH,
12139            Keyword::COMPUPDATE,
12140            Keyword::CREDENTIALS,
12141            Keyword::CSV,
12142            Keyword::DATEFORMAT,
12143            Keyword::DELIMITER,
12144            Keyword::EMPTYASNULL,
12145            Keyword::ENCRYPTED,
12146            Keyword::ESCAPE,
12147            Keyword::EXTENSION,
12148            Keyword::FIXEDWIDTH,
12149            Keyword::GZIP,
12150            Keyword::HEADER,
12151            Keyword::IAM_ROLE,
12152            Keyword::IGNOREHEADER,
12153            Keyword::JSON,
12154            Keyword::MANIFEST,
12155            Keyword::MAXFILESIZE,
12156            Keyword::NULL,
12157            Keyword::PARALLEL,
12158            Keyword::PARQUET,
12159            Keyword::PARTITION,
12160            Keyword::REGION,
12161            Keyword::REMOVEQUOTES,
12162            Keyword::ROWGROUPSIZE,
12163            Keyword::STATUPDATE,
12164            Keyword::TIMEFORMAT,
12165            Keyword::TRUNCATECOLUMNS,
12166            Keyword::ZSTD,
12167        ]) {
12168            Some(Keyword::ACCEPTANYDATE) => CopyLegacyOption::AcceptAnyDate,
12169            Some(Keyword::ACCEPTINVCHARS) => {
12170                let _ = self.parse_keyword(Keyword::AS); // [ AS ]
12171                let ch = if matches!(self.peek_token_ref().token, Token::SingleQuotedString(_)) {
12172                    Some(self.parse_literal_string()?)
12173                } else {
12174                    None
12175                };
12176                CopyLegacyOption::AcceptInvChars(ch)
12177            }
12178            Some(Keyword::ADDQUOTES) => CopyLegacyOption::AddQuotes,
12179            Some(Keyword::ALLOWOVERWRITE) => CopyLegacyOption::AllowOverwrite,
12180            Some(Keyword::BINARY) => CopyLegacyOption::Binary,
12181            Some(Keyword::BLANKSASNULL) => CopyLegacyOption::BlankAsNull,
12182            Some(Keyword::BZIP2) => CopyLegacyOption::Bzip2,
12183            Some(Keyword::CLEANPATH) => CopyLegacyOption::CleanPath,
12184            Some(Keyword::COMPUPDATE) => {
12185                let preset = self.parse_keyword(Keyword::PRESET);
12186                let enabled = match self.parse_one_of_keywords(&[
12187                    Keyword::TRUE,
12188                    Keyword::FALSE,
12189                    Keyword::ON,
12190                    Keyword::OFF,
12191                ]) {
12192                    Some(Keyword::TRUE) | Some(Keyword::ON) => Some(true),
12193                    Some(Keyword::FALSE) | Some(Keyword::OFF) => Some(false),
12194                    _ => None,
12195                };
12196                CopyLegacyOption::CompUpdate { preset, enabled }
12197            }
12198            Some(Keyword::CREDENTIALS) => {
12199                CopyLegacyOption::Credentials(self.parse_literal_string()?)
12200            }
12201            Some(Keyword::CSV) => CopyLegacyOption::Csv({
12202                let mut opts = vec![];
12203                while let Some(opt) =
12204                    self.maybe_parse(|parser| parser.parse_copy_legacy_csv_option())?
12205                {
12206                    opts.push(opt);
12207                }
12208                opts
12209            }),
12210            Some(Keyword::DATEFORMAT) => {
12211                let _ = self.parse_keyword(Keyword::AS);
12212                let fmt = if matches!(self.peek_token_ref().token, Token::SingleQuotedString(_)) {
12213                    Some(self.parse_literal_string()?)
12214                } else {
12215                    None
12216                };
12217                CopyLegacyOption::DateFormat(fmt)
12218            }
12219            Some(Keyword::DELIMITER) => {
12220                let _ = self.parse_keyword(Keyword::AS);
12221                CopyLegacyOption::Delimiter(self.parse_literal_char()?)
12222            }
12223            Some(Keyword::EMPTYASNULL) => CopyLegacyOption::EmptyAsNull,
12224            Some(Keyword::ENCRYPTED) => {
12225                let auto = self.parse_keyword(Keyword::AUTO);
12226                CopyLegacyOption::Encrypted { auto }
12227            }
12228            Some(Keyword::ESCAPE) => CopyLegacyOption::Escape,
12229            Some(Keyword::EXTENSION) => {
12230                let ext = self.parse_literal_string()?;
12231                CopyLegacyOption::Extension(ext)
12232            }
12233            Some(Keyword::FIXEDWIDTH) => {
12234                let spec = self.parse_literal_string()?;
12235                CopyLegacyOption::FixedWidth(spec)
12236            }
12237            Some(Keyword::GZIP) => CopyLegacyOption::Gzip,
12238            Some(Keyword::HEADER) => CopyLegacyOption::Header,
12239            Some(Keyword::IAM_ROLE) => CopyLegacyOption::IamRole(self.parse_iam_role_kind()?),
12240            Some(Keyword::IGNOREHEADER) => {
12241                let _ = self.parse_keyword(Keyword::AS);
12242                let num_rows = self.parse_literal_uint()?;
12243                CopyLegacyOption::IgnoreHeader(num_rows)
12244            }
12245            Some(Keyword::JSON) => {
12246                let _ = self.parse_keyword(Keyword::AS);
12247                let fmt = if matches!(self.peek_token_ref().token, Token::SingleQuotedString(_)) {
12248                    Some(self.parse_literal_string()?)
12249                } else {
12250                    None
12251                };
12252                CopyLegacyOption::Json(fmt)
12253            }
12254            Some(Keyword::MANIFEST) => {
12255                let verbose = self.parse_keyword(Keyword::VERBOSE);
12256                CopyLegacyOption::Manifest { verbose }
12257            }
12258            Some(Keyword::MAXFILESIZE) => {
12259                let _ = self.parse_keyword(Keyword::AS);
12260                let size = self.parse_number_value()?;
12261                let unit = match self.parse_one_of_keywords(&[Keyword::MB, Keyword::GB]) {
12262                    Some(Keyword::MB) => Some(FileSizeUnit::MB),
12263                    Some(Keyword::GB) => Some(FileSizeUnit::GB),
12264                    _ => None,
12265                };
12266                CopyLegacyOption::MaxFileSize(FileSize { size, unit })
12267            }
12268            Some(Keyword::NULL) => {
12269                let _ = self.parse_keyword(Keyword::AS);
12270                CopyLegacyOption::Null(self.parse_literal_string()?)
12271            }
12272            Some(Keyword::PARALLEL) => {
12273                let enabled = match self.parse_one_of_keywords(&[
12274                    Keyword::TRUE,
12275                    Keyword::FALSE,
12276                    Keyword::ON,
12277                    Keyword::OFF,
12278                ]) {
12279                    Some(Keyword::TRUE) | Some(Keyword::ON) => Some(true),
12280                    Some(Keyword::FALSE) | Some(Keyword::OFF) => Some(false),
12281                    _ => None,
12282                };
12283                CopyLegacyOption::Parallel(enabled)
12284            }
12285            Some(Keyword::PARQUET) => CopyLegacyOption::Parquet,
12286            Some(Keyword::PARTITION) => {
12287                self.expect_keyword(Keyword::BY)?;
12288                let columns = self.parse_parenthesized_column_list(IsOptional::Mandatory, false)?;
12289                let include = self.parse_keyword(Keyword::INCLUDE);
12290                CopyLegacyOption::PartitionBy(UnloadPartitionBy { columns, include })
12291            }
12292            Some(Keyword::REGION) => {
12293                let _ = self.parse_keyword(Keyword::AS);
12294                let region = self.parse_literal_string()?;
12295                CopyLegacyOption::Region(region)
12296            }
12297            Some(Keyword::REMOVEQUOTES) => CopyLegacyOption::RemoveQuotes,
12298            Some(Keyword::ROWGROUPSIZE) => {
12299                let _ = self.parse_keyword(Keyword::AS);
12300                let file_size = self.parse_file_size()?;
12301                CopyLegacyOption::RowGroupSize(file_size)
12302            }
12303            Some(Keyword::STATUPDATE) => {
12304                let enabled = match self.parse_one_of_keywords(&[
12305                    Keyword::TRUE,
12306                    Keyword::FALSE,
12307                    Keyword::ON,
12308                    Keyword::OFF,
12309                ]) {
12310                    Some(Keyword::TRUE) | Some(Keyword::ON) => Some(true),
12311                    Some(Keyword::FALSE) | Some(Keyword::OFF) => Some(false),
12312                    _ => None,
12313                };
12314                CopyLegacyOption::StatUpdate(enabled)
12315            }
12316            Some(Keyword::TIMEFORMAT) => {
12317                let _ = self.parse_keyword(Keyword::AS);
12318                let fmt = if matches!(self.peek_token_ref().token, Token::SingleQuotedString(_)) {
12319                    Some(self.parse_literal_string()?)
12320                } else {
12321                    None
12322                };
12323                CopyLegacyOption::TimeFormat(fmt)
12324            }
12325            Some(Keyword::TRUNCATECOLUMNS) => CopyLegacyOption::TruncateColumns,
12326            Some(Keyword::ZSTD) => CopyLegacyOption::Zstd,
12327            _ => self.expected_ref("option", self.peek_token_ref())?,
12328        };
12329        Ok(ret)
12330    }
12331
12332    fn parse_file_size(&mut self) -> Result<FileSize, ParserError> {
12333        let size = self.parse_number_value()?;
12334        let unit = self.maybe_parse_file_size_unit();
12335        Ok(FileSize { size, unit })
12336    }
12337
12338    fn maybe_parse_file_size_unit(&mut self) -> Option<FileSizeUnit> {
12339        match self.parse_one_of_keywords(&[Keyword::MB, Keyword::GB]) {
12340            Some(Keyword::MB) => Some(FileSizeUnit::MB),
12341            Some(Keyword::GB) => Some(FileSizeUnit::GB),
12342            _ => None,
12343        }
12344    }
12345
12346    fn parse_iam_role_kind(&mut self) -> Result<IamRoleKind, ParserError> {
12347        if self.parse_keyword(Keyword::DEFAULT) {
12348            Ok(IamRoleKind::Default)
12349        } else {
12350            let arn = self.parse_literal_string()?;
12351            Ok(IamRoleKind::Arn(arn))
12352        }
12353    }
12354
12355    fn parse_copy_legacy_csv_option(&mut self) -> Result<CopyLegacyCsvOption, ParserError> {
12356        let ret = match self.parse_one_of_keywords(&[
12357            Keyword::HEADER,
12358            Keyword::QUOTE,
12359            Keyword::ESCAPE,
12360            Keyword::FORCE,
12361        ]) {
12362            Some(Keyword::HEADER) => CopyLegacyCsvOption::Header,
12363            Some(Keyword::QUOTE) => {
12364                let _ = self.parse_keyword(Keyword::AS); // [ AS ]
12365                CopyLegacyCsvOption::Quote(self.parse_literal_char()?)
12366            }
12367            Some(Keyword::ESCAPE) => {
12368                let _ = self.parse_keyword(Keyword::AS); // [ AS ]
12369                CopyLegacyCsvOption::Escape(self.parse_literal_char()?)
12370            }
12371            Some(Keyword::FORCE) if self.parse_keywords(&[Keyword::NOT, Keyword::NULL]) => {
12372                CopyLegacyCsvOption::ForceNotNull(
12373                    self.parse_comma_separated(|p| p.parse_identifier())?,
12374                )
12375            }
12376            Some(Keyword::FORCE) if self.parse_keywords(&[Keyword::QUOTE]) => {
12377                CopyLegacyCsvOption::ForceQuote(
12378                    self.parse_comma_separated(|p| p.parse_identifier())?,
12379                )
12380            }
12381            _ => self.expected_ref("csv option", self.peek_token_ref())?,
12382        };
12383        Ok(ret)
12384    }
12385
12386    fn parse_literal_char(&mut self) -> Result<char, ParserError> {
12387        let s = self.parse_literal_string()?;
12388        if s.len() != 1 {
12389            let loc = self
12390                .tokens
12391                .get(self.index - 1)
12392                .map_or(Location { line: 0, column: 0 }, |t| t.span.start);
12393            return parser_err!(format!("Expect a char, found {s:?}"), loc);
12394        }
12395        Ok(s.chars().next().unwrap())
12396    }
12397
12398    /// Parse a tab separated values in
12399    /// COPY payload
12400    pub fn parse_tsv(&mut self) -> Vec<Option<String>> {
12401        self.parse_tab_value()
12402    }
12403
12404    /// Parse a single tab-separated value row used by `COPY` payload parsing.
12405    pub fn parse_tab_value(&mut self) -> Vec<Option<String>> {
12406        let mut values = vec![];
12407        let mut content = String::new();
12408        while let Some(t) = self.next_token_no_skip().map(|t| &t.token) {
12409            match t {
12410                Token::Whitespace(Whitespace::Tab) => {
12411                    values.push(Some(core::mem::take(&mut content)));
12412                }
12413                Token::Whitespace(Whitespace::Newline) => {
12414                    values.push(Some(core::mem::take(&mut content)));
12415                }
12416                Token::Backslash => {
12417                    if self.consume_token(&Token::Period) {
12418                        return values;
12419                    }
12420                    if let Token::Word(w) = self.next_token().token {
12421                        if w.value == "N" {
12422                            values.push(None);
12423                        }
12424                    }
12425                }
12426                _ => {
12427                    content.push_str(&t.to_string());
12428                }
12429            }
12430        }
12431        values
12432    }
12433
12434    /// Parse a literal value (numbers, strings, date/time, booleans)
12435    pub fn parse_value(&mut self) -> Result<ValueWithSpan, ParserError> {
12436        let next_token = self.next_token();
12437        let span = next_token.span;
12438        let ok_value = |value: Value| Ok(value.with_span(span));
12439        match next_token.token {
12440            Token::Word(w) => match w.keyword {
12441                Keyword::TRUE if self.dialect.supports_boolean_literals() => {
12442                    ok_value(Value::Boolean(true))
12443                }
12444                Keyword::FALSE if self.dialect.supports_boolean_literals() => {
12445                    ok_value(Value::Boolean(false))
12446                }
12447                Keyword::NULL => ok_value(Value::Null),
12448                Keyword::NoKeyword if w.quote_style.is_some() => match w.quote_style {
12449                    Some('"') => ok_value(Value::DoubleQuotedString(w.value)),
12450                    Some('\'') => ok_value(Value::SingleQuotedString(w.value)),
12451                    _ => self.expected(
12452                        "A value?",
12453                        TokenWithSpan {
12454                            token: Token::Word(w),
12455                            span,
12456                        },
12457                    )?,
12458                },
12459                _ => self.expected(
12460                    "a concrete value",
12461                    TokenWithSpan {
12462                        token: Token::Word(w),
12463                        span,
12464                    },
12465                ),
12466            },
12467            // The call to n.parse() returns a bigdecimal when the
12468            // bigdecimal feature is enabled, and is otherwise a no-op
12469            // (i.e., it returns the input string).
12470            Token::Number(n, l) => ok_value(Value::Number(Self::parse(n, span.start)?, l)),
12471            Token::SingleQuotedString(ref s) => ok_value(Value::SingleQuotedString(
12472                self.maybe_concat_string_literal(s.to_string()),
12473            )),
12474            Token::DoubleQuotedString(ref s) => ok_value(Value::DoubleQuotedString(
12475                self.maybe_concat_string_literal(s.to_string()),
12476            )),
12477            Token::TripleSingleQuotedString(ref s) => {
12478                ok_value(Value::TripleSingleQuotedString(s.to_string()))
12479            }
12480            Token::TripleDoubleQuotedString(ref s) => {
12481                ok_value(Value::TripleDoubleQuotedString(s.to_string()))
12482            }
12483            Token::DollarQuotedString(ref s) => ok_value(Value::DollarQuotedString(s.clone())),
12484            Token::SingleQuotedByteStringLiteral(ref s) => {
12485                ok_value(Value::SingleQuotedByteStringLiteral(s.clone()))
12486            }
12487            Token::DoubleQuotedByteStringLiteral(ref s) => {
12488                ok_value(Value::DoubleQuotedByteStringLiteral(s.clone()))
12489            }
12490            Token::TripleSingleQuotedByteStringLiteral(ref s) => {
12491                ok_value(Value::TripleSingleQuotedByteStringLiteral(s.clone()))
12492            }
12493            Token::TripleDoubleQuotedByteStringLiteral(ref s) => {
12494                ok_value(Value::TripleDoubleQuotedByteStringLiteral(s.clone()))
12495            }
12496            Token::SingleQuotedRawStringLiteral(ref s) => {
12497                ok_value(Value::SingleQuotedRawStringLiteral(s.clone()))
12498            }
12499            Token::DoubleQuotedRawStringLiteral(ref s) => {
12500                ok_value(Value::DoubleQuotedRawStringLiteral(s.clone()))
12501            }
12502            Token::TripleSingleQuotedRawStringLiteral(ref s) => {
12503                ok_value(Value::TripleSingleQuotedRawStringLiteral(s.clone()))
12504            }
12505            Token::TripleDoubleQuotedRawStringLiteral(ref s) => {
12506                ok_value(Value::TripleDoubleQuotedRawStringLiteral(s.clone()))
12507            }
12508            Token::NationalStringLiteral(ref s) => {
12509                ok_value(Value::NationalStringLiteral(s.to_string()))
12510            }
12511            Token::QuoteDelimitedStringLiteral(v) => {
12512                ok_value(Value::QuoteDelimitedStringLiteral(v))
12513            }
12514            Token::NationalQuoteDelimitedStringLiteral(v) => {
12515                ok_value(Value::NationalQuoteDelimitedStringLiteral(v))
12516            }
12517            Token::EscapedStringLiteral(ref s) => {
12518                ok_value(Value::EscapedStringLiteral(s.to_string()))
12519            }
12520            Token::UnicodeStringLiteral(ref s) => {
12521                ok_value(Value::UnicodeStringLiteral(s.to_string()))
12522            }
12523            Token::HexStringLiteral(ref s) => ok_value(Value::HexStringLiteral(s.to_string())),
12524            Token::Placeholder(ref s) => ok_value(Value::Placeholder(s.to_string())),
12525            tok @ Token::Colon | tok @ Token::AtSign => {
12526                // 1. Not calling self.parse_identifier(false)?
12527                //    because only in placeholder we want to check
12528                //    numbers as idfentifies.  This because snowflake
12529                //    allows numbers as placeholders
12530                // 2. Not calling self.next_token() to enforce `tok`
12531                //    be followed immediately by a word/number, ie.
12532                //    without any whitespace in between
12533                let next_token = self.next_token_no_skip().unwrap_or(&EOF_TOKEN).clone();
12534                let ident = match next_token.token {
12535                    Token::Word(w) => Ok(w.into_ident(next_token.span)),
12536                    Token::Number(w, false) => Ok(Ident::with_span(next_token.span, w)),
12537                    _ => self.expected("placeholder", next_token),
12538                }?;
12539                Ok(Value::Placeholder(format!("{tok}{}", ident.value))
12540                    .with_span(Span::new(span.start, ident.span.end)))
12541            }
12542            unexpected => self.expected(
12543                "a value",
12544                TokenWithSpan {
12545                    token: unexpected,
12546                    span,
12547                },
12548            ),
12549        }
12550    }
12551
12552    fn maybe_concat_string_literal(&mut self, mut str: String) -> String {
12553        if self.dialect.supports_string_literal_concatenation() {
12554            while let Token::SingleQuotedString(ref s) | Token::DoubleQuotedString(ref s) =
12555                self.peek_token_ref().token
12556            {
12557                str.push_str(s);
12558                self.advance_token();
12559            }
12560        } else if self
12561            .dialect
12562            .supports_string_literal_concatenation_with_newline()
12563        {
12564            // We are iterating over tokens including whitespaces, to identify
12565            // string literals separated by newlines so we can concatenate them.
12566            let mut after_newline = false;
12567            loop {
12568                match self.peek_token_no_skip().token {
12569                    Token::Whitespace(Whitespace::Newline) => {
12570                        after_newline = true;
12571                        self.next_token_no_skip();
12572                    }
12573                    Token::Whitespace(_) => {
12574                        self.next_token_no_skip();
12575                    }
12576                    Token::SingleQuotedString(ref s) | Token::DoubleQuotedString(ref s)
12577                        if after_newline =>
12578                    {
12579                        str.push_str(s.clone().as_str());
12580                        self.next_token_no_skip();
12581                        after_newline = false;
12582                    }
12583                    _ => break,
12584                }
12585            }
12586        }
12587
12588        str
12589    }
12590
12591    /// Parse an unsigned numeric literal
12592    pub fn parse_number_value(&mut self) -> Result<ValueWithSpan, ParserError> {
12593        let value_wrapper = self.parse_value()?;
12594        match &value_wrapper.value {
12595            Value::Number(_, _) => Ok(value_wrapper),
12596            Value::Placeholder(_) => Ok(value_wrapper),
12597            _ => {
12598                self.prev_token();
12599                self.expected_ref("literal number", self.peek_token_ref())
12600            }
12601        }
12602    }
12603
12604    /// Parse a numeric literal as an expression. Returns a [`Expr::UnaryOp`] if the number is signed,
12605    /// otherwise returns a [`Expr::Value`]
12606    pub fn parse_number(&mut self) -> Result<Expr, ParserError> {
12607        let next_token = self.next_token();
12608        match next_token.token {
12609            Token::Plus => Ok(Expr::UnaryOp {
12610                op: UnaryOperator::Plus,
12611                expr: Box::new(Expr::Value(self.parse_number_value()?)),
12612            }),
12613            Token::Minus => Ok(Expr::UnaryOp {
12614                op: UnaryOperator::Minus,
12615                expr: Box::new(Expr::Value(self.parse_number_value()?)),
12616            }),
12617            _ => {
12618                self.prev_token();
12619                Ok(Expr::Value(self.parse_number_value()?))
12620            }
12621        }
12622    }
12623
12624    fn parse_introduced_string_expr(&mut self) -> Result<Expr, ParserError> {
12625        let next_token = self.next_token();
12626        let span = next_token.span;
12627        match next_token.token {
12628            Token::SingleQuotedString(ref s) => Ok(Expr::Value(
12629                Value::SingleQuotedString(s.to_string()).with_span(span),
12630            )),
12631            Token::DoubleQuotedString(ref s) => Ok(Expr::Value(
12632                Value::DoubleQuotedString(s.to_string()).with_span(span),
12633            )),
12634            Token::HexStringLiteral(ref s) => Ok(Expr::Value(
12635                Value::HexStringLiteral(s.to_string()).with_span(span),
12636            )),
12637            unexpected => self.expected(
12638                "a string value",
12639                TokenWithSpan {
12640                    token: unexpected,
12641                    span,
12642                },
12643            ),
12644        }
12645    }
12646
12647    /// Parse an unsigned literal integer/long
12648    pub fn parse_literal_uint(&mut self) -> Result<u64, ParserError> {
12649        let next_token = self.next_token();
12650        match next_token.token {
12651            Token::Number(s, _) => Self::parse::<u64>(s, next_token.span.start),
12652            _ => self.expected("literal int", next_token),
12653        }
12654    }
12655
12656    /// Parse the body of a `CREATE FUNCTION` specified as a string.
12657    /// e.g. `CREATE FUNCTION ... AS $$ body $$`.
12658    fn parse_create_function_body_string(&mut self) -> Result<CreateFunctionBody, ParserError> {
12659        let parse_string_expr = |parser: &mut Parser| -> Result<Expr, ParserError> {
12660            let peek_token = parser.peek_token();
12661            let span = peek_token.span;
12662            match peek_token.token {
12663                Token::DollarQuotedString(s) if dialect_of!(parser is PostgreSqlDialect | GenericDialect) =>
12664                {
12665                    parser.next_token();
12666                    Ok(Expr::Value(Value::DollarQuotedString(s).with_span(span)))
12667                }
12668                _ => Ok(Expr::Value(
12669                    Value::SingleQuotedString(parser.parse_literal_string()?).with_span(span),
12670                )),
12671            }
12672        };
12673
12674        Ok(CreateFunctionBody::AsBeforeOptions {
12675            body: parse_string_expr(self)?,
12676            link_symbol: if self.consume_token(&Token::Comma) {
12677                Some(parse_string_expr(self)?)
12678            } else {
12679                None
12680            },
12681        })
12682    }
12683
12684    /// Parse a literal string
12685    pub fn parse_literal_string(&mut self) -> Result<String, ParserError> {
12686        let next_token = self.next_token();
12687        match next_token.token {
12688            Token::Word(Word {
12689                value,
12690                keyword: Keyword::NoKeyword,
12691                ..
12692            }) => Ok(value),
12693            Token::SingleQuotedString(s) => Ok(s),
12694            Token::DoubleQuotedString(s) => Ok(s),
12695            Token::EscapedStringLiteral(s) if dialect_of!(self is PostgreSqlDialect | GenericDialect) => {
12696                Ok(s)
12697            }
12698            Token::UnicodeStringLiteral(s) => Ok(s),
12699            _ => self.expected("literal string", next_token),
12700        }
12701    }
12702
12703    /// Parse a boolean string
12704    pub(crate) fn parse_boolean_string(&mut self) -> Result<bool, ParserError> {
12705        match self.parse_one_of_keywords(&[Keyword::TRUE, Keyword::FALSE]) {
12706            Some(Keyword::TRUE) => Ok(true),
12707            Some(Keyword::FALSE) => Ok(false),
12708            _ => self.expected_ref("TRUE or FALSE", self.peek_token_ref()),
12709        }
12710    }
12711
12712    /// Parse a literal unicode normalization clause
12713    pub fn parse_unicode_is_normalized(&mut self, expr: Expr) -> Result<Expr, ParserError> {
12714        let neg = self.parse_keyword(Keyword::NOT);
12715        let normalized_form = self.maybe_parse(|parser| {
12716            match parser.parse_one_of_keywords(&[
12717                Keyword::NFC,
12718                Keyword::NFD,
12719                Keyword::NFKC,
12720                Keyword::NFKD,
12721            ]) {
12722                Some(Keyword::NFC) => Ok(NormalizationForm::NFC),
12723                Some(Keyword::NFD) => Ok(NormalizationForm::NFD),
12724                Some(Keyword::NFKC) => Ok(NormalizationForm::NFKC),
12725                Some(Keyword::NFKD) => Ok(NormalizationForm::NFKD),
12726                _ => parser.expected_ref("unicode normalization form", parser.peek_token_ref()),
12727            }
12728        })?;
12729        if self.parse_keyword(Keyword::NORMALIZED) {
12730            return Ok(Expr::IsNormalized {
12731                expr: Box::new(expr),
12732                form: normalized_form,
12733                negated: neg,
12734            });
12735        }
12736        self.expected_ref("unicode normalization form", self.peek_token_ref())
12737    }
12738
12739    /// Parse parenthesized enum members, used with `ENUM(...)` type definitions.
12740    pub fn parse_enum_values(&mut self) -> Result<Vec<EnumMember>, ParserError> {
12741        self.expect_token(&Token::LParen)?;
12742        let values = self.parse_comma_separated(|parser| {
12743            let name = parser.parse_literal_string()?;
12744            let e = if parser.consume_token(&Token::Eq) {
12745                let value = parser.parse_number()?;
12746                EnumMember::NamedValue(name, value)
12747            } else {
12748                EnumMember::Name(name)
12749            };
12750            Ok(e)
12751        })?;
12752        self.expect_token(&Token::RParen)?;
12753
12754        Ok(values)
12755    }
12756
12757    /// Parse a SQL datatype (in the context of a CREATE TABLE statement for example)
12758    pub fn parse_data_type(&mut self) -> Result<DataType, ParserError> {
12759        let (ty, trailing_bracket) = self.parse_data_type_helper()?;
12760        if trailing_bracket.0 {
12761            return parser_err!(
12762                format!("unmatched > after parsing data type {ty}"),
12763                self.peek_token_ref()
12764            );
12765        }
12766
12767        Ok(ty)
12768    }
12769
12770    fn parse_data_type_helper(
12771        &mut self,
12772    ) -> Result<(DataType, MatchedTrailingBracket), ParserError> {
12773        let dialect = self.dialect;
12774        self.advance_token();
12775        let next_token = self.get_current_token();
12776        let next_token_index = self.get_current_index();
12777
12778        let mut trailing_bracket: MatchedTrailingBracket = false.into();
12779        let mut data = match &next_token.token {
12780            Token::Word(w) => match w.keyword {
12781                Keyword::BOOLEAN => Ok(DataType::Boolean),
12782                Keyword::BOOL => Ok(DataType::Bool),
12783                Keyword::FLOAT => {
12784                    let precision = self.parse_exact_number_optional_precision_scale()?;
12785
12786                    if self.parse_keyword(Keyword::UNSIGNED) {
12787                        Ok(DataType::FloatUnsigned(precision))
12788                    } else {
12789                        Ok(DataType::Float(precision))
12790                    }
12791                }
12792                Keyword::REAL => {
12793                    if self.parse_keyword(Keyword::UNSIGNED) {
12794                        Ok(DataType::RealUnsigned)
12795                    } else {
12796                        Ok(DataType::Real)
12797                    }
12798                }
12799                Keyword::FLOAT4 => Ok(DataType::Float4),
12800                Keyword::FLOAT32 => Ok(DataType::Float32),
12801                Keyword::FLOAT64 => Ok(DataType::Float64),
12802                Keyword::FLOAT8 => Ok(DataType::Float8),
12803                Keyword::DOUBLE => {
12804                    if self.parse_keyword(Keyword::PRECISION) {
12805                        if self.parse_keyword(Keyword::UNSIGNED) {
12806                            Ok(DataType::DoublePrecisionUnsigned)
12807                        } else {
12808                            Ok(DataType::DoublePrecision)
12809                        }
12810                    } else {
12811                        let precision = self.parse_exact_number_optional_precision_scale()?;
12812
12813                        if self.parse_keyword(Keyword::UNSIGNED) {
12814                            Ok(DataType::DoubleUnsigned(precision))
12815                        } else {
12816                            Ok(DataType::Double(precision))
12817                        }
12818                    }
12819                }
12820                Keyword::TINYINT => {
12821                    let optional_precision = self.parse_optional_precision();
12822                    if self.parse_keyword(Keyword::UNSIGNED) {
12823                        Ok(DataType::TinyIntUnsigned(optional_precision?))
12824                    } else {
12825                        if dialect.supports_data_type_signed_suffix() {
12826                            let _ = self.parse_keyword(Keyword::SIGNED);
12827                        }
12828                        Ok(DataType::TinyInt(optional_precision?))
12829                    }
12830                }
12831                Keyword::INT2 => {
12832                    let optional_precision = self.parse_optional_precision();
12833                    if self.parse_keyword(Keyword::UNSIGNED) {
12834                        Ok(DataType::Int2Unsigned(optional_precision?))
12835                    } else {
12836                        Ok(DataType::Int2(optional_precision?))
12837                    }
12838                }
12839                Keyword::SMALLINT => {
12840                    let optional_precision = self.parse_optional_precision();
12841                    if self.parse_keyword(Keyword::UNSIGNED) {
12842                        Ok(DataType::SmallIntUnsigned(optional_precision?))
12843                    } else {
12844                        if dialect.supports_data_type_signed_suffix() {
12845                            let _ = self.parse_keyword(Keyword::SIGNED);
12846                        }
12847                        Ok(DataType::SmallInt(optional_precision?))
12848                    }
12849                }
12850                Keyword::MEDIUMINT => {
12851                    let optional_precision = self.parse_optional_precision();
12852                    if self.parse_keyword(Keyword::UNSIGNED) {
12853                        Ok(DataType::MediumIntUnsigned(optional_precision?))
12854                    } else {
12855                        if dialect.supports_data_type_signed_suffix() {
12856                            let _ = self.parse_keyword(Keyword::SIGNED);
12857                        }
12858                        Ok(DataType::MediumInt(optional_precision?))
12859                    }
12860                }
12861                Keyword::INT => {
12862                    let optional_precision = self.parse_optional_precision();
12863                    if self.parse_keyword(Keyword::UNSIGNED) {
12864                        Ok(DataType::IntUnsigned(optional_precision?))
12865                    } else {
12866                        if dialect.supports_data_type_signed_suffix() {
12867                            let _ = self.parse_keyword(Keyword::SIGNED);
12868                        }
12869                        Ok(DataType::Int(optional_precision?))
12870                    }
12871                }
12872                Keyword::INT4 => {
12873                    let optional_precision = self.parse_optional_precision();
12874                    if self.parse_keyword(Keyword::UNSIGNED) {
12875                        Ok(DataType::Int4Unsigned(optional_precision?))
12876                    } else {
12877                        Ok(DataType::Int4(optional_precision?))
12878                    }
12879                }
12880                Keyword::INT8 => {
12881                    let optional_precision = self.parse_optional_precision();
12882                    if self.parse_keyword(Keyword::UNSIGNED) {
12883                        Ok(DataType::Int8Unsigned(optional_precision?))
12884                    } else {
12885                        Ok(DataType::Int8(optional_precision?))
12886                    }
12887                }
12888                Keyword::INT16 => Ok(DataType::Int16),
12889                Keyword::INT32 => Ok(DataType::Int32),
12890                Keyword::INT64 => Ok(DataType::Int64),
12891                Keyword::INT128 => Ok(DataType::Int128),
12892                Keyword::INT256 => Ok(DataType::Int256),
12893                Keyword::INTEGER => {
12894                    let optional_precision = self.parse_optional_precision();
12895                    if self.parse_keyword(Keyword::UNSIGNED) {
12896                        Ok(DataType::IntegerUnsigned(optional_precision?))
12897                    } else {
12898                        if dialect.supports_data_type_signed_suffix() {
12899                            let _ = self.parse_keyword(Keyword::SIGNED);
12900                        }
12901                        Ok(DataType::Integer(optional_precision?))
12902                    }
12903                }
12904                Keyword::BIGINT => {
12905                    let optional_precision = self.parse_optional_precision();
12906                    if self.parse_keyword(Keyword::UNSIGNED) {
12907                        Ok(DataType::BigIntUnsigned(optional_precision?))
12908                    } else {
12909                        if dialect.supports_data_type_signed_suffix() {
12910                            let _ = self.parse_keyword(Keyword::SIGNED);
12911                        }
12912                        Ok(DataType::BigInt(optional_precision?))
12913                    }
12914                }
12915                Keyword::HUGEINT => Ok(DataType::HugeInt),
12916                Keyword::UBIGINT => Ok(DataType::UBigInt),
12917                Keyword::UHUGEINT => Ok(DataType::UHugeInt),
12918                Keyword::USMALLINT => Ok(DataType::USmallInt),
12919                Keyword::UTINYINT => Ok(DataType::UTinyInt),
12920                Keyword::UINT8 => Ok(DataType::UInt8),
12921                Keyword::UINT16 => Ok(DataType::UInt16),
12922                Keyword::UINT32 => Ok(DataType::UInt32),
12923                Keyword::UINT64 => Ok(DataType::UInt64),
12924                Keyword::UINT128 => Ok(DataType::UInt128),
12925                Keyword::UINT256 => Ok(DataType::UInt256),
12926                Keyword::VARCHAR => Ok(DataType::Varchar(self.parse_optional_character_length()?)),
12927                Keyword::NVARCHAR => {
12928                    Ok(DataType::Nvarchar(self.parse_optional_character_length()?))
12929                }
12930                Keyword::CHARACTER => {
12931                    if self.parse_keyword(Keyword::VARYING) {
12932                        Ok(DataType::CharacterVarying(
12933                            self.parse_optional_character_length()?,
12934                        ))
12935                    } else if self.parse_keywords(&[Keyword::LARGE, Keyword::OBJECT]) {
12936                        Ok(DataType::CharacterLargeObject(
12937                            self.parse_optional_precision()?,
12938                        ))
12939                    } else {
12940                        Ok(DataType::Character(self.parse_optional_character_length()?))
12941                    }
12942                }
12943                Keyword::CHAR => {
12944                    if self.parse_keyword(Keyword::VARYING) {
12945                        Ok(DataType::CharVarying(
12946                            self.parse_optional_character_length()?,
12947                        ))
12948                    } else if self.parse_keywords(&[Keyword::LARGE, Keyword::OBJECT]) {
12949                        Ok(DataType::CharLargeObject(self.parse_optional_precision()?))
12950                    } else {
12951                        Ok(DataType::Char(self.parse_optional_character_length()?))
12952                    }
12953                }
12954                Keyword::CLOB => Ok(DataType::Clob(self.parse_optional_precision()?)),
12955                Keyword::BINARY => Ok(DataType::Binary(self.parse_optional_precision()?)),
12956                Keyword::VARBINARY => Ok(DataType::Varbinary(self.parse_optional_binary_length()?)),
12957                Keyword::BLOB => Ok(DataType::Blob(self.parse_optional_precision()?)),
12958                Keyword::TINYBLOB => Ok(DataType::TinyBlob),
12959                Keyword::MEDIUMBLOB => Ok(DataType::MediumBlob),
12960                Keyword::LONGBLOB => Ok(DataType::LongBlob),
12961                Keyword::LONG if self.dialect.supports_long_type_as_bigint() => {
12962                    Ok(DataType::BigInt(None))
12963                }
12964                Keyword::BYTES => Ok(DataType::Bytes(self.parse_optional_precision()?)),
12965                Keyword::BIT => {
12966                    if self.parse_keyword(Keyword::VARYING) {
12967                        Ok(DataType::BitVarying(self.parse_optional_precision()?))
12968                    } else {
12969                        Ok(DataType::Bit(self.parse_optional_precision()?))
12970                    }
12971                }
12972                Keyword::VARBIT => Ok(DataType::VarBit(self.parse_optional_precision()?)),
12973                Keyword::UUID => Ok(DataType::Uuid),
12974                Keyword::DATE => Ok(DataType::Date),
12975                Keyword::DATE32 => Ok(DataType::Date32),
12976                Keyword::DATETIME => Ok(DataType::Datetime(self.parse_optional_precision()?)),
12977                Keyword::DATETIME64 => {
12978                    self.prev_token();
12979                    let (precision, time_zone) = self.parse_datetime_64()?;
12980                    Ok(DataType::Datetime64(precision, time_zone))
12981                }
12982                Keyword::TIMESTAMP => {
12983                    let precision = self.parse_optional_precision()?;
12984                    let tz = if self.parse_keyword(Keyword::WITH) {
12985                        self.expect_keywords(&[Keyword::TIME, Keyword::ZONE])?;
12986                        TimezoneInfo::WithTimeZone
12987                    } else if self.parse_keyword(Keyword::WITHOUT) {
12988                        self.expect_keywords(&[Keyword::TIME, Keyword::ZONE])?;
12989                        TimezoneInfo::WithoutTimeZone
12990                    } else {
12991                        TimezoneInfo::None
12992                    };
12993                    Ok(DataType::Timestamp(precision, tz))
12994                }
12995                Keyword::TIMESTAMPTZ => Ok(DataType::Timestamp(
12996                    self.parse_optional_precision()?,
12997                    TimezoneInfo::Tz,
12998                )),
12999                Keyword::TIMESTAMP_NTZ => {
13000                    Ok(DataType::TimestampNtz(self.parse_optional_precision()?))
13001                }
13002                Keyword::TIME => {
13003                    let precision = self.parse_optional_precision()?;
13004                    let tz = if self.parse_keyword(Keyword::WITH) {
13005                        self.expect_keywords(&[Keyword::TIME, Keyword::ZONE])?;
13006                        TimezoneInfo::WithTimeZone
13007                    } else if self.parse_keyword(Keyword::WITHOUT) {
13008                        self.expect_keywords(&[Keyword::TIME, Keyword::ZONE])?;
13009                        TimezoneInfo::WithoutTimeZone
13010                    } else {
13011                        TimezoneInfo::None
13012                    };
13013                    Ok(DataType::Time(precision, tz))
13014                }
13015                Keyword::TIMETZ => Ok(DataType::Time(
13016                    self.parse_optional_precision()?,
13017                    TimezoneInfo::Tz,
13018                )),
13019                Keyword::INTERVAL => {
13020                    if self.dialect.supports_interval_options() {
13021                        let fields = self.maybe_parse_optional_interval_fields()?;
13022                        let precision = self.parse_optional_precision()?;
13023                        Ok(DataType::Interval { fields, precision })
13024                    } else {
13025                        Ok(DataType::Interval {
13026                            fields: None,
13027                            precision: None,
13028                        })
13029                    }
13030                }
13031                Keyword::JSON => Ok(DataType::JSON),
13032                Keyword::JSONB => Ok(DataType::JSONB),
13033                Keyword::REGCLASS => Ok(DataType::Regclass),
13034                Keyword::STRING => Ok(DataType::String(self.parse_optional_precision()?)),
13035                Keyword::FIXEDSTRING => {
13036                    self.expect_token(&Token::LParen)?;
13037                    let character_length = self.parse_literal_uint()?;
13038                    self.expect_token(&Token::RParen)?;
13039                    Ok(DataType::FixedString(character_length))
13040                }
13041                Keyword::TEXT => {
13042                    if let Some(modifiers) = self.parse_optional_type_modifiers()? {
13043                        Ok(DataType::Custom(
13044                            ObjectName::from(vec![Ident::new("TEXT")]),
13045                            modifiers,
13046                        ))
13047                    } else {
13048                        Ok(DataType::Text)
13049                    }
13050                }
13051                Keyword::TINYTEXT => Ok(DataType::TinyText),
13052                Keyword::MEDIUMTEXT => Ok(DataType::MediumText),
13053                Keyword::LONGTEXT => Ok(DataType::LongText),
13054                Keyword::BYTEA => Ok(DataType::Bytea),
13055                Keyword::NUMERIC => Ok(DataType::Numeric(
13056                    self.parse_exact_number_optional_precision_scale()?,
13057                )),
13058                Keyword::DECIMAL => {
13059                    let precision = self.parse_exact_number_optional_precision_scale()?;
13060
13061                    if self.parse_keyword(Keyword::UNSIGNED) {
13062                        Ok(DataType::DecimalUnsigned(precision))
13063                    } else {
13064                        Ok(DataType::Decimal(precision))
13065                    }
13066                }
13067                Keyword::DEC => {
13068                    let precision = self.parse_exact_number_optional_precision_scale()?;
13069
13070                    if self.parse_keyword(Keyword::UNSIGNED) {
13071                        Ok(DataType::DecUnsigned(precision))
13072                    } else {
13073                        Ok(DataType::Dec(precision))
13074                    }
13075                }
13076                Keyword::BIGNUMERIC => Ok(DataType::BigNumeric(
13077                    self.parse_exact_number_optional_precision_scale()?,
13078                )),
13079                Keyword::BIGDECIMAL => Ok(DataType::BigDecimal(
13080                    self.parse_exact_number_optional_precision_scale()?,
13081                )),
13082                Keyword::ENUM => Ok(DataType::Enum(self.parse_enum_values()?, None)),
13083                Keyword::ENUM8 => Ok(DataType::Enum(self.parse_enum_values()?, Some(8))),
13084                Keyword::ENUM16 => Ok(DataType::Enum(self.parse_enum_values()?, Some(16))),
13085                Keyword::SET => Ok(DataType::Set(self.parse_string_values()?)),
13086                Keyword::ARRAY => {
13087                    if self.dialect.supports_array_typedef_without_element_type() {
13088                        Ok(DataType::Array(ArrayElemTypeDef::None))
13089                    } else if dialect_of!(self is ClickHouseDialect) {
13090                        Ok(self.parse_sub_type(|internal_type| {
13091                            DataType::Array(ArrayElemTypeDef::Parenthesis(internal_type))
13092                        })?)
13093                    } else {
13094                        self.expect_token(&Token::Lt)?;
13095                        let (inside_type, _trailing_bracket) = self.parse_data_type_helper()?;
13096                        trailing_bracket = self.expect_closing_angle_bracket(_trailing_bracket)?;
13097                        Ok(DataType::Array(ArrayElemTypeDef::AngleBracket(Box::new(
13098                            inside_type,
13099                        ))))
13100                    }
13101                }
13102                Keyword::STRUCT if dialect_is!(dialect is DuckDbDialect) => {
13103                    self.prev_token();
13104                    let field_defs = self.parse_duckdb_struct_type_def()?;
13105                    Ok(DataType::Struct(field_defs, StructBracketKind::Parentheses))
13106                }
13107                Keyword::STRUCT if self.dialect.supports_struct_literal() => {
13108                    self.prev_token();
13109                    let (field_defs, _trailing_bracket) =
13110                        self.parse_struct_type_def(Self::parse_struct_field_def)?;
13111                    trailing_bracket = _trailing_bracket;
13112                    Ok(DataType::Struct(
13113                        field_defs,
13114                        StructBracketKind::AngleBrackets,
13115                    ))
13116                }
13117                Keyword::UNION if dialect_is!(dialect is DuckDbDialect | GenericDialect) => {
13118                    self.prev_token();
13119                    let fields = self.parse_union_type_def()?;
13120                    Ok(DataType::Union(fields))
13121                }
13122                Keyword::NULLABLE if dialect_is!(dialect is ClickHouseDialect | GenericDialect) => {
13123                    Ok(self.parse_sub_type(DataType::Nullable)?)
13124                }
13125                Keyword::LOWCARDINALITY if dialect_is!(dialect is ClickHouseDialect | GenericDialect) => {
13126                    Ok(self.parse_sub_type(DataType::LowCardinality)?)
13127                }
13128                Keyword::MAP if self.dialect.supports_map_literal_with_angle_brackets() => {
13129                    self.expect_token(&Token::Lt)?;
13130                    let key_data_type = self.parse_data_type()?;
13131                    self.expect_token(&Token::Comma)?;
13132                    let (value_data_type, _trailing_bracket) = self.parse_data_type_helper()?;
13133                    trailing_bracket = self.expect_closing_angle_bracket(_trailing_bracket)?;
13134                    Ok(DataType::Map(
13135                        Box::new(key_data_type),
13136                        Box::new(value_data_type),
13137                        MapBracketKind::AngleBrackets,
13138                    ))
13139                }
13140                Keyword::MAP if dialect_is!(dialect is ClickHouseDialect | GenericDialect) => {
13141                    self.prev_token();
13142                    let (key_data_type, value_data_type) = self.parse_click_house_map_def()?;
13143                    Ok(DataType::Map(
13144                        Box::new(key_data_type),
13145                        Box::new(value_data_type),
13146                        MapBracketKind::Parentheses,
13147                    ))
13148                }
13149                Keyword::NESTED if dialect_is!(dialect is ClickHouseDialect | GenericDialect) => {
13150                    self.expect_token(&Token::LParen)?;
13151                    let field_defs = self.parse_comma_separated(Parser::parse_column_def)?;
13152                    self.expect_token(&Token::RParen)?;
13153                    Ok(DataType::Nested(field_defs))
13154                }
13155                Keyword::TUPLE if dialect_is!(dialect is ClickHouseDialect | GenericDialect) => {
13156                    self.prev_token();
13157                    let field_defs = self.parse_click_house_tuple_def()?;
13158                    Ok(DataType::Tuple(field_defs))
13159                }
13160                Keyword::TRIGGER => Ok(DataType::Trigger),
13161                Keyword::ANY if self.peek_keyword(Keyword::TYPE) => {
13162                    let _ = self.parse_keyword(Keyword::TYPE);
13163                    Ok(DataType::AnyType)
13164                }
13165                Keyword::TABLE => {
13166                    // an LParen after the TABLE keyword indicates that table columns are being defined
13167                    // whereas no LParen indicates an anonymous table expression will be returned
13168                    if self.peek_token_ref().token == Token::LParen {
13169                        let columns = self.parse_returns_table_columns()?;
13170                        Ok(DataType::Table(Some(columns)))
13171                    } else {
13172                        Ok(DataType::Table(None))
13173                    }
13174                }
13175                Keyword::SIGNED => {
13176                    if self.parse_keyword(Keyword::INTEGER) {
13177                        Ok(DataType::SignedInteger)
13178                    } else {
13179                        Ok(DataType::Signed)
13180                    }
13181                }
13182                Keyword::UNSIGNED => {
13183                    if self.parse_keyword(Keyword::INTEGER) {
13184                        Ok(DataType::UnsignedInteger)
13185                    } else {
13186                        Ok(DataType::Unsigned)
13187                    }
13188                }
13189                Keyword::TSVECTOR if dialect_is!(dialect is PostgreSqlDialect | GenericDialect) => {
13190                    Ok(DataType::TsVector)
13191                }
13192                Keyword::TSQUERY if dialect_is!(dialect is PostgreSqlDialect | GenericDialect) => {
13193                    Ok(DataType::TsQuery)
13194                }
13195                _ => {
13196                    self.prev_token();
13197                    let type_name = self.parse_object_name(false)?;
13198                    if let Some(modifiers) = self.parse_optional_type_modifiers()? {
13199                        Ok(DataType::Custom(type_name, modifiers))
13200                    } else {
13201                        Ok(DataType::Custom(type_name, vec![]))
13202                    }
13203                }
13204            },
13205            _ => self.expected_at("a data type name", next_token_index),
13206        }?;
13207
13208        if self.dialect.supports_array_typedef_with_brackets() {
13209            while self.consume_token(&Token::LBracket) {
13210                // Parse optional array data type size
13211                let size = self.maybe_parse(|p| p.parse_literal_uint())?;
13212                self.expect_token(&Token::RBracket)?;
13213                data = DataType::Array(ArrayElemTypeDef::SquareBracket(Box::new(data), size))
13214            }
13215        }
13216        Ok((data, trailing_bracket))
13217    }
13218
13219    fn parse_returns_table_column(&mut self) -> Result<ColumnDef, ParserError> {
13220        self.parse_column_def()
13221    }
13222
13223    fn parse_returns_table_columns(&mut self) -> Result<Vec<ColumnDef>, ParserError> {
13224        self.expect_token(&Token::LParen)?;
13225        let columns = self.parse_comma_separated(Parser::parse_returns_table_column)?;
13226        self.expect_token(&Token::RParen)?;
13227        Ok(columns)
13228    }
13229
13230    /// Parse a parenthesized, comma-separated list of single-quoted strings.
13231    pub fn parse_string_values(&mut self) -> Result<Vec<String>, ParserError> {
13232        self.expect_token(&Token::LParen)?;
13233        let mut values = Vec::new();
13234        loop {
13235            let next_token = self.next_token();
13236            match next_token.token {
13237                Token::SingleQuotedString(value) => values.push(value),
13238                _ => self.expected("a string", next_token)?,
13239            }
13240            let next_token = self.next_token();
13241            match next_token.token {
13242                Token::Comma => (),
13243                Token::RParen => break,
13244                _ => self.expected(", or }", next_token)?,
13245            }
13246        }
13247        Ok(values)
13248    }
13249
13250    /// Strictly parse `identifier AS identifier`
13251    pub fn parse_identifier_with_alias(&mut self) -> Result<IdentWithAlias, ParserError> {
13252        let ident = self.parse_identifier()?;
13253        self.expect_keyword_is(Keyword::AS)?;
13254        let alias = self.parse_identifier()?;
13255        Ok(IdentWithAlias { ident, alias })
13256    }
13257
13258    /// Parse `identifier [AS] identifier` where the AS keyword is optional
13259    fn parse_identifier_with_optional_alias(&mut self) -> Result<IdentWithAlias, ParserError> {
13260        let ident = self.parse_identifier()?;
13261        let _after_as = self.parse_keyword(Keyword::AS);
13262        let alias = self.parse_identifier()?;
13263        Ok(IdentWithAlias { ident, alias })
13264    }
13265
13266    /// Parse comma-separated list of parenthesized queries for pipe operators
13267    fn parse_pipe_operator_queries(&mut self) -> Result<Vec<Query>, ParserError> {
13268        self.parse_comma_separated(|parser| {
13269            parser.expect_token(&Token::LParen)?;
13270            let query = parser.parse_query()?;
13271            parser.expect_token(&Token::RParen)?;
13272            Ok(*query)
13273        })
13274    }
13275
13276    /// Parse set quantifier for pipe operators that require DISTINCT. E.g. INTERSECT and EXCEPT
13277    fn parse_distinct_required_set_quantifier(
13278        &mut self,
13279        operator_name: &str,
13280    ) -> Result<SetQuantifier, ParserError> {
13281        let quantifier = self.parse_set_quantifier(&Some(SetOperator::Intersect));
13282        match quantifier {
13283            SetQuantifier::Distinct | SetQuantifier::DistinctByName => Ok(quantifier),
13284            _ => Err(ParserError::ParserError(format!(
13285                "{operator_name} pipe operator requires DISTINCT modifier",
13286            ))),
13287        }
13288    }
13289
13290    /// Parse optional identifier alias (with or without AS keyword)
13291    fn parse_identifier_optional_alias(&mut self) -> Result<Option<Ident>, ParserError> {
13292        if self.parse_keyword(Keyword::AS) {
13293            Ok(Some(self.parse_identifier()?))
13294        } else {
13295            // Check if the next token is an identifier (implicit alias)
13296            self.maybe_parse(|parser| parser.parse_identifier())
13297        }
13298    }
13299
13300    /// Optionally parses an alias for a select list item
13301    fn maybe_parse_select_item_alias(&mut self) -> Result<Option<Ident>, ParserError> {
13302        fn validator(explicit: bool, kw: &Keyword, parser: &mut Parser) -> bool {
13303            parser.dialect.is_select_item_alias(explicit, kw, parser)
13304        }
13305        self.parse_optional_alias_inner(None, validator)
13306    }
13307
13308    /// Optionally parses an alias for a table like in `... FROM generate_series(1, 10) AS t (col)`.
13309    /// In this case, the alias is allowed to optionally name the columns in the table, in
13310    /// addition to the table itself.
13311    pub fn maybe_parse_table_alias(&mut self) -> Result<Option<TableAlias>, ParserError> {
13312        fn validator(explicit: bool, kw: &Keyword, parser: &mut Parser) -> bool {
13313            parser.dialect.is_table_factor_alias(explicit, kw, parser)
13314        }
13315        let explicit = self.peek_keyword(Keyword::AS);
13316        match self.parse_optional_alias_inner(None, validator)? {
13317            Some(name) => {
13318                let columns = self.parse_table_alias_column_defs()?;
13319                let at = if self.dialect.supports_partiql() && self.parse_keyword(Keyword::AT) {
13320                    Some(self.parse_identifier()?)
13321                } else {
13322                    None
13323                };
13324                Ok(Some(TableAlias {
13325                    explicit,
13326                    name,
13327                    columns,
13328                    at,
13329                }))
13330            }
13331            None => Ok(None),
13332        }
13333    }
13334
13335    fn parse_table_index_hints(&mut self) -> Result<Vec<TableIndexHints>, ParserError> {
13336        let mut hints = vec![];
13337        while let Some(hint_type) =
13338            self.parse_one_of_keywords(&[Keyword::USE, Keyword::IGNORE, Keyword::FORCE])
13339        {
13340            let hint_type = match hint_type {
13341                Keyword::USE => TableIndexHintType::Use,
13342                Keyword::IGNORE => TableIndexHintType::Ignore,
13343                Keyword::FORCE => TableIndexHintType::Force,
13344                _ => {
13345                    return self.expected_ref(
13346                        "expected to match USE/IGNORE/FORCE keyword",
13347                        self.peek_token_ref(),
13348                    )
13349                }
13350            };
13351            let index_type = match self.parse_one_of_keywords(&[Keyword::INDEX, Keyword::KEY]) {
13352                Some(Keyword::INDEX) => TableIndexType::Index,
13353                Some(Keyword::KEY) => TableIndexType::Key,
13354                _ => {
13355                    return self
13356                        .expected_ref("expected to match INDEX/KEY keyword", self.peek_token_ref())
13357                }
13358            };
13359            let for_clause = if self.parse_keyword(Keyword::FOR) {
13360                let clause = if self.parse_keyword(Keyword::JOIN) {
13361                    TableIndexHintForClause::Join
13362                } else if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
13363                    TableIndexHintForClause::OrderBy
13364                } else if self.parse_keywords(&[Keyword::GROUP, Keyword::BY]) {
13365                    TableIndexHintForClause::GroupBy
13366                } else {
13367                    return self.expected_ref(
13368                        "expected to match FOR/ORDER BY/GROUP BY table hint in for clause",
13369                        self.peek_token_ref(),
13370                    );
13371                };
13372                Some(clause)
13373            } else {
13374                None
13375            };
13376
13377            self.expect_token(&Token::LParen)?;
13378            let index_names = if self.peek_token_ref().token != Token::RParen {
13379                self.parse_comma_separated(Parser::parse_identifier)?
13380            } else {
13381                vec![]
13382            };
13383            self.expect_token(&Token::RParen)?;
13384            hints.push(TableIndexHints {
13385                hint_type,
13386                index_type,
13387                for_clause,
13388                index_names,
13389            });
13390        }
13391        Ok(hints)
13392    }
13393
13394    /// Wrapper for parse_optional_alias_inner, left for backwards-compatibility
13395    /// but new flows should use the context-specific methods such as `maybe_parse_select_item_alias`
13396    /// and `maybe_parse_table_alias`.
13397    pub fn parse_optional_alias(
13398        &mut self,
13399        reserved_kwds: &[Keyword],
13400    ) -> Result<Option<Ident>, ParserError> {
13401        fn validator(_explicit: bool, _kw: &Keyword, _parser: &mut Parser) -> bool {
13402            false
13403        }
13404        self.parse_optional_alias_inner(Some(reserved_kwds), validator)
13405    }
13406
13407    /// Parses an optional alias after a SQL element such as a select list item
13408    /// or a table name.
13409    ///
13410    /// This method accepts an optional list of reserved keywords or a function
13411    /// to call to validate if a keyword should be parsed as an alias, to allow
13412    /// callers to customize the parsing logic based on their context.
13413    fn parse_optional_alias_inner<F>(
13414        &mut self,
13415        reserved_kwds: Option<&[Keyword]>,
13416        validator: F,
13417    ) -> Result<Option<Ident>, ParserError>
13418    where
13419        F: Fn(bool, &Keyword, &mut Parser) -> bool,
13420    {
13421        let after_as = self.parse_keyword(Keyword::AS);
13422
13423        let next_token = self.next_token();
13424        match next_token.token {
13425            // Accepts a keyword as an alias if the AS keyword explicitly indicate an alias or if the
13426            // caller provided a list of reserved keywords and the keyword is not on that list.
13427            Token::Word(w)
13428                if reserved_kwds.is_some()
13429                    && (after_as || reserved_kwds.is_some_and(|x| !x.contains(&w.keyword))) =>
13430            {
13431                Ok(Some(w.into_ident(next_token.span)))
13432            }
13433            // Accepts a keyword as alias based on the caller's context, such as to what SQL element
13434            // this word is a potential alias of using the validator call-back. This allows for
13435            // dialect-specific logic.
13436            Token::Word(w) if validator(after_as, &w.keyword, self) => {
13437                Ok(Some(w.into_ident(next_token.span)))
13438            }
13439            // For backwards-compatibility, we accept quoted strings as aliases regardless of the context.
13440            Token::SingleQuotedString(s) => Ok(Some(Ident::with_quote('\'', s))),
13441            Token::DoubleQuotedString(s) => Ok(Some(Ident::with_quote('\"', s))),
13442            _ => {
13443                if after_as {
13444                    return self.expected("an identifier after AS", next_token);
13445                }
13446                self.prev_token();
13447                Ok(None) // no alias found
13448            }
13449        }
13450    }
13451
13452    /// Parse an optional `GROUP BY` clause, returning `Some(GroupByExpr)` when present.
13453    pub fn parse_optional_group_by(&mut self) -> Result<Option<GroupByExpr>, ParserError> {
13454        if self.parse_keywords(&[Keyword::GROUP, Keyword::BY]) {
13455            let expressions = if self.parse_keyword(Keyword::ALL) {
13456                None
13457            } else {
13458                Some(self.parse_comma_separated(Parser::parse_group_by_expr)?)
13459            };
13460
13461            let mut modifiers = vec![];
13462            if self.dialect.supports_group_by_with_modifier() {
13463                loop {
13464                    if !self.parse_keyword(Keyword::WITH) {
13465                        break;
13466                    }
13467                    let keyword = self.expect_one_of_keywords(&[
13468                        Keyword::ROLLUP,
13469                        Keyword::CUBE,
13470                        Keyword::TOTALS,
13471                    ])?;
13472                    modifiers.push(match keyword {
13473                        Keyword::ROLLUP => GroupByWithModifier::Rollup,
13474                        Keyword::CUBE => GroupByWithModifier::Cube,
13475                        Keyword::TOTALS => GroupByWithModifier::Totals,
13476                        _ => {
13477                            return parser_err!(
13478                                "BUG: expected to match GroupBy modifier keyword",
13479                                self.peek_token_ref().span.start
13480                            )
13481                        }
13482                    });
13483                }
13484            }
13485            if self.parse_keywords(&[Keyword::GROUPING, Keyword::SETS]) {
13486                self.expect_token(&Token::LParen)?;
13487                let result = self.parse_comma_separated(|p| {
13488                    if p.peek_token_ref().token == Token::LParen {
13489                        p.parse_tuple(true, true)
13490                    } else {
13491                        Ok(vec![p.parse_expr()?])
13492                    }
13493                })?;
13494                self.expect_token(&Token::RParen)?;
13495                modifiers.push(GroupByWithModifier::GroupingSets(Expr::GroupingSets(
13496                    result,
13497                )));
13498            };
13499            let group_by = match expressions {
13500                None => GroupByExpr::All(modifiers),
13501                Some(exprs) => GroupByExpr::Expressions(exprs, modifiers),
13502            };
13503            Ok(Some(group_by))
13504        } else {
13505            Ok(None)
13506        }
13507    }
13508
13509    /// Parse an optional `ORDER BY` clause, returning `Some(OrderBy)` when present.
13510    pub fn parse_optional_order_by(&mut self) -> Result<Option<OrderBy>, ParserError> {
13511        if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
13512            let order_by =
13513                if self.dialect.supports_order_by_all() && self.parse_keyword(Keyword::ALL) {
13514                    let order_by_options = self.parse_order_by_options()?;
13515                    OrderBy {
13516                        kind: OrderByKind::All(order_by_options),
13517                        interpolate: None,
13518                    }
13519                } else {
13520                    let exprs = self.parse_comma_separated(Parser::parse_order_by_expr)?;
13521                    let interpolate = if self.dialect.supports_interpolate() {
13522                        self.parse_interpolations()?
13523                    } else {
13524                        None
13525                    };
13526                    OrderBy {
13527                        kind: OrderByKind::Expressions(exprs),
13528                        interpolate,
13529                    }
13530                };
13531            Ok(Some(order_by))
13532        } else {
13533            Ok(None)
13534        }
13535    }
13536
13537    fn parse_optional_limit_clause(&mut self) -> Result<Option<LimitClause>, ParserError> {
13538        let mut offset = if self.parse_keyword(Keyword::OFFSET) {
13539            Some(self.parse_offset()?)
13540        } else {
13541            None
13542        };
13543
13544        let (limit, limit_by) = if self.parse_keyword(Keyword::LIMIT) {
13545            let expr = self.parse_limit()?;
13546
13547            if self.dialect.supports_limit_comma()
13548                && offset.is_none()
13549                && expr.is_some() // ALL not supported with comma
13550                && self.consume_token(&Token::Comma)
13551            {
13552                let offset = expr.ok_or_else(|| {
13553                    ParserError::ParserError(
13554                        "Missing offset for LIMIT <offset>, <limit>".to_string(),
13555                    )
13556                })?;
13557                return Ok(Some(LimitClause::OffsetCommaLimit {
13558                    offset,
13559                    limit: self.parse_expr()?,
13560                }));
13561            }
13562
13563            let limit_by = if self.dialect.supports_limit_by() && self.parse_keyword(Keyword::BY) {
13564                Some(self.parse_comma_separated(Parser::parse_expr)?)
13565            } else {
13566                None
13567            };
13568
13569            (Some(expr), limit_by)
13570        } else {
13571            (None, None)
13572        };
13573
13574        if offset.is_none() && limit.is_some() && self.parse_keyword(Keyword::OFFSET) {
13575            offset = Some(self.parse_offset()?);
13576        }
13577
13578        if offset.is_some() || (limit.is_some() && limit != Some(None)) || limit_by.is_some() {
13579            Ok(Some(LimitClause::LimitOffset {
13580                limit: limit.unwrap_or_default(),
13581                offset,
13582                limit_by: limit_by.unwrap_or_default(),
13583            }))
13584        } else {
13585            Ok(None)
13586        }
13587    }
13588
13589    /// Parse a table object for insertion
13590    /// e.g. `some_database.some_table` or `FUNCTION some_table_func(...)`
13591    pub fn parse_table_object(&mut self) -> Result<TableObject, ParserError> {
13592        if self.dialect.supports_insert_table_function() && self.parse_keyword(Keyword::FUNCTION) {
13593            let fn_name = self.parse_object_name(false)?;
13594            self.parse_function_call(fn_name)
13595                .map(TableObject::TableFunction)
13596        } else if self.dialect.supports_insert_table_query() && self.peek_subquery_or_cte_start() {
13597            self.parse_parenthesized(|p| p.parse_query())
13598                .map(TableObject::TableQuery)
13599        } else {
13600            self.parse_object_name(false).map(TableObject::TableName)
13601        }
13602    }
13603
13604    /// Parse a possibly qualified, possibly quoted identifier, e.g.
13605    /// `foo` or `myschema."table"
13606    ///
13607    /// The `in_table_clause` parameter indicates whether the object name is a table in a FROM, JOIN,
13608    /// or similar table clause. Currently, this is used only to support unquoted hyphenated identifiers
13609    /// in this context on BigQuery.
13610    pub fn parse_object_name(&mut self, in_table_clause: bool) -> Result<ObjectName, ParserError> {
13611        self.parse_object_name_inner(in_table_clause, false)
13612    }
13613
13614    /// Parse a possibly qualified, possibly quoted identifier, e.g.
13615    /// `foo` or `myschema."table"
13616    ///
13617    /// The `in_table_clause` parameter indicates whether the object name is a table in a FROM, JOIN,
13618    /// or similar table clause. Currently, this is used only to support unquoted hyphenated identifiers
13619    /// in this context on BigQuery.
13620    ///
13621    /// The `allow_wildcards` parameter indicates whether to allow for wildcards in the object name
13622    /// e.g. *, *.*, `foo`.*, or "foo"."bar"
13623    fn parse_object_name_inner(
13624        &mut self,
13625        in_table_clause: bool,
13626        allow_wildcards: bool,
13627    ) -> Result<ObjectName, ParserError> {
13628        let mut parts = vec![];
13629        if dialect_of!(self is BigQueryDialect) && in_table_clause {
13630            loop {
13631                let (ident, end_with_period) = self.parse_unquoted_hyphenated_identifier()?;
13632                parts.push(ObjectNamePart::Identifier(ident));
13633                if !self.consume_token(&Token::Period) && !end_with_period {
13634                    break;
13635                }
13636            }
13637        } else {
13638            loop {
13639                if allow_wildcards && self.peek_token_ref().token == Token::Mul {
13640                    let span = self.next_token().span;
13641                    parts.push(ObjectNamePart::Identifier(Ident {
13642                        value: Token::Mul.to_string(),
13643                        quote_style: None,
13644                        span,
13645                    }));
13646                } else if dialect_of!(self is BigQueryDialect) && in_table_clause {
13647                    let (ident, end_with_period) = self.parse_unquoted_hyphenated_identifier()?;
13648                    parts.push(ObjectNamePart::Identifier(ident));
13649                    if !self.consume_token(&Token::Period) && !end_with_period {
13650                        break;
13651                    }
13652                } else if self.dialect.supports_object_name_double_dot_notation()
13653                    && parts.len() == 1
13654                    && matches!(self.peek_token_ref().token, Token::Period)
13655                {
13656                    // Empty string here means default schema
13657                    parts.push(ObjectNamePart::Identifier(Ident::new("")));
13658                } else {
13659                    let ident = self.parse_identifier()?;
13660                    let part = if self
13661                        .dialect
13662                        .is_identifier_generating_function_name(&ident, &parts)
13663                    {
13664                        self.expect_token(&Token::LParen)?;
13665                        let args: Vec<FunctionArg> =
13666                            self.parse_comma_separated0(Self::parse_function_args, Token::RParen)?;
13667                        self.expect_token(&Token::RParen)?;
13668                        ObjectNamePart::Function(ObjectNamePartFunction { name: ident, args })
13669                    } else {
13670                        ObjectNamePart::Identifier(ident)
13671                    };
13672                    parts.push(part);
13673                }
13674
13675                if !self.consume_token(&Token::Period) {
13676                    break;
13677                }
13678            }
13679        }
13680
13681        // BigQuery accepts any number of quoted identifiers of a table name.
13682        // https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical#quoted_identifiers
13683        if dialect_of!(self is BigQueryDialect)
13684            && parts.iter().any(|part| {
13685                part.as_ident()
13686                    .is_some_and(|ident| ident.value.contains('.'))
13687            })
13688        {
13689            parts = parts
13690                .into_iter()
13691                .flat_map(|part| match part.as_ident() {
13692                    Some(ident) => ident
13693                        .value
13694                        .split('.')
13695                        .map(|value| {
13696                            ObjectNamePart::Identifier(Ident {
13697                                value: value.into(),
13698                                quote_style: ident.quote_style,
13699                                span: ident.span,
13700                            })
13701                        })
13702                        .collect::<Vec<_>>(),
13703                    None => vec![part],
13704                })
13705                .collect()
13706        }
13707
13708        Ok(ObjectName(parts))
13709    }
13710
13711    /// Parse identifiers
13712    pub fn parse_identifiers(&mut self) -> Result<Vec<Ident>, ParserError> {
13713        let mut idents = vec![];
13714        loop {
13715            let token = self.peek_token_ref();
13716            match &token.token {
13717                Token::Word(w) => {
13718                    idents.push(w.to_ident(token.span));
13719                }
13720                Token::EOF | Token::Eq | Token::SemiColon | Token::VerticalBarRightAngleBracket => {
13721                    break
13722                }
13723                _ => {}
13724            }
13725            self.advance_token();
13726        }
13727        Ok(idents)
13728    }
13729
13730    /// Parse identifiers of form ident1[.identN]*
13731    ///
13732    /// Similar in functionality to [parse_identifiers], with difference
13733    /// being this function is much more strict about parsing a valid multipart identifier, not
13734    /// allowing extraneous tokens to be parsed, otherwise it fails.
13735    ///
13736    /// For example:
13737    ///
13738    /// ```rust
13739    /// use sqlparser::ast::Ident;
13740    /// use sqlparser::dialect::GenericDialect;
13741    /// use sqlparser::parser::Parser;
13742    ///
13743    /// let dialect = GenericDialect {};
13744    /// let expected = vec![Ident::new("one"), Ident::new("two")];
13745    ///
13746    /// // expected usage
13747    /// let sql = "one.two";
13748    /// let mut parser = Parser::new(&dialect).try_with_sql(sql).unwrap();
13749    /// let actual = parser.parse_multipart_identifier().unwrap();
13750    /// assert_eq!(&actual, &expected);
13751    ///
13752    /// // parse_identifiers is more loose on what it allows, parsing successfully
13753    /// let sql = "one + two";
13754    /// let mut parser = Parser::new(&dialect).try_with_sql(sql).unwrap();
13755    /// let actual = parser.parse_identifiers().unwrap();
13756    /// assert_eq!(&actual, &expected);
13757    ///
13758    /// // expected to strictly fail due to + separator
13759    /// let sql = "one + two";
13760    /// let mut parser = Parser::new(&dialect).try_with_sql(sql).unwrap();
13761    /// let actual = parser.parse_multipart_identifier().unwrap_err();
13762    /// assert_eq!(
13763    ///     actual.to_string(),
13764    ///     "sql parser error: Unexpected token in identifier: +"
13765    /// );
13766    /// ```
13767    ///
13768    /// [parse_identifiers]: Parser::parse_identifiers
13769    pub fn parse_multipart_identifier(&mut self) -> Result<Vec<Ident>, ParserError> {
13770        let mut idents = vec![];
13771
13772        // expecting at least one word for identifier
13773        let next_token = self.next_token();
13774        match next_token.token {
13775            Token::Word(w) => idents.push(w.into_ident(next_token.span)),
13776            Token::EOF => {
13777                return Err(ParserError::ParserError(
13778                    "Empty input when parsing identifier".to_string(),
13779                ))?
13780            }
13781            token => {
13782                return Err(ParserError::ParserError(format!(
13783                    "Unexpected token in identifier: {token}"
13784                )))?
13785            }
13786        };
13787
13788        // parse optional next parts if exist
13789        loop {
13790            match self.next_token().token {
13791                // ensure that optional period is succeeded by another identifier
13792                Token::Period => {
13793                    let next_token = self.next_token();
13794                    match next_token.token {
13795                        Token::Word(w) => idents.push(w.into_ident(next_token.span)),
13796                        Token::EOF => {
13797                            return Err(ParserError::ParserError(
13798                                "Trailing period in identifier".to_string(),
13799                            ))?
13800                        }
13801                        token => {
13802                            return Err(ParserError::ParserError(format!(
13803                                "Unexpected token following period in identifier: {token}"
13804                            )))?
13805                        }
13806                    }
13807                }
13808                Token::EOF => break,
13809                token => {
13810                    return Err(ParserError::ParserError(format!(
13811                        "Unexpected token in identifier: {token}"
13812                    )))?;
13813                }
13814            }
13815        }
13816
13817        Ok(idents)
13818    }
13819
13820    /// Parse a simple one-word identifier (possibly quoted, possibly a keyword)
13821    pub fn parse_identifier(&mut self) -> Result<Ident, ParserError> {
13822        let next_token = self.next_token();
13823        match next_token.token {
13824            Token::Word(w) => Ok(w.into_ident(next_token.span)),
13825            Token::SingleQuotedString(s) => Ok(Ident::with_quote('\'', s)),
13826            Token::DoubleQuotedString(s) => Ok(Ident::with_quote('\"', s)),
13827            _ => self.expected("identifier", next_token),
13828        }
13829    }
13830
13831    /// On BigQuery, hyphens are permitted in unquoted identifiers inside of a FROM or
13832    /// TABLE clause.
13833    ///
13834    /// The first segment must be an ordinary unquoted identifier, e.g. it must not start
13835    /// with a digit. Subsequent segments are either must either be valid identifiers or
13836    /// integers, e.g. foo-123 is allowed, but foo-123a is not.
13837    ///
13838    /// [BigQuery-lexical](https://cloud.google.com/bigquery/docs/reference/standard-sql/lexical)
13839    ///
13840    /// Return a tuple of the identifier and a boolean indicating it ends with a period.
13841    fn parse_unquoted_hyphenated_identifier(&mut self) -> Result<(Ident, bool), ParserError> {
13842        match self.peek_token().token {
13843            Token::Word(w) => {
13844                let quote_style_is_none = w.quote_style.is_none();
13845                let mut requires_whitespace = false;
13846                let mut ident = w.into_ident(self.next_token().span);
13847                if quote_style_is_none {
13848                    while matches!(self.peek_token_no_skip().token, Token::Minus) {
13849                        self.next_token();
13850                        ident.value.push('-');
13851
13852                        let token = self
13853                            .next_token_no_skip()
13854                            .cloned()
13855                            .unwrap_or(TokenWithSpan::wrap(Token::EOF));
13856                        requires_whitespace = match token.token {
13857                            Token::Word(next_word) if next_word.quote_style.is_none() => {
13858                                ident.value.push_str(&next_word.value);
13859                                false
13860                            }
13861                            Token::Number(s, false) => {
13862                                // A number token can represent a decimal value ending with a period, e.g., `Number('123.')`.
13863                                // However, for an [ObjectName], it is part of a hyphenated identifier, e.g., `foo-123.bar`.
13864                                //
13865                                // If a number token is followed by a period, it is part of an [ObjectName].
13866                                // Return the identifier with `true` if the number token is followed by a period, indicating that
13867                                // parsing should continue for the next part of the hyphenated identifier.
13868                                if s.ends_with('.') {
13869                                    let Some(s) = s.split('.').next().filter(|s| {
13870                                        !s.is_empty() && s.chars().all(|c| c.is_ascii_digit())
13871                                    }) else {
13872                                        return self.expected(
13873                                            "continuation of hyphenated identifier",
13874                                            TokenWithSpan::new(Token::Number(s, false), token.span),
13875                                        );
13876                                    };
13877                                    ident.value.push_str(s);
13878                                    return Ok((ident, true));
13879                                } else {
13880                                    ident.value.push_str(&s);
13881                                }
13882                                // If next token is period, then it is part of an ObjectName and we don't expect whitespace
13883                                // after the number.
13884                                !matches!(self.peek_token_ref().token, Token::Period)
13885                            }
13886                            _ => {
13887                                return self
13888                                    .expected("continuation of hyphenated identifier", token);
13889                            }
13890                        }
13891                    }
13892
13893                    // If the last segment was a number, we must check that it's followed by whitespace,
13894                    // otherwise foo-123a will be parsed as `foo-123` with the alias `a`.
13895                    if requires_whitespace {
13896                        let token = self.next_token();
13897                        if !matches!(token.token, Token::EOF | Token::Whitespace(_)) {
13898                            return self
13899                                .expected("whitespace following hyphenated identifier", token);
13900                        }
13901                    }
13902                }
13903                Ok((ident, false))
13904            }
13905            _ => Ok((self.parse_identifier()?, false)),
13906        }
13907    }
13908
13909    /// Parses a parenthesized, comma-separated list of column definitions within a view.
13910    fn parse_view_columns(&mut self) -> Result<Vec<ViewColumnDef>, ParserError> {
13911        if self.consume_token(&Token::LParen) {
13912            if self.peek_token_ref().token == Token::RParen {
13913                self.next_token();
13914                Ok(vec![])
13915            } else {
13916                let cols = self.parse_comma_separated_with_trailing_commas(
13917                    Parser::parse_view_column,
13918                    self.dialect.supports_column_definition_trailing_commas(),
13919                    Self::is_reserved_for_column_alias,
13920                )?;
13921                self.expect_token(&Token::RParen)?;
13922                Ok(cols)
13923            }
13924        } else {
13925            Ok(vec![])
13926        }
13927    }
13928
13929    /// Parses a column definition within a view.
13930    fn parse_view_column(&mut self) -> Result<ViewColumnDef, ParserError> {
13931        let name = self.parse_identifier()?;
13932        let options = self.parse_view_column_options()?;
13933        let data_type = if dialect_of!(self is ClickHouseDialect) {
13934            Some(self.parse_data_type()?)
13935        } else {
13936            None
13937        };
13938        Ok(ViewColumnDef {
13939            name,
13940            data_type,
13941            options,
13942        })
13943    }
13944
13945    fn parse_view_column_options(&mut self) -> Result<Option<ColumnOptions>, ParserError> {
13946        let mut options = Vec::new();
13947        loop {
13948            let option = self.parse_optional_column_option()?;
13949            if let Some(option) = option {
13950                options.push(option);
13951            } else {
13952                break;
13953            }
13954        }
13955        if options.is_empty() {
13956            Ok(None)
13957        } else if self.dialect.supports_space_separated_column_options() {
13958            Ok(Some(ColumnOptions::SpaceSeparated(options)))
13959        } else {
13960            Ok(Some(ColumnOptions::CommaSeparated(options)))
13961        }
13962    }
13963
13964    /// Parses a parenthesized comma-separated list of unqualified, possibly quoted identifiers.
13965    /// For example: `(col1, "col 2", ...)`
13966    pub fn parse_parenthesized_column_list(
13967        &mut self,
13968        optional: IsOptional,
13969        allow_empty: bool,
13970    ) -> Result<Vec<Ident>, ParserError> {
13971        self.parse_parenthesized_column_list_inner(optional, allow_empty, |p| p.parse_identifier())
13972    }
13973
13974    /// Parse a parenthesized list of compound identifiers as expressions.
13975    pub fn parse_parenthesized_compound_identifier_list(
13976        &mut self,
13977        optional: IsOptional,
13978        allow_empty: bool,
13979    ) -> Result<Vec<Expr>, ParserError> {
13980        self.parse_parenthesized_column_list_inner(optional, allow_empty, |p| {
13981            Ok(Expr::CompoundIdentifier(
13982                p.parse_period_separated(|p| p.parse_identifier())?,
13983            ))
13984        })
13985    }
13986
13987    /// Parses a parenthesized comma-separated list of index columns, which can be arbitrary
13988    /// expressions with ordering information (and an opclass in some dialects).
13989    fn parse_parenthesized_index_column_list(&mut self) -> Result<Vec<IndexColumn>, ParserError> {
13990        self.parse_parenthesized_column_list_inner(Mandatory, false, |p| {
13991            p.parse_create_index_expr()
13992        })
13993    }
13994
13995    /// Parses a parenthesized comma-separated list of qualified, possibly quoted identifiers.
13996    /// For example: `(db1.sc1.tbl1.col1, db1.sc1.tbl1."col 2", ...)`
13997    pub fn parse_parenthesized_qualified_column_list(
13998        &mut self,
13999        optional: IsOptional,
14000        allow_empty: bool,
14001    ) -> Result<Vec<ObjectName>, ParserError> {
14002        self.parse_parenthesized_column_list_inner(optional, allow_empty, |p| {
14003            p.parse_object_name(true)
14004        })
14005    }
14006
14007    /// Parses a parenthesized comma-separated list of columns using
14008    /// the provided function to parse each element.
14009    fn parse_parenthesized_column_list_inner<F, T>(
14010        &mut self,
14011        optional: IsOptional,
14012        allow_empty: bool,
14013        mut f: F,
14014    ) -> Result<Vec<T>, ParserError>
14015    where
14016        F: FnMut(&mut Parser) -> Result<T, ParserError>,
14017    {
14018        if self.consume_token(&Token::LParen) {
14019            if allow_empty && self.peek_token_ref().token == Token::RParen {
14020                self.next_token();
14021                Ok(vec![])
14022            } else {
14023                let cols = self.parse_comma_separated(|p| f(p))?;
14024                self.expect_token(&Token::RParen)?;
14025                Ok(cols)
14026            }
14027        } else if optional == Optional {
14028            Ok(vec![])
14029        } else {
14030            self.expected_ref("a list of columns in parentheses", self.peek_token_ref())
14031        }
14032    }
14033
14034    /// Parses a parenthesized comma-separated list of table alias column definitions.
14035    fn parse_table_alias_column_defs(&mut self) -> Result<Vec<TableAliasColumnDef>, ParserError> {
14036        if self.consume_token(&Token::LParen) {
14037            let cols = self.parse_comma_separated(|p| {
14038                let name = p.parse_identifier()?;
14039                let data_type = p.maybe_parse(|p| p.parse_data_type())?;
14040                Ok(TableAliasColumnDef { name, data_type })
14041            })?;
14042            self.expect_token(&Token::RParen)?;
14043            Ok(cols)
14044        } else {
14045            Ok(vec![])
14046        }
14047    }
14048
14049    /// Parse an unsigned precision value enclosed in parentheses, e.g. `(10)`.
14050    pub fn parse_precision(&mut self) -> Result<u64, ParserError> {
14051        self.expect_token(&Token::LParen)?;
14052        let n = self.parse_literal_uint()?;
14053        self.expect_token(&Token::RParen)?;
14054        Ok(n)
14055    }
14056
14057    /// Parse an optional precision `(n)` and return it as `Some(n)` when present.
14058    pub fn parse_optional_precision(&mut self) -> Result<Option<u64>, ParserError> {
14059        if self.consume_token(&Token::LParen) {
14060            let n = self.parse_literal_uint()?;
14061            self.expect_token(&Token::RParen)?;
14062            Ok(Some(n))
14063        } else {
14064            Ok(None)
14065        }
14066    }
14067
14068    fn maybe_parse_optional_interval_fields(
14069        &mut self,
14070    ) -> Result<Option<IntervalFields>, ParserError> {
14071        match self.parse_one_of_keywords(&[
14072            // Can be followed by `TO` option
14073            Keyword::YEAR,
14074            Keyword::DAY,
14075            Keyword::HOUR,
14076            Keyword::MINUTE,
14077            // No `TO` option
14078            Keyword::MONTH,
14079            Keyword::SECOND,
14080        ]) {
14081            Some(Keyword::YEAR) => {
14082                if self.peek_keyword(Keyword::TO) {
14083                    self.expect_keyword(Keyword::TO)?;
14084                    self.expect_keyword(Keyword::MONTH)?;
14085                    Ok(Some(IntervalFields::YearToMonth))
14086                } else {
14087                    Ok(Some(IntervalFields::Year))
14088                }
14089            }
14090            Some(Keyword::DAY) => {
14091                if self.peek_keyword(Keyword::TO) {
14092                    self.expect_keyword(Keyword::TO)?;
14093                    match self.expect_one_of_keywords(&[
14094                        Keyword::HOUR,
14095                        Keyword::MINUTE,
14096                        Keyword::SECOND,
14097                    ])? {
14098                        Keyword::HOUR => Ok(Some(IntervalFields::DayToHour)),
14099                        Keyword::MINUTE => Ok(Some(IntervalFields::DayToMinute)),
14100                        Keyword::SECOND => Ok(Some(IntervalFields::DayToSecond)),
14101                        _ => {
14102                            self.prev_token();
14103                            self.expected_ref("HOUR, MINUTE, or SECOND", self.peek_token_ref())
14104                        }
14105                    }
14106                } else {
14107                    Ok(Some(IntervalFields::Day))
14108                }
14109            }
14110            Some(Keyword::HOUR) => {
14111                if self.peek_keyword(Keyword::TO) {
14112                    self.expect_keyword(Keyword::TO)?;
14113                    match self.expect_one_of_keywords(&[Keyword::MINUTE, Keyword::SECOND])? {
14114                        Keyword::MINUTE => Ok(Some(IntervalFields::HourToMinute)),
14115                        Keyword::SECOND => Ok(Some(IntervalFields::HourToSecond)),
14116                        _ => {
14117                            self.prev_token();
14118                            self.expected_ref("MINUTE or SECOND", self.peek_token_ref())
14119                        }
14120                    }
14121                } else {
14122                    Ok(Some(IntervalFields::Hour))
14123                }
14124            }
14125            Some(Keyword::MINUTE) => {
14126                if self.peek_keyword(Keyword::TO) {
14127                    self.expect_keyword(Keyword::TO)?;
14128                    self.expect_keyword(Keyword::SECOND)?;
14129                    Ok(Some(IntervalFields::MinuteToSecond))
14130                } else {
14131                    Ok(Some(IntervalFields::Minute))
14132                }
14133            }
14134            Some(Keyword::MONTH) => Ok(Some(IntervalFields::Month)),
14135            Some(Keyword::SECOND) => Ok(Some(IntervalFields::Second)),
14136            Some(_) => {
14137                self.prev_token();
14138                self.expected_ref(
14139                    "YEAR, MONTH, DAY, HOUR, MINUTE, or SECOND",
14140                    self.peek_token_ref(),
14141                )
14142            }
14143            None => Ok(None),
14144        }
14145    }
14146
14147    /// Parse datetime64 [1]
14148    /// Syntax
14149    /// ```sql
14150    /// DateTime64(precision[, timezone])
14151    /// ```
14152    ///
14153    /// [1]: https://clickhouse.com/docs/en/sql-reference/data-types/datetime64
14154    pub fn parse_datetime_64(&mut self) -> Result<(u64, Option<String>), ParserError> {
14155        self.expect_keyword_is(Keyword::DATETIME64)?;
14156        self.expect_token(&Token::LParen)?;
14157        let precision = self.parse_literal_uint()?;
14158        let time_zone = if self.consume_token(&Token::Comma) {
14159            Some(self.parse_literal_string()?)
14160        } else {
14161            None
14162        };
14163        self.expect_token(&Token::RParen)?;
14164        Ok((precision, time_zone))
14165    }
14166
14167    /// Parse an optional character length specification `(n | MAX [CHARACTERS|OCTETS])`.
14168    pub fn parse_optional_character_length(
14169        &mut self,
14170    ) -> Result<Option<CharacterLength>, ParserError> {
14171        if self.consume_token(&Token::LParen) {
14172            let character_length = self.parse_character_length()?;
14173            self.expect_token(&Token::RParen)?;
14174            Ok(Some(character_length))
14175        } else {
14176            Ok(None)
14177        }
14178    }
14179
14180    /// Parse an optional binary length specification like `(n)`.
14181    pub fn parse_optional_binary_length(&mut self) -> Result<Option<BinaryLength>, ParserError> {
14182        if self.consume_token(&Token::LParen) {
14183            let binary_length = self.parse_binary_length()?;
14184            self.expect_token(&Token::RParen)?;
14185            Ok(Some(binary_length))
14186        } else {
14187            Ok(None)
14188        }
14189    }
14190
14191    /// Parse a character length, handling `MAX` or integer lengths with optional units.
14192    pub fn parse_character_length(&mut self) -> Result<CharacterLength, ParserError> {
14193        if self.parse_keyword(Keyword::MAX) {
14194            return Ok(CharacterLength::Max);
14195        }
14196        let length = self.parse_literal_uint()?;
14197        let unit = if self.parse_keyword(Keyword::CHARACTERS) {
14198            Some(CharLengthUnits::Characters)
14199        } else if self.parse_keyword(Keyword::OCTETS) {
14200            Some(CharLengthUnits::Octets)
14201        } else {
14202            None
14203        };
14204        Ok(CharacterLength::IntegerLength { length, unit })
14205    }
14206
14207    /// Parse a binary length specification, returning `BinaryLength`.
14208    pub fn parse_binary_length(&mut self) -> Result<BinaryLength, ParserError> {
14209        if self.parse_keyword(Keyword::MAX) {
14210            return Ok(BinaryLength::Max);
14211        }
14212        let length = self.parse_literal_uint()?;
14213        Ok(BinaryLength::IntegerLength { length })
14214    }
14215
14216    /// Parse an optional `(precision[, scale])` and return `(Option<precision>, Option<scale>)`.
14217    pub fn parse_optional_precision_scale(
14218        &mut self,
14219    ) -> Result<(Option<u64>, Option<u64>), ParserError> {
14220        if self.consume_token(&Token::LParen) {
14221            let n = self.parse_literal_uint()?;
14222            let scale = if self.consume_token(&Token::Comma) {
14223                Some(self.parse_literal_uint()?)
14224            } else {
14225                None
14226            };
14227            self.expect_token(&Token::RParen)?;
14228            Ok((Some(n), scale))
14229        } else {
14230            Ok((None, None))
14231        }
14232    }
14233
14234    /// Parse exact-number precision/scale info like `(precision[, scale])` for decimal types.
14235    pub fn parse_exact_number_optional_precision_scale(
14236        &mut self,
14237    ) -> Result<ExactNumberInfo, ParserError> {
14238        if self.consume_token(&Token::LParen) {
14239            let precision = self.parse_literal_uint()?;
14240            let scale = if self.consume_token(&Token::Comma) {
14241                Some(self.parse_signed_integer()?)
14242            } else {
14243                None
14244            };
14245
14246            self.expect_token(&Token::RParen)?;
14247
14248            match scale {
14249                None => Ok(ExactNumberInfo::Precision(precision)),
14250                Some(scale) => Ok(ExactNumberInfo::PrecisionAndScale(precision, scale)),
14251            }
14252        } else {
14253            Ok(ExactNumberInfo::None)
14254        }
14255    }
14256
14257    /// Parse an optionally signed integer literal.
14258    fn parse_signed_integer(&mut self) -> Result<i64, ParserError> {
14259        let is_negative = self.consume_token(&Token::Minus);
14260
14261        if !is_negative {
14262            let _ = self.consume_token(&Token::Plus);
14263        }
14264
14265        let current_token = self.peek_token_ref();
14266        match &current_token.token {
14267            Token::Number(s, _) => {
14268                let s = s.clone();
14269                let span_start = current_token.span.start;
14270                self.advance_token();
14271                let value = Self::parse::<i64>(s, span_start)?;
14272                Ok(if is_negative { -value } else { value })
14273            }
14274            _ => self.expected_ref("number", current_token),
14275        }
14276    }
14277
14278    /// Parse optional type modifiers appearing in parentheses e.g. `(UNSIGNED, ZEROFILL)`.
14279    pub fn parse_optional_type_modifiers(&mut self) -> Result<Option<Vec<String>>, ParserError> {
14280        if self.consume_token(&Token::LParen) {
14281            let mut modifiers = Vec::new();
14282            loop {
14283                let next_token = self.next_token();
14284                match next_token.token {
14285                    Token::Word(w) => modifiers.push(w.to_string()),
14286                    Token::Number(n, _) => modifiers.push(n),
14287                    Token::SingleQuotedString(s) => modifiers.push(s),
14288
14289                    Token::Comma => {
14290                        continue;
14291                    }
14292                    Token::RParen => {
14293                        break;
14294                    }
14295                    _ => self.expected("type modifiers", next_token)?,
14296                }
14297            }
14298
14299            Ok(Some(modifiers))
14300        } else {
14301            Ok(None)
14302        }
14303    }
14304
14305    /// Parse a parenthesized sub data type
14306    fn parse_sub_type<F>(&mut self, parent_type: F) -> Result<DataType, ParserError>
14307    where
14308        F: FnOnce(Box<DataType>) -> DataType,
14309    {
14310        self.expect_token(&Token::LParen)?;
14311        let inside_type = self.parse_data_type()?;
14312        self.expect_token(&Token::RParen)?;
14313        Ok(parent_type(inside_type.into()))
14314    }
14315
14316    /// Parse a DELETE statement, returning a `Box`ed SetExpr
14317    ///
14318    /// This is used to reduce the size of the stack frames in debug builds
14319    fn parse_delete_setexpr_boxed(
14320        &mut self,
14321        delete_token: TokenWithSpan,
14322    ) -> Result<Box<SetExpr>, ParserError> {
14323        Ok(Box::new(SetExpr::Delete(self.parse_delete(delete_token)?)))
14324    }
14325
14326    /// Parse a `DELETE` statement and return `Statement::Delete`.
14327    pub fn parse_delete(&mut self, delete_token: TokenWithSpan) -> Result<Statement, ParserError> {
14328        let optimizer_hints = self.maybe_parse_optimizer_hints()?;
14329        let (tables, with_from_keyword) = if !self.parse_keyword(Keyword::FROM) {
14330            // `FROM` keyword is optional in BigQuery SQL.
14331            // https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#delete_statement
14332            if dialect_of!(self is BigQueryDialect | OracleDialect | GenericDialect) {
14333                (vec![], false)
14334            } else {
14335                let tables = self.parse_comma_separated(|p| p.parse_object_name(false))?;
14336                self.expect_keyword_is(Keyword::FROM)?;
14337                (tables, true)
14338            }
14339        } else {
14340            (vec![], true)
14341        };
14342
14343        let from = self.parse_comma_separated(Parser::parse_table_and_joins)?;
14344
14345        let output = self.maybe_parse_output_clause()?;
14346
14347        let using = if self.parse_keyword(Keyword::USING) {
14348            Some(self.parse_comma_separated(Parser::parse_table_and_joins)?)
14349        } else {
14350            None
14351        };
14352        let selection = if self.parse_keyword(Keyword::WHERE) {
14353            Some(self.parse_expr()?)
14354        } else {
14355            None
14356        };
14357        let returning = if self.parse_keyword(Keyword::RETURNING) {
14358            Some(self.parse_comma_separated(Parser::parse_select_item)?)
14359        } else {
14360            None
14361        };
14362        let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
14363            self.parse_comma_separated(Parser::parse_order_by_expr)?
14364        } else {
14365            vec![]
14366        };
14367        let limit = if self.parse_keyword(Keyword::LIMIT) {
14368            self.parse_limit()?
14369        } else {
14370            None
14371        };
14372
14373        Ok(Statement::Delete(Delete {
14374            delete_token: delete_token.into(),
14375            optimizer_hints,
14376            tables,
14377            from: if with_from_keyword {
14378                FromTable::WithFromKeyword(from)
14379            } else {
14380                FromTable::WithoutKeyword(from)
14381            },
14382            using,
14383            selection,
14384            returning,
14385            output,
14386            order_by,
14387            limit,
14388        }))
14389    }
14390
14391    /// Parse a `KILL` statement, optionally specifying `CONNECTION`, `QUERY`, or `MUTATION`.
14392    /// KILL [CONNECTION | QUERY | MUTATION] processlist_id
14393    pub fn parse_kill(&mut self) -> Result<Statement, ParserError> {
14394        let modifier_keyword =
14395            self.parse_one_of_keywords(&[Keyword::CONNECTION, Keyword::QUERY, Keyword::MUTATION]);
14396
14397        let id = self.parse_literal_uint()?;
14398
14399        let modifier = match modifier_keyword {
14400            Some(Keyword::CONNECTION) => Some(KillType::Connection),
14401            Some(Keyword::QUERY) => Some(KillType::Query),
14402            Some(Keyword::MUTATION) => {
14403                if dialect_of!(self is ClickHouseDialect | GenericDialect) {
14404                    Some(KillType::Mutation)
14405                } else {
14406                    self.expected_ref(
14407                        "Unsupported type for KILL, allowed: CONNECTION | QUERY",
14408                        self.peek_token_ref(),
14409                    )?
14410                }
14411            }
14412            _ => None,
14413        };
14414
14415        Ok(Statement::Kill { modifier, id })
14416    }
14417
14418    /// Parse an `EXPLAIN` statement, handling dialect-specific options and modifiers.
14419    pub fn parse_explain(
14420        &mut self,
14421        describe_alias: DescribeAlias,
14422    ) -> Result<Statement, ParserError> {
14423        let mut analyze = false;
14424        let mut verbose = false;
14425        let mut query_plan = false;
14426        let mut estimate = false;
14427        let mut format = None;
14428        let mut options = None;
14429
14430        // Note: DuckDB is compatible with PostgreSQL syntax for this statement,
14431        // although not all features may be implemented.
14432        if describe_alias == DescribeAlias::Explain
14433            && self.dialect.supports_explain_with_utility_options()
14434            && self.peek_token_ref().token == Token::LParen
14435        {
14436            options = Some(self.parse_utility_options()?)
14437        } else if self.parse_keywords(&[Keyword::QUERY, Keyword::PLAN]) {
14438            query_plan = true;
14439        } else if self.parse_keyword(Keyword::ESTIMATE) {
14440            estimate = true;
14441        } else {
14442            analyze = self.parse_keyword(Keyword::ANALYZE);
14443            verbose = self.parse_keyword(Keyword::VERBOSE);
14444            if self.parse_keyword(Keyword::FORMAT) {
14445                format = Some(self.parse_analyze_format_kind()?);
14446            }
14447        }
14448
14449        match self.maybe_parse(|parser| parser.parse_statement())? {
14450            Some(Statement::Explain { .. }) | Some(Statement::ExplainTable { .. }) => Err(
14451                ParserError::ParserError("Explain must be root of the plan".to_string()),
14452            ),
14453            Some(statement) => Ok(Statement::Explain {
14454                describe_alias,
14455                analyze,
14456                verbose,
14457                query_plan,
14458                estimate,
14459                statement: Box::new(statement),
14460                format,
14461                options,
14462            }),
14463            _ => {
14464                let hive_format =
14465                    match self.parse_one_of_keywords(&[Keyword::EXTENDED, Keyword::FORMATTED]) {
14466                        Some(Keyword::EXTENDED) => Some(HiveDescribeFormat::Extended),
14467                        Some(Keyword::FORMATTED) => Some(HiveDescribeFormat::Formatted),
14468                        _ => None,
14469                    };
14470
14471                let has_table_keyword = if self.dialect.describe_requires_table_keyword() {
14472                    // only allow to use TABLE keyword for DESC|DESCRIBE statement
14473                    self.parse_keyword(Keyword::TABLE)
14474                } else {
14475                    false
14476                };
14477
14478                let table_name = self.parse_object_name(false)?;
14479                Ok(Statement::ExplainTable {
14480                    describe_alias,
14481                    hive_format,
14482                    has_table_keyword,
14483                    table_name,
14484                })
14485            }
14486        }
14487    }
14488
14489    /// Parse a query expression, i.e. a `SELECT` statement optionally
14490    /// preceded with some `WITH` CTE declarations and optionally followed
14491    /// by `ORDER BY`. Unlike some other parse_... methods, this one doesn't
14492    /// expect the initial keyword to be already consumed
14493    #[cfg_attr(feature = "recursive-protection", recursive::recursive)]
14494    pub fn parse_query(&mut self) -> Result<Box<Query>, ParserError> {
14495        let _guard = self.recursion_counter.try_decrease()?;
14496        let with = if self.parse_keyword(Keyword::WITH) {
14497            let with_token = self.get_current_token();
14498            Some(With {
14499                with_token: with_token.clone().into(),
14500                recursive: self.parse_keyword(Keyword::RECURSIVE),
14501                cte_tables: self.parse_comma_separated(Parser::parse_cte)?,
14502            })
14503        } else {
14504            None
14505        };
14506        if self.parse_keyword(Keyword::INSERT) {
14507            Ok(Query {
14508                with,
14509                body: self.parse_insert_setexpr_boxed(self.get_current_token().clone())?,
14510                order_by: None,
14511                limit_clause: None,
14512                fetch: None,
14513                locks: vec![],
14514                for_clause: None,
14515                settings: None,
14516                format_clause: None,
14517                pipe_operators: vec![],
14518            }
14519            .into())
14520        } else if self.parse_keyword(Keyword::UPDATE) {
14521            Ok(Query {
14522                with,
14523                body: self.parse_update_setexpr_boxed(self.get_current_token().clone())?,
14524                order_by: None,
14525                limit_clause: None,
14526                fetch: None,
14527                locks: vec![],
14528                for_clause: None,
14529                settings: None,
14530                format_clause: None,
14531                pipe_operators: vec![],
14532            }
14533            .into())
14534        } else if self.parse_keyword(Keyword::DELETE) {
14535            Ok(Query {
14536                with,
14537                body: self.parse_delete_setexpr_boxed(self.get_current_token().clone())?,
14538                limit_clause: None,
14539                order_by: None,
14540                fetch: None,
14541                locks: vec![],
14542                for_clause: None,
14543                settings: None,
14544                format_clause: None,
14545                pipe_operators: vec![],
14546            }
14547            .into())
14548        } else if self.parse_keyword(Keyword::MERGE) {
14549            Ok(Query {
14550                with,
14551                body: self.parse_merge_setexpr_boxed(self.get_current_token().clone())?,
14552                limit_clause: None,
14553                order_by: None,
14554                fetch: None,
14555                locks: vec![],
14556                for_clause: None,
14557                settings: None,
14558                format_clause: None,
14559                pipe_operators: vec![],
14560            }
14561            .into())
14562        } else {
14563            let body = self.parse_query_body(self.dialect.prec_unknown())?;
14564
14565            let order_by = self.parse_optional_order_by()?;
14566
14567            let limit_clause = self.parse_optional_limit_clause()?;
14568
14569            let settings = self.parse_settings()?;
14570
14571            let fetch = if self.parse_keyword(Keyword::FETCH) {
14572                Some(self.parse_fetch()?)
14573            } else {
14574                None
14575            };
14576
14577            let mut for_clause = None;
14578            let mut locks = Vec::new();
14579            while self.parse_keyword(Keyword::FOR) {
14580                if let Some(parsed_for_clause) = self.parse_for_clause()? {
14581                    for_clause = Some(parsed_for_clause);
14582                    break;
14583                } else {
14584                    locks.push(self.parse_lock()?);
14585                }
14586            }
14587            let format_clause =
14588                if self.dialect.supports_select_format() && self.parse_keyword(Keyword::FORMAT) {
14589                    if self.parse_keyword(Keyword::NULL) {
14590                        Some(FormatClause::Null)
14591                    } else {
14592                        let ident = self.parse_identifier()?;
14593                        Some(FormatClause::Identifier(ident))
14594                    }
14595                } else {
14596                    None
14597                };
14598
14599            let pipe_operators = if self.dialect.supports_pipe_operator() {
14600                self.parse_pipe_operators()?
14601            } else {
14602                Vec::new()
14603            };
14604
14605            Ok(Query {
14606                with,
14607                body,
14608                order_by,
14609                limit_clause,
14610                fetch,
14611                locks,
14612                for_clause,
14613                settings,
14614                format_clause,
14615                pipe_operators,
14616            }
14617            .into())
14618        }
14619    }
14620
14621    fn parse_pipe_operators(&mut self) -> Result<Vec<PipeOperator>, ParserError> {
14622        let mut pipe_operators = Vec::new();
14623
14624        while self.consume_token(&Token::VerticalBarRightAngleBracket) {
14625            let kw = self.expect_one_of_keywords(&[
14626                Keyword::SELECT,
14627                Keyword::EXTEND,
14628                Keyword::SET,
14629                Keyword::DROP,
14630                Keyword::AS,
14631                Keyword::WHERE,
14632                Keyword::LIMIT,
14633                Keyword::AGGREGATE,
14634                Keyword::ORDER,
14635                Keyword::TABLESAMPLE,
14636                Keyword::RENAME,
14637                Keyword::UNION,
14638                Keyword::INTERSECT,
14639                Keyword::EXCEPT,
14640                Keyword::CALL,
14641                Keyword::PIVOT,
14642                Keyword::UNPIVOT,
14643                Keyword::JOIN,
14644                Keyword::INNER,
14645                Keyword::LEFT,
14646                Keyword::RIGHT,
14647                Keyword::FULL,
14648                Keyword::CROSS,
14649            ])?;
14650            match kw {
14651                Keyword::SELECT => {
14652                    let exprs = self.parse_comma_separated(Parser::parse_select_item)?;
14653                    pipe_operators.push(PipeOperator::Select { exprs })
14654                }
14655                Keyword::EXTEND => {
14656                    let exprs = self.parse_comma_separated(Parser::parse_select_item)?;
14657                    pipe_operators.push(PipeOperator::Extend { exprs })
14658                }
14659                Keyword::SET => {
14660                    let assignments = self.parse_comma_separated(Parser::parse_assignment)?;
14661                    pipe_operators.push(PipeOperator::Set { assignments })
14662                }
14663                Keyword::DROP => {
14664                    let columns = self.parse_identifiers()?;
14665                    pipe_operators.push(PipeOperator::Drop { columns })
14666                }
14667                Keyword::AS => {
14668                    let alias = self.parse_identifier()?;
14669                    pipe_operators.push(PipeOperator::As { alias })
14670                }
14671                Keyword::WHERE => {
14672                    let expr = self.parse_expr()?;
14673                    pipe_operators.push(PipeOperator::Where { expr })
14674                }
14675                Keyword::LIMIT => {
14676                    let expr = self.parse_expr()?;
14677                    let offset = if self.parse_keyword(Keyword::OFFSET) {
14678                        Some(self.parse_expr()?)
14679                    } else {
14680                        None
14681                    };
14682                    pipe_operators.push(PipeOperator::Limit { expr, offset })
14683                }
14684                Keyword::AGGREGATE => {
14685                    let full_table_exprs = if self.peek_keyword(Keyword::GROUP) {
14686                        vec![]
14687                    } else {
14688                        self.parse_comma_separated(|parser| {
14689                            parser.parse_expr_with_alias_and_order_by()
14690                        })?
14691                    };
14692
14693                    let group_by_expr = if self.parse_keywords(&[Keyword::GROUP, Keyword::BY]) {
14694                        self.parse_comma_separated(|parser| {
14695                            parser.parse_expr_with_alias_and_order_by()
14696                        })?
14697                    } else {
14698                        vec![]
14699                    };
14700
14701                    pipe_operators.push(PipeOperator::Aggregate {
14702                        full_table_exprs,
14703                        group_by_expr,
14704                    })
14705                }
14706                Keyword::ORDER => {
14707                    self.expect_one_of_keywords(&[Keyword::BY])?;
14708                    let exprs = self.parse_comma_separated(Parser::parse_order_by_expr)?;
14709                    pipe_operators.push(PipeOperator::OrderBy { exprs })
14710                }
14711                Keyword::TABLESAMPLE => {
14712                    let sample = self.parse_table_sample(TableSampleModifier::TableSample)?;
14713                    pipe_operators.push(PipeOperator::TableSample { sample });
14714                }
14715                Keyword::RENAME => {
14716                    let mappings =
14717                        self.parse_comma_separated(Parser::parse_identifier_with_optional_alias)?;
14718                    pipe_operators.push(PipeOperator::Rename { mappings });
14719                }
14720                Keyword::UNION => {
14721                    let set_quantifier = self.parse_set_quantifier(&Some(SetOperator::Union));
14722                    let queries = self.parse_pipe_operator_queries()?;
14723                    pipe_operators.push(PipeOperator::Union {
14724                        set_quantifier,
14725                        queries,
14726                    });
14727                }
14728                Keyword::INTERSECT => {
14729                    let set_quantifier =
14730                        self.parse_distinct_required_set_quantifier("INTERSECT")?;
14731                    let queries = self.parse_pipe_operator_queries()?;
14732                    pipe_operators.push(PipeOperator::Intersect {
14733                        set_quantifier,
14734                        queries,
14735                    });
14736                }
14737                Keyword::EXCEPT => {
14738                    let set_quantifier = self.parse_distinct_required_set_quantifier("EXCEPT")?;
14739                    let queries = self.parse_pipe_operator_queries()?;
14740                    pipe_operators.push(PipeOperator::Except {
14741                        set_quantifier,
14742                        queries,
14743                    });
14744                }
14745                Keyword::CALL => {
14746                    let function_name = self.parse_object_name(false)?;
14747                    let function_expr = self.parse_function(function_name)?;
14748                    if let Expr::Function(function) = function_expr {
14749                        let alias = self.parse_identifier_optional_alias()?;
14750                        pipe_operators.push(PipeOperator::Call { function, alias });
14751                    } else {
14752                        return Err(ParserError::ParserError(
14753                            "Expected function call after CALL".to_string(),
14754                        ));
14755                    }
14756                }
14757                Keyword::PIVOT => {
14758                    self.expect_token(&Token::LParen)?;
14759                    let aggregate_functions =
14760                        self.parse_comma_separated(Self::parse_pivot_aggregate_function)?;
14761                    self.expect_keyword_is(Keyword::FOR)?;
14762                    let value_column = self.parse_period_separated(|p| p.parse_identifier())?;
14763                    self.expect_keyword_is(Keyword::IN)?;
14764
14765                    self.expect_token(&Token::LParen)?;
14766                    let value_source = if self.parse_keyword(Keyword::ANY) {
14767                        let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
14768                            self.parse_comma_separated(Parser::parse_order_by_expr)?
14769                        } else {
14770                            vec![]
14771                        };
14772                        PivotValueSource::Any(order_by)
14773                    } else if self.peek_sub_query() {
14774                        PivotValueSource::Subquery(self.parse_query()?)
14775                    } else {
14776                        PivotValueSource::List(
14777                            self.parse_comma_separated(Self::parse_expr_with_alias)?,
14778                        )
14779                    };
14780                    self.expect_token(&Token::RParen)?;
14781                    self.expect_token(&Token::RParen)?;
14782
14783                    let alias = self.parse_identifier_optional_alias()?;
14784
14785                    pipe_operators.push(PipeOperator::Pivot {
14786                        aggregate_functions,
14787                        value_column,
14788                        value_source,
14789                        alias,
14790                    });
14791                }
14792                Keyword::UNPIVOT => {
14793                    self.expect_token(&Token::LParen)?;
14794                    let value_column = self.parse_identifier()?;
14795                    self.expect_keyword(Keyword::FOR)?;
14796                    let name_column = self.parse_identifier()?;
14797                    self.expect_keyword(Keyword::IN)?;
14798
14799                    self.expect_token(&Token::LParen)?;
14800                    let unpivot_columns = self.parse_comma_separated(Parser::parse_identifier)?;
14801                    self.expect_token(&Token::RParen)?;
14802
14803                    self.expect_token(&Token::RParen)?;
14804
14805                    let alias = self.parse_identifier_optional_alias()?;
14806
14807                    pipe_operators.push(PipeOperator::Unpivot {
14808                        value_column,
14809                        name_column,
14810                        unpivot_columns,
14811                        alias,
14812                    });
14813                }
14814                Keyword::JOIN
14815                | Keyword::INNER
14816                | Keyword::LEFT
14817                | Keyword::RIGHT
14818                | Keyword::FULL
14819                | Keyword::CROSS => {
14820                    self.prev_token();
14821                    let mut joins = self.parse_joins()?;
14822                    if joins.len() != 1 {
14823                        return Err(ParserError::ParserError(
14824                            "Join pipe operator must have a single join".to_string(),
14825                        ));
14826                    }
14827                    let join = joins.swap_remove(0);
14828                    pipe_operators.push(PipeOperator::Join(join))
14829                }
14830                unhandled => {
14831                    return Err(ParserError::ParserError(format!(
14832                    "`expect_one_of_keywords` further up allowed unhandled keyword: {unhandled:?}"
14833                )))
14834                }
14835            }
14836        }
14837        Ok(pipe_operators)
14838    }
14839
14840    fn parse_settings(&mut self) -> Result<Option<Vec<Setting>>, ParserError> {
14841        let settings = if self.dialect.supports_settings() && self.parse_keyword(Keyword::SETTINGS)
14842        {
14843            let key_values = self.parse_comma_separated(|p| {
14844                let key = p.parse_identifier()?;
14845                p.expect_token(&Token::Eq)?;
14846                let value = p.parse_expr()?;
14847                Ok(Setting { key, value })
14848            })?;
14849            Some(key_values)
14850        } else {
14851            None
14852        };
14853        Ok(settings)
14854    }
14855
14856    /// Parse a mssql `FOR [XML | JSON | BROWSE]` clause
14857    pub fn parse_for_clause(&mut self) -> Result<Option<ForClause>, ParserError> {
14858        if self.parse_keyword(Keyword::XML) {
14859            Ok(Some(self.parse_for_xml()?))
14860        } else if self.parse_keyword(Keyword::JSON) {
14861            Ok(Some(self.parse_for_json()?))
14862        } else if self.parse_keyword(Keyword::BROWSE) {
14863            Ok(Some(ForClause::Browse))
14864        } else {
14865            Ok(None)
14866        }
14867    }
14868
14869    /// Parse a mssql `FOR XML` clause
14870    pub fn parse_for_xml(&mut self) -> Result<ForClause, ParserError> {
14871        let for_xml = if self.parse_keyword(Keyword::RAW) {
14872            let mut element_name = None;
14873            if self.peek_token_ref().token == Token::LParen {
14874                self.expect_token(&Token::LParen)?;
14875                element_name = Some(self.parse_literal_string()?);
14876                self.expect_token(&Token::RParen)?;
14877            }
14878            ForXml::Raw(element_name)
14879        } else if self.parse_keyword(Keyword::AUTO) {
14880            ForXml::Auto
14881        } else if self.parse_keyword(Keyword::EXPLICIT) {
14882            ForXml::Explicit
14883        } else if self.parse_keyword(Keyword::PATH) {
14884            let mut element_name = None;
14885            if self.peek_token_ref().token == Token::LParen {
14886                self.expect_token(&Token::LParen)?;
14887                element_name = Some(self.parse_literal_string()?);
14888                self.expect_token(&Token::RParen)?;
14889            }
14890            ForXml::Path(element_name)
14891        } else {
14892            return Err(ParserError::ParserError(
14893                "Expected FOR XML [RAW | AUTO | EXPLICIT | PATH ]".to_string(),
14894            ));
14895        };
14896        let mut elements = false;
14897        let mut binary_base64 = false;
14898        let mut root = None;
14899        let mut r#type = false;
14900        while self.peek_token_ref().token == Token::Comma {
14901            self.next_token();
14902            if self.parse_keyword(Keyword::ELEMENTS) {
14903                elements = true;
14904            } else if self.parse_keyword(Keyword::BINARY) {
14905                self.expect_keyword_is(Keyword::BASE64)?;
14906                binary_base64 = true;
14907            } else if self.parse_keyword(Keyword::ROOT) {
14908                self.expect_token(&Token::LParen)?;
14909                root = Some(self.parse_literal_string()?);
14910                self.expect_token(&Token::RParen)?;
14911            } else if self.parse_keyword(Keyword::TYPE) {
14912                r#type = true;
14913            }
14914        }
14915        Ok(ForClause::Xml {
14916            for_xml,
14917            elements,
14918            binary_base64,
14919            root,
14920            r#type,
14921        })
14922    }
14923
14924    /// Parse a mssql `FOR JSON` clause
14925    pub fn parse_for_json(&mut self) -> Result<ForClause, ParserError> {
14926        let for_json = if self.parse_keyword(Keyword::AUTO) {
14927            ForJson::Auto
14928        } else if self.parse_keyword(Keyword::PATH) {
14929            ForJson::Path
14930        } else {
14931            return Err(ParserError::ParserError(
14932                "Expected FOR JSON [AUTO | PATH ]".to_string(),
14933            ));
14934        };
14935        let mut root = None;
14936        let mut include_null_values = false;
14937        let mut without_array_wrapper = false;
14938        while self.peek_token_ref().token == Token::Comma {
14939            self.next_token();
14940            if self.parse_keyword(Keyword::ROOT) {
14941                self.expect_token(&Token::LParen)?;
14942                root = Some(self.parse_literal_string()?);
14943                self.expect_token(&Token::RParen)?;
14944            } else if self.parse_keyword(Keyword::INCLUDE_NULL_VALUES) {
14945                include_null_values = true;
14946            } else if self.parse_keyword(Keyword::WITHOUT_ARRAY_WRAPPER) {
14947                without_array_wrapper = true;
14948            }
14949        }
14950        Ok(ForClause::Json {
14951            for_json,
14952            root,
14953            include_null_values,
14954            without_array_wrapper,
14955        })
14956    }
14957
14958    /// Parse a CTE (`alias [( col1, col2, ... )] [AS] (subquery)`)
14959    pub fn parse_cte(&mut self) -> Result<Cte, ParserError> {
14960        let name = self.parse_identifier()?;
14961
14962        let as_optional = self.dialect.supports_cte_without_as();
14963
14964        // If AS is optional, first try to parse `name (query)` directly
14965        if as_optional && !self.peek_keyword(Keyword::AS) {
14966            if let Some((query, closing_paren_token)) = self.maybe_parse(|p| {
14967                p.expect_token(&Token::LParen)?;
14968                let query = p.parse_query()?;
14969                let closing_paren_token = p.expect_token(&Token::RParen)?;
14970                Ok((query, closing_paren_token))
14971            })? {
14972                let mut cte = Cte {
14973                    alias: TableAlias {
14974                        explicit: false,
14975                        name,
14976                        columns: vec![],
14977                        at: None,
14978                    },
14979                    query,
14980                    from: None,
14981                    materialized: None,
14982                    closing_paren_token: closing_paren_token.into(),
14983                };
14984                if self.parse_keyword(Keyword::FROM) {
14985                    cte.from = Some(self.parse_identifier()?);
14986                }
14987                return Ok(cte);
14988            }
14989        }
14990
14991        // Determine column definitions and consume AS
14992        let columns = if self.parse_keyword(Keyword::AS) {
14993            vec![]
14994        } else {
14995            let columns = self.parse_table_alias_column_defs()?;
14996            if as_optional {
14997                let _ = self.parse_keyword(Keyword::AS);
14998            } else {
14999                self.expect_keyword_is(Keyword::AS)?;
15000            }
15001            columns
15002        };
15003
15004        let mut is_materialized = None;
15005        if dialect_of!(self is PostgreSqlDialect) {
15006            if self.parse_keyword(Keyword::MATERIALIZED) {
15007                is_materialized = Some(CteAsMaterialized::Materialized);
15008            } else if self.parse_keywords(&[Keyword::NOT, Keyword::MATERIALIZED]) {
15009                is_materialized = Some(CteAsMaterialized::NotMaterialized);
15010            }
15011        }
15012
15013        self.expect_token(&Token::LParen)?;
15014        let query = self.parse_query()?;
15015        let closing_paren_token = self.expect_token(&Token::RParen)?;
15016
15017        let mut cte = Cte {
15018            alias: TableAlias {
15019                explicit: false,
15020                name,
15021                columns,
15022                at: None,
15023            },
15024            query,
15025            from: None,
15026            materialized: is_materialized,
15027            closing_paren_token: closing_paren_token.into(),
15028        };
15029        if self.dialect.supports_from_first_insert() && self.parse_keyword(Keyword::FROM) {
15030            cte.from = Some(self.parse_identifier()?);
15031        }
15032        Ok(cte)
15033    }
15034
15035    /// Parse a "query body", which is an expression with roughly the
15036    /// following grammar:
15037    /// ```sql
15038    ///   query_body ::= restricted_select | '(' subquery ')' | set_operation
15039    ///   restricted_select ::= 'SELECT' [expr_list] [ from ] [ where ] [ groupby_having ]
15040    ///   subquery ::= query_body [ order_by_limit ]
15041    ///   set_operation ::= query_body { 'UNION' | 'EXCEPT' | 'INTERSECT' } [ 'ALL' ] query_body
15042    /// ```
15043    pub fn parse_query_body(&mut self, precedence: u8) -> Result<Box<SetExpr>, ParserError> {
15044        // We parse the expression using a Pratt parser, as in `parse_expr()`.
15045        // Start by parsing a restricted SELECT or a `(subquery)`:
15046        let expr = if self.peek_keyword(Keyword::SELECT)
15047            || (self.peek_keyword(Keyword::FROM) && self.dialect.supports_from_first_select())
15048        {
15049            SetExpr::Select(self.parse_select().map(Box::new)?)
15050        } else if self.consume_token(&Token::LParen) {
15051            // CTEs are not allowed here, but the parser currently accepts them
15052            let subquery = self.parse_query()?;
15053            self.expect_token(&Token::RParen)?;
15054            SetExpr::Query(subquery)
15055        } else if self.parse_keyword(Keyword::VALUES) {
15056            let is_mysql = dialect_of!(self is MySqlDialect);
15057            SetExpr::Values(self.parse_values(is_mysql, false)?)
15058        } else if self.parse_keyword(Keyword::VALUE) {
15059            let is_mysql = dialect_of!(self is MySqlDialect);
15060            SetExpr::Values(self.parse_values(is_mysql, true)?)
15061        } else if self.parse_keyword(Keyword::TABLE) {
15062            SetExpr::Table(Box::new(self.parse_as_table()?))
15063        } else {
15064            return self.expected_ref(
15065                "SELECT, VALUES, or a subquery in the query body",
15066                self.peek_token_ref(),
15067            );
15068        };
15069
15070        self.parse_remaining_set_exprs(expr, precedence)
15071    }
15072
15073    /// Parse any extra set expressions that may be present in a query body
15074    ///
15075    /// (this is its own function to reduce required stack size in debug builds)
15076    fn parse_remaining_set_exprs(
15077        &mut self,
15078        mut expr: SetExpr,
15079        precedence: u8,
15080    ) -> Result<Box<SetExpr>, ParserError> {
15081        loop {
15082            // The query can be optionally followed by a set operator:
15083            let op = self.parse_set_operator(&self.peek_token().token);
15084            let next_precedence = match op {
15085                // UNION and EXCEPT have the same binding power and evaluate left-to-right
15086                Some(SetOperator::Union) | Some(SetOperator::Except) | Some(SetOperator::Minus) => {
15087                    10
15088                }
15089                // INTERSECT has higher precedence than UNION/EXCEPT
15090                Some(SetOperator::Intersect) => 20,
15091                // Unexpected token or EOF => stop parsing the query body
15092                None => break,
15093            };
15094            if precedence >= next_precedence {
15095                break;
15096            }
15097            self.next_token(); // skip past the set operator
15098            let set_quantifier = self.parse_set_quantifier(&op);
15099            expr = SetExpr::SetOperation {
15100                left: Box::new(expr),
15101                op: op.unwrap(),
15102                set_quantifier,
15103                right: self.parse_query_body(next_precedence)?,
15104            };
15105        }
15106
15107        Ok(expr.into())
15108    }
15109
15110    /// Parse a set operator token into its `SetOperator` variant.
15111    pub fn parse_set_operator(&mut self, token: &Token) -> Option<SetOperator> {
15112        match token {
15113            Token::Word(w) if w.keyword == Keyword::UNION => Some(SetOperator::Union),
15114            Token::Word(w) if w.keyword == Keyword::EXCEPT => Some(SetOperator::Except),
15115            Token::Word(w) if w.keyword == Keyword::INTERSECT => Some(SetOperator::Intersect),
15116            Token::Word(w) if w.keyword == Keyword::MINUS => Some(SetOperator::Minus),
15117            _ => None,
15118        }
15119    }
15120
15121    /// Parse a set quantifier (e.g., `ALL`, `DISTINCT BY NAME`) for the given set operator.
15122    pub fn parse_set_quantifier(&mut self, op: &Option<SetOperator>) -> SetQuantifier {
15123        match op {
15124            Some(
15125                SetOperator::Except
15126                | SetOperator::Intersect
15127                | SetOperator::Union
15128                | SetOperator::Minus,
15129            ) => {
15130                if self.parse_keywords(&[Keyword::DISTINCT, Keyword::BY, Keyword::NAME]) {
15131                    SetQuantifier::DistinctByName
15132                } else if self.parse_keywords(&[Keyword::BY, Keyword::NAME]) {
15133                    SetQuantifier::ByName
15134                } else if self.parse_keyword(Keyword::ALL) {
15135                    if self.parse_keywords(&[Keyword::BY, Keyword::NAME]) {
15136                        SetQuantifier::AllByName
15137                    } else {
15138                        SetQuantifier::All
15139                    }
15140                } else if self.parse_keyword(Keyword::DISTINCT) {
15141                    SetQuantifier::Distinct
15142                } else {
15143                    SetQuantifier::None
15144                }
15145            }
15146            _ => SetQuantifier::None,
15147        }
15148    }
15149
15150    /// Parse a restricted `SELECT` statement (no CTEs / `UNION` / `ORDER BY`)
15151    pub fn parse_select(&mut self) -> Result<Select, ParserError> {
15152        let mut from_first = None;
15153
15154        if self.dialect.supports_from_first_select() && self.peek_keyword(Keyword::FROM) {
15155            let from_token = self.expect_keyword(Keyword::FROM)?;
15156            let from = self.parse_table_with_joins()?;
15157            if !self.peek_keyword(Keyword::SELECT) {
15158                return Ok(Select {
15159                    select_token: AttachedToken(from_token),
15160                    optimizer_hints: vec![],
15161                    distinct: None,
15162                    select_modifiers: None,
15163                    top: None,
15164                    top_before_distinct: false,
15165                    projection: vec![],
15166                    exclude: None,
15167                    into: None,
15168                    from,
15169                    lateral_views: vec![],
15170                    prewhere: None,
15171                    selection: None,
15172                    group_by: GroupByExpr::Expressions(vec![], vec![]),
15173                    cluster_by: vec![],
15174                    distribute_by: vec![],
15175                    sort_by: vec![],
15176                    having: None,
15177                    named_window: vec![],
15178                    window_before_qualify: false,
15179                    qualify: None,
15180                    value_table_mode: None,
15181                    connect_by: vec![],
15182                    flavor: SelectFlavor::FromFirstNoSelect,
15183                });
15184            }
15185            from_first = Some(from);
15186        }
15187
15188        let select_token = self.expect_keyword(Keyword::SELECT)?;
15189        let optimizer_hints = self.maybe_parse_optimizer_hints()?;
15190        let value_table_mode = self.parse_value_table_mode()?;
15191
15192        let (select_modifiers, distinct_select_modifier) =
15193            if self.dialect.supports_select_modifiers() {
15194                self.parse_select_modifiers()?
15195            } else {
15196                (None, None)
15197            };
15198
15199        let mut top_before_distinct = false;
15200        let mut top = None;
15201        if self.dialect.supports_top_before_distinct() && self.parse_keyword(Keyword::TOP) {
15202            top = Some(self.parse_top()?);
15203            top_before_distinct = true;
15204        }
15205
15206        let distinct = if distinct_select_modifier.is_some() {
15207            distinct_select_modifier
15208        } else {
15209            self.parse_all_or_distinct()?
15210        };
15211
15212        if !self.dialect.supports_top_before_distinct() && self.parse_keyword(Keyword::TOP) {
15213            top = Some(self.parse_top()?);
15214        }
15215
15216        let projection =
15217            if self.dialect.supports_empty_projections() && self.peek_keyword(Keyword::FROM) {
15218                vec![]
15219            } else {
15220                self.parse_projection()?
15221            };
15222
15223        let exclude = if self.dialect.supports_select_exclude() {
15224            self.parse_optional_select_item_exclude()?
15225        } else {
15226            None
15227        };
15228
15229        let into = if self.parse_keyword(Keyword::INTO) {
15230            Some(self.parse_select_into()?)
15231        } else {
15232            None
15233        };
15234
15235        // Note that for keywords to be properly handled here, they need to be
15236        // added to `RESERVED_FOR_COLUMN_ALIAS` / `RESERVED_FOR_TABLE_ALIAS`,
15237        // otherwise they may be parsed as an alias as part of the `projection`
15238        // or `from`.
15239
15240        let (from, from_first) = if let Some(from) = from_first.take() {
15241            (from, true)
15242        } else if self.parse_keyword(Keyword::FROM) {
15243            (self.parse_table_with_joins()?, false)
15244        } else {
15245            (vec![], false)
15246        };
15247
15248        let mut lateral_views = vec![];
15249        loop {
15250            if self.parse_keywords(&[Keyword::LATERAL, Keyword::VIEW]) {
15251                let outer = self.parse_keyword(Keyword::OUTER);
15252                let lateral_view = self.parse_expr()?;
15253                let lateral_view_name = self.parse_object_name(false)?;
15254                let lateral_col_alias = self
15255                    .parse_comma_separated(|parser| {
15256                        parser.parse_optional_alias(&[
15257                            Keyword::WHERE,
15258                            Keyword::GROUP,
15259                            Keyword::CLUSTER,
15260                            Keyword::HAVING,
15261                            Keyword::LATERAL,
15262                        ]) // This couldn't possibly be a bad idea
15263                    })?
15264                    .into_iter()
15265                    .flatten()
15266                    .collect();
15267
15268                lateral_views.push(LateralView {
15269                    lateral_view,
15270                    lateral_view_name,
15271                    lateral_col_alias,
15272                    outer,
15273                });
15274            } else {
15275                break;
15276            }
15277        }
15278
15279        let prewhere = if self.dialect.supports_prewhere() && self.parse_keyword(Keyword::PREWHERE)
15280        {
15281            Some(self.parse_expr()?)
15282        } else {
15283            None
15284        };
15285
15286        let selection = if self.parse_keyword(Keyword::WHERE) {
15287            Some(self.parse_expr()?)
15288        } else {
15289            None
15290        };
15291
15292        let connect_by = self.maybe_parse_connect_by()?;
15293
15294        let group_by = self
15295            .parse_optional_group_by()?
15296            .unwrap_or_else(|| GroupByExpr::Expressions(vec![], vec![]));
15297
15298        let cluster_by = if self.parse_keywords(&[Keyword::CLUSTER, Keyword::BY]) {
15299            self.parse_comma_separated(Parser::parse_expr)?
15300        } else {
15301            vec![]
15302        };
15303
15304        let distribute_by = if self.parse_keywords(&[Keyword::DISTRIBUTE, Keyword::BY]) {
15305            self.parse_comma_separated(Parser::parse_expr)?
15306        } else {
15307            vec![]
15308        };
15309
15310        let sort_by = if self.parse_keywords(&[Keyword::SORT, Keyword::BY]) {
15311            self.parse_comma_separated(Parser::parse_order_by_expr)?
15312        } else {
15313            vec![]
15314        };
15315
15316        let having = if self.parse_keyword(Keyword::HAVING) {
15317            Some(self.parse_expr()?)
15318        } else {
15319            None
15320        };
15321
15322        // Accept QUALIFY and WINDOW in any order and flag accordingly.
15323        let (named_windows, qualify, window_before_qualify) = if self.parse_keyword(Keyword::WINDOW)
15324        {
15325            let named_windows = self.parse_comma_separated(Parser::parse_named_window)?;
15326            if self.parse_keyword(Keyword::QUALIFY) {
15327                (named_windows, Some(self.parse_expr()?), true)
15328            } else {
15329                (named_windows, None, true)
15330            }
15331        } else if self.parse_keyword(Keyword::QUALIFY) {
15332            let qualify = Some(self.parse_expr()?);
15333            if self.parse_keyword(Keyword::WINDOW) {
15334                (
15335                    self.parse_comma_separated(Parser::parse_named_window)?,
15336                    qualify,
15337                    false,
15338                )
15339            } else {
15340                (Default::default(), qualify, false)
15341            }
15342        } else {
15343            Default::default()
15344        };
15345
15346        Ok(Select {
15347            select_token: AttachedToken(select_token),
15348            optimizer_hints,
15349            distinct,
15350            select_modifiers,
15351            top,
15352            top_before_distinct,
15353            projection,
15354            exclude,
15355            into,
15356            from,
15357            lateral_views,
15358            prewhere,
15359            selection,
15360            group_by,
15361            cluster_by,
15362            distribute_by,
15363            sort_by,
15364            having,
15365            named_window: named_windows,
15366            window_before_qualify,
15367            qualify,
15368            value_table_mode,
15369            connect_by,
15370            flavor: if from_first {
15371                SelectFlavor::FromFirst
15372            } else {
15373                SelectFlavor::Standard
15374            },
15375        })
15376    }
15377
15378    /// Parses optimizer hints at the current token position.
15379    ///
15380    /// Collects all `/*prefix+...*/` and `--prefix+...` patterns.
15381    /// The `prefix` is any run of ASCII alphanumeric characters between the
15382    /// comment marker and `+` (e.g. `""` for `/*+...*/`, `"abc"` for `/*abc+...*/`).
15383    ///
15384    /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/optimizer-hints.html#optimizer-hints-overview)
15385    /// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Comments.html#GUID-D316D545-89E2-4D54-977F-FC97815CD62E)
15386    fn maybe_parse_optimizer_hints(&mut self) -> Result<Vec<OptimizerHint>, ParserError> {
15387        let supports_hints = self.dialect.supports_comment_optimizer_hint();
15388        if !supports_hints {
15389            return Ok(vec![]);
15390        }
15391        let mut hints = vec![];
15392        loop {
15393            let t = self.peek_nth_token_no_skip_ref(0);
15394            let Token::Whitespace(ws) = &t.token else {
15395                break;
15396            };
15397            match ws {
15398                Whitespace::SingleLineComment { comment, prefix } => {
15399                    if let Some((hint_prefix, text)) = Self::extract_hint_prefix_and_text(comment) {
15400                        hints.push(OptimizerHint {
15401                            prefix: hint_prefix,
15402                            text,
15403                            style: OptimizerHintStyle::SingleLine {
15404                                prefix: prefix.clone(),
15405                            },
15406                        });
15407                    }
15408                    self.next_token_no_skip();
15409                }
15410                Whitespace::MultiLineComment(comment) => {
15411                    if let Some((hint_prefix, text)) = Self::extract_hint_prefix_and_text(comment) {
15412                        hints.push(OptimizerHint {
15413                            prefix: hint_prefix,
15414                            text,
15415                            style: OptimizerHintStyle::MultiLine,
15416                        });
15417                    }
15418                    self.next_token_no_skip();
15419                }
15420                Whitespace::Space | Whitespace::Tab | Whitespace::Newline => {
15421                    self.next_token_no_skip();
15422                }
15423            }
15424        }
15425        Ok(hints)
15426    }
15427
15428    /// Checks if a comment's content starts with `[ASCII-alphanumeric]*+`
15429    /// and returns `(prefix, text_after_plus)` if so.
15430    fn extract_hint_prefix_and_text(comment: &str) -> Option<(String, String)> {
15431        let (before_plus, text) = comment.split_once('+')?;
15432        if before_plus.chars().all(|c| c.is_ascii_alphanumeric()) {
15433            Some((before_plus.to_string(), text.to_string()))
15434        } else {
15435            None
15436        }
15437    }
15438
15439    /// Parses MySQL SELECT modifiers and DISTINCT/ALL in any order.
15440    ///
15441    /// Manual testing shows odifiers can appear in any order, and modifiers other than DISTINCT/ALL
15442    /// can be repeated.
15443    ///
15444    /// <https://dev.mysql.com/doc/refman/8.4/en/select.html>
15445    fn parse_select_modifiers(
15446        &mut self,
15447    ) -> Result<(Option<SelectModifiers>, Option<Distinct>), ParserError> {
15448        let mut modifiers = SelectModifiers::default();
15449        let mut distinct = None;
15450
15451        let keywords = &[
15452            Keyword::ALL,
15453            Keyword::DISTINCT,
15454            Keyword::DISTINCTROW,
15455            Keyword::HIGH_PRIORITY,
15456            Keyword::STRAIGHT_JOIN,
15457            Keyword::SQL_SMALL_RESULT,
15458            Keyword::SQL_BIG_RESULT,
15459            Keyword::SQL_BUFFER_RESULT,
15460            Keyword::SQL_NO_CACHE,
15461            Keyword::SQL_CALC_FOUND_ROWS,
15462        ];
15463
15464        while let Some(keyword) = self.parse_one_of_keywords(keywords) {
15465            match keyword {
15466                Keyword::ALL | Keyword::DISTINCT if distinct.is_none() => {
15467                    self.prev_token();
15468                    distinct = self.parse_all_or_distinct()?;
15469                }
15470                // DISTINCTROW is a MySQL-specific legacy (but not deprecated) alias for DISTINCT
15471                Keyword::DISTINCTROW if distinct.is_none() => {
15472                    distinct = Some(Distinct::Distinct);
15473                }
15474                Keyword::HIGH_PRIORITY => modifiers.high_priority = true,
15475                Keyword::STRAIGHT_JOIN => modifiers.straight_join = true,
15476                Keyword::SQL_SMALL_RESULT => modifiers.sql_small_result = true,
15477                Keyword::SQL_BIG_RESULT => modifiers.sql_big_result = true,
15478                Keyword::SQL_BUFFER_RESULT => modifiers.sql_buffer_result = true,
15479                Keyword::SQL_NO_CACHE => modifiers.sql_no_cache = true,
15480                Keyword::SQL_CALC_FOUND_ROWS => modifiers.sql_calc_found_rows = true,
15481                _ => {
15482                    self.prev_token();
15483                    return self.expected_ref(
15484                        "HIGH_PRIORITY, STRAIGHT_JOIN, or other MySQL select modifier",
15485                        self.peek_token_ref(),
15486                    );
15487                }
15488            }
15489        }
15490
15491        // Avoid polluting the AST with `Some(SelectModifiers::default())` empty value unless there
15492        // actually were some modifiers set.
15493        let select_modifiers = if modifiers.is_any_set() {
15494            Some(modifiers)
15495        } else {
15496            None
15497        };
15498        Ok((select_modifiers, distinct))
15499    }
15500
15501    fn parse_value_table_mode(&mut self) -> Result<Option<ValueTableMode>, ParserError> {
15502        if !dialect_of!(self is BigQueryDialect) {
15503            return Ok(None);
15504        }
15505
15506        let mode = if self.parse_keywords(&[Keyword::DISTINCT, Keyword::AS, Keyword::VALUE]) {
15507            Some(ValueTableMode::DistinctAsValue)
15508        } else if self.parse_keywords(&[Keyword::DISTINCT, Keyword::AS, Keyword::STRUCT]) {
15509            Some(ValueTableMode::DistinctAsStruct)
15510        } else if self.parse_keywords(&[Keyword::AS, Keyword::VALUE])
15511            || self.parse_keywords(&[Keyword::ALL, Keyword::AS, Keyword::VALUE])
15512        {
15513            Some(ValueTableMode::AsValue)
15514        } else if self.parse_keywords(&[Keyword::AS, Keyword::STRUCT])
15515            || self.parse_keywords(&[Keyword::ALL, Keyword::AS, Keyword::STRUCT])
15516        {
15517            Some(ValueTableMode::AsStruct)
15518        } else if self.parse_keyword(Keyword::AS) {
15519            self.expected_ref("VALUE or STRUCT", self.peek_token_ref())?
15520        } else {
15521            None
15522        };
15523
15524        Ok(mode)
15525    }
15526
15527    /// Invoke `f` after first setting the parser's `ParserState` to `state`.
15528    ///
15529    /// Upon return, restores the parser's state to what it started at.
15530    fn with_state<T, F>(&mut self, state: ParserState, mut f: F) -> Result<T, ParserError>
15531    where
15532        F: FnMut(&mut Parser) -> Result<T, ParserError>,
15533    {
15534        let current_state = self.state;
15535        self.state = state;
15536        let res = f(self);
15537        self.state = current_state;
15538        res
15539    }
15540
15541    /// Parse a `CONNECT BY` clause (Oracle-style hierarchical query support).
15542    pub fn maybe_parse_connect_by(&mut self) -> Result<Vec<ConnectByKind>, ParserError> {
15543        let mut clauses = Vec::with_capacity(2);
15544        loop {
15545            if let Some(idx) = self.parse_keywords_indexed(&[Keyword::START, Keyword::WITH]) {
15546                clauses.push(ConnectByKind::StartWith {
15547                    start_token: self.token_at(idx).clone().into(),
15548                    condition: self.parse_expr()?.into(),
15549                });
15550            } else if let Some(idx) = self.parse_keywords_indexed(&[Keyword::CONNECT, Keyword::BY])
15551            {
15552                clauses.push(ConnectByKind::ConnectBy {
15553                    connect_token: self.token_at(idx).clone().into(),
15554                    nocycle: self.parse_keyword(Keyword::NOCYCLE),
15555                    relationships: self.with_state(ParserState::ConnectBy, |parser| {
15556                        parser.parse_comma_separated(Parser::parse_expr)
15557                    })?,
15558                });
15559            } else {
15560                break;
15561            }
15562        }
15563        Ok(clauses)
15564    }
15565
15566    /// Parse `CREATE TABLE x AS TABLE y`
15567    pub fn parse_as_table(&mut self) -> Result<Table, ParserError> {
15568        let token1 = self.next_token();
15569        let token2 = self.next_token();
15570        let token3 = self.next_token();
15571
15572        let table_name;
15573        let schema_name;
15574        if token2 == Token::Period {
15575            match token1.token {
15576                Token::Word(w) => {
15577                    schema_name = w.value;
15578                }
15579                _ => {
15580                    return self.expected("Schema name", token1);
15581                }
15582            }
15583            match token3.token {
15584                Token::Word(w) => {
15585                    table_name = w.value;
15586                }
15587                _ => {
15588                    return self.expected("Table name", token3);
15589                }
15590            }
15591            Ok(Table {
15592                table_name: Some(table_name),
15593                schema_name: Some(schema_name),
15594            })
15595        } else {
15596            match token1.token {
15597                Token::Word(w) => {
15598                    table_name = w.value;
15599                }
15600                _ => {
15601                    return self.expected("Table name", token1);
15602                }
15603            }
15604            Ok(Table {
15605                table_name: Some(table_name),
15606                schema_name: None,
15607            })
15608        }
15609    }
15610
15611    /// Parse a `SET ROLE` statement. Expects SET to be consumed already.
15612    fn parse_set_role(
15613        &mut self,
15614        modifier: Option<ContextModifier>,
15615    ) -> Result<Statement, ParserError> {
15616        self.expect_keyword_is(Keyword::ROLE)?;
15617
15618        let role_name = if self.parse_keyword(Keyword::NONE) {
15619            None
15620        } else {
15621            Some(self.parse_identifier()?)
15622        };
15623        Ok(Statement::Set(Set::SetRole {
15624            context_modifier: modifier,
15625            role_name,
15626        }))
15627    }
15628
15629    fn parse_set_values(
15630        &mut self,
15631        parenthesized_assignment: bool,
15632    ) -> Result<Vec<Expr>, ParserError> {
15633        let mut values = vec![];
15634
15635        if parenthesized_assignment {
15636            self.expect_token(&Token::LParen)?;
15637        }
15638
15639        loop {
15640            let value = if let Some(expr) = self.try_parse_expr_sub_query()? {
15641                expr
15642            } else if let Ok(expr) = self.parse_expr() {
15643                expr
15644            } else {
15645                self.expected_ref("variable value", self.peek_token_ref())?
15646            };
15647
15648            values.push(value);
15649            if self.consume_token(&Token::Comma) {
15650                continue;
15651            }
15652
15653            if parenthesized_assignment {
15654                self.expect_token(&Token::RParen)?;
15655            }
15656            return Ok(values);
15657        }
15658    }
15659
15660    fn parse_context_modifier(&mut self) -> Option<ContextModifier> {
15661        let modifier =
15662            self.parse_one_of_keywords(&[Keyword::SESSION, Keyword::LOCAL, Keyword::GLOBAL])?;
15663
15664        Self::keyword_to_modifier(modifier)
15665    }
15666
15667    /// Parse a single SET statement assignment `var = expr`.
15668    fn parse_set_assignment(&mut self) -> Result<SetAssignment, ParserError> {
15669        let scope = self.parse_context_modifier();
15670
15671        let name = if self.dialect.supports_parenthesized_set_variables()
15672            && self.consume_token(&Token::LParen)
15673        {
15674            // Parenthesized assignments are handled in the `parse_set` function after
15675            // trying to parse list of assignments using this function.
15676            // If a dialect supports both, and we find a LParen, we early exit from this function.
15677            self.expected_ref("Unparenthesized assignment", self.peek_token_ref())?
15678        } else {
15679            self.parse_object_name(false)?
15680        };
15681
15682        if !(self.consume_token(&Token::Eq) || self.parse_keyword(Keyword::TO)) {
15683            return self.expected_ref("assignment operator", self.peek_token_ref());
15684        }
15685
15686        let value = self.parse_expr()?;
15687
15688        Ok(SetAssignment { scope, name, value })
15689    }
15690
15691    fn parse_set(&mut self) -> Result<Statement, ParserError> {
15692        let hivevar = self.parse_keyword(Keyword::HIVEVAR);
15693
15694        // Modifier is either HIVEVAR: or a ContextModifier (LOCAL, SESSION, etc), not both
15695        let scope = if !hivevar {
15696            self.parse_context_modifier()
15697        } else {
15698            None
15699        };
15700
15701        if hivevar {
15702            self.expect_token(&Token::Colon)?;
15703        }
15704
15705        if let Some(set_role_stmt) = self.maybe_parse(|parser| parser.parse_set_role(scope))? {
15706            return Ok(set_role_stmt);
15707        }
15708
15709        // Handle special cases first
15710        if self.parse_keywords(&[Keyword::TIME, Keyword::ZONE])
15711            || self.parse_keyword(Keyword::TIMEZONE)
15712        {
15713            if self.consume_token(&Token::Eq) || self.parse_keyword(Keyword::TO) {
15714                return Ok(Set::SingleAssignment {
15715                    scope,
15716                    hivevar,
15717                    variable: ObjectName::from(vec!["TIMEZONE".into()]),
15718                    values: self.parse_set_values(false)?,
15719                }
15720                .into());
15721            } else {
15722                // A shorthand alias for SET TIME ZONE that doesn't require
15723                // the assignment operator. It's originally PostgreSQL specific,
15724                // but we allow it for all the dialects
15725                return Ok(Set::SetTimeZone {
15726                    local: scope == Some(ContextModifier::Local),
15727                    value: self.parse_expr()?,
15728                }
15729                .into());
15730            }
15731        } else if self.dialect.supports_set_names() && self.parse_keyword(Keyword::NAMES) {
15732            if self.parse_keyword(Keyword::DEFAULT) {
15733                return Ok(Set::SetNamesDefault {}.into());
15734            }
15735            let charset_name = self.parse_identifier()?;
15736            let collation_name = if self.parse_one_of_keywords(&[Keyword::COLLATE]).is_some() {
15737                Some(self.parse_literal_string()?)
15738            } else {
15739                None
15740            };
15741
15742            return Ok(Set::SetNames {
15743                charset_name,
15744                collation_name,
15745            }
15746            .into());
15747        } else if self.parse_keyword(Keyword::CHARACTERISTICS) {
15748            self.expect_keywords(&[Keyword::AS, Keyword::TRANSACTION])?;
15749            return Ok(Set::SetTransaction {
15750                modes: self.parse_transaction_modes()?,
15751                snapshot: None,
15752                session: true,
15753            }
15754            .into());
15755        } else if self.parse_keyword(Keyword::TRANSACTION) {
15756            if self.parse_keyword(Keyword::SNAPSHOT) {
15757                let snapshot_id = self.parse_value()?;
15758                return Ok(Set::SetTransaction {
15759                    modes: vec![],
15760                    snapshot: Some(snapshot_id),
15761                    session: false,
15762                }
15763                .into());
15764            }
15765            return Ok(Set::SetTransaction {
15766                modes: self.parse_transaction_modes()?,
15767                snapshot: None,
15768                session: false,
15769            }
15770            .into());
15771        } else if self.parse_keyword(Keyword::AUTHORIZATION) {
15772            let scope = match scope {
15773                Some(s) => s,
15774                None => {
15775                    return self.expected_at(
15776                        "SESSION, LOCAL, or other scope modifier before AUTHORIZATION",
15777                        self.get_current_index(),
15778                    )
15779                }
15780            };
15781            let auth_value = if self.parse_keyword(Keyword::DEFAULT) {
15782                SetSessionAuthorizationParamKind::Default
15783            } else {
15784                let value = self.parse_identifier()?;
15785                SetSessionAuthorizationParamKind::User(value)
15786            };
15787            return Ok(Set::SetSessionAuthorization(SetSessionAuthorizationParam {
15788                scope,
15789                kind: auth_value,
15790            })
15791            .into());
15792        }
15793
15794        if self.dialect.supports_comma_separated_set_assignments() {
15795            if scope.is_some() {
15796                self.prev_token();
15797            }
15798
15799            if let Some(assignments) = self
15800                .maybe_parse(|parser| parser.parse_comma_separated(Parser::parse_set_assignment))?
15801            {
15802                return if assignments.len() > 1 {
15803                    Ok(Set::MultipleAssignments { assignments }.into())
15804                } else {
15805                    let SetAssignment { scope, name, value } =
15806                        assignments.into_iter().next().ok_or_else(|| {
15807                            ParserError::ParserError("Expected at least one assignment".to_string())
15808                        })?;
15809
15810                    Ok(Set::SingleAssignment {
15811                        scope,
15812                        hivevar,
15813                        variable: name,
15814                        values: vec![value],
15815                    }
15816                    .into())
15817                };
15818            }
15819        }
15820
15821        let variables = if self.dialect.supports_parenthesized_set_variables()
15822            && self.consume_token(&Token::LParen)
15823        {
15824            let vars = OneOrManyWithParens::Many(
15825                self.parse_comma_separated(|parser: &mut Parser<'a>| parser.parse_identifier())?
15826                    .into_iter()
15827                    .map(|ident| ObjectName::from(vec![ident]))
15828                    .collect(),
15829            );
15830            self.expect_token(&Token::RParen)?;
15831            vars
15832        } else {
15833            OneOrManyWithParens::One(self.parse_object_name(false)?)
15834        };
15835
15836        if self.consume_token(&Token::Eq) || self.parse_keyword(Keyword::TO) {
15837            let stmt = match variables {
15838                OneOrManyWithParens::One(var) => Set::SingleAssignment {
15839                    scope,
15840                    hivevar,
15841                    variable: var,
15842                    values: self.parse_set_values(false)?,
15843                },
15844                OneOrManyWithParens::Many(vars) => Set::ParenthesizedAssignments {
15845                    variables: vars,
15846                    values: self.parse_set_values(true)?,
15847                },
15848            };
15849
15850            return Ok(stmt.into());
15851        }
15852
15853        if self.dialect.supports_set_stmt_without_operator() {
15854            self.prev_token();
15855            return self.parse_set_session_params();
15856        };
15857
15858        self.expected_ref("equals sign or TO", self.peek_token_ref())
15859    }
15860
15861    /// Parse session parameter assignments after `SET` when no `=` or `TO` is present.
15862    pub fn parse_set_session_params(&mut self) -> Result<Statement, ParserError> {
15863        if self.parse_keyword(Keyword::STATISTICS) {
15864            let topic = match self.parse_one_of_keywords(&[
15865                Keyword::IO,
15866                Keyword::PROFILE,
15867                Keyword::TIME,
15868                Keyword::XML,
15869            ]) {
15870                Some(Keyword::IO) => SessionParamStatsTopic::IO,
15871                Some(Keyword::PROFILE) => SessionParamStatsTopic::Profile,
15872                Some(Keyword::TIME) => SessionParamStatsTopic::Time,
15873                Some(Keyword::XML) => SessionParamStatsTopic::Xml,
15874                _ => return self.expected_ref("IO, PROFILE, TIME or XML", self.peek_token_ref()),
15875            };
15876            let value = self.parse_session_param_value()?;
15877            Ok(
15878                Set::SetSessionParam(SetSessionParamKind::Statistics(SetSessionParamStatistics {
15879                    topic,
15880                    value,
15881                }))
15882                .into(),
15883            )
15884        } else if self.parse_keyword(Keyword::IDENTITY_INSERT) {
15885            let obj = self.parse_object_name(false)?;
15886            let value = self.parse_session_param_value()?;
15887            Ok(Set::SetSessionParam(SetSessionParamKind::IdentityInsert(
15888                SetSessionParamIdentityInsert { obj, value },
15889            ))
15890            .into())
15891        } else if self.parse_keyword(Keyword::OFFSETS) {
15892            let keywords = self.parse_comma_separated(|parser| {
15893                let next_token = parser.next_token();
15894                match &next_token.token {
15895                    Token::Word(w) => Ok(w.to_string()),
15896                    _ => parser.expected("SQL keyword", next_token),
15897                }
15898            })?;
15899            let value = self.parse_session_param_value()?;
15900            Ok(
15901                Set::SetSessionParam(SetSessionParamKind::Offsets(SetSessionParamOffsets {
15902                    keywords,
15903                    value,
15904                }))
15905                .into(),
15906            )
15907        } else {
15908            let names = self.parse_comma_separated(|parser| {
15909                let next_token = parser.next_token();
15910                match next_token.token {
15911                    Token::Word(w) => Ok(w.to_string()),
15912                    _ => parser.expected("Session param name", next_token),
15913                }
15914            })?;
15915            let value = self.parse_expr()?.to_string();
15916            Ok(
15917                Set::SetSessionParam(SetSessionParamKind::Generic(SetSessionParamGeneric {
15918                    names,
15919                    value,
15920                }))
15921                .into(),
15922            )
15923        }
15924    }
15925
15926    fn parse_session_param_value(&mut self) -> Result<SessionParamValue, ParserError> {
15927        if self.parse_keyword(Keyword::ON) {
15928            Ok(SessionParamValue::On)
15929        } else if self.parse_keyword(Keyword::OFF) {
15930            Ok(SessionParamValue::Off)
15931        } else {
15932            self.expected_ref("ON or OFF", self.peek_token_ref())
15933        }
15934    }
15935
15936    /// Parse a `SHOW` statement and dispatch to specific SHOW handlers.
15937    pub fn parse_show(&mut self) -> Result<Statement, ParserError> {
15938        let terse = self.parse_keyword(Keyword::TERSE);
15939        let extended = self.parse_keyword(Keyword::EXTENDED);
15940        let full = self.parse_keyword(Keyword::FULL);
15941        let session = self.parse_keyword(Keyword::SESSION);
15942        let global = self.parse_keyword(Keyword::GLOBAL);
15943        let external = self.parse_keyword(Keyword::EXTERNAL);
15944        if self
15945            .parse_one_of_keywords(&[Keyword::COLUMNS, Keyword::FIELDS])
15946            .is_some()
15947        {
15948            Ok(self.parse_show_columns(extended, full)?)
15949        } else if self.parse_keyword(Keyword::TABLES) {
15950            Ok(self.parse_show_tables(terse, extended, full, external)?)
15951        } else if self.parse_keywords(&[Keyword::MATERIALIZED, Keyword::VIEWS]) {
15952            Ok(self.parse_show_views(terse, true)?)
15953        } else if self.parse_keyword(Keyword::VIEWS) {
15954            Ok(self.parse_show_views(terse, false)?)
15955        } else if self.parse_keyword(Keyword::FUNCTIONS) {
15956            Ok(self.parse_show_functions()?)
15957        } else if self.parse_keyword(Keyword::PROCESSLIST) {
15958            Ok(Statement::ShowProcessList { full })
15959        } else if extended || full {
15960            Err(ParserError::ParserError(
15961                "EXTENDED/FULL are not supported with this type of SHOW query".to_string(),
15962            ))
15963        } else if self.parse_one_of_keywords(&[Keyword::CREATE]).is_some() {
15964            Ok(self.parse_show_create()?)
15965        } else if self.parse_keyword(Keyword::COLLATION) {
15966            Ok(self.parse_show_collation()?)
15967        } else if self.parse_keyword(Keyword::VARIABLES)
15968            && dialect_of!(self is MySqlDialect | GenericDialect)
15969        {
15970            Ok(Statement::ShowVariables {
15971                filter: self.parse_show_statement_filter()?,
15972                session,
15973                global,
15974            })
15975        } else if self.parse_keyword(Keyword::STATUS)
15976            && dialect_of!(self is MySqlDialect | GenericDialect)
15977        {
15978            Ok(Statement::ShowStatus {
15979                filter: self.parse_show_statement_filter()?,
15980                session,
15981                global,
15982            })
15983        } else if self.parse_keyword(Keyword::CATALOGS) {
15984            self.parse_show_catalogs(terse)
15985        } else if self.parse_keyword(Keyword::DATABASES) {
15986            self.parse_show_databases(terse)
15987        } else if self.parse_keyword(Keyword::SCHEMAS) {
15988            self.parse_show_schemas(terse)
15989        } else if self.parse_keywords(&[Keyword::CHARACTER, Keyword::SET]) {
15990            self.parse_show_charset(false)
15991        } else if self.parse_keyword(Keyword::CHARSET) {
15992            self.parse_show_charset(true)
15993        } else {
15994            Ok(Statement::ShowVariable {
15995                variable: self.parse_identifiers()?,
15996            })
15997        }
15998    }
15999
16000    fn parse_show_charset(&mut self, is_shorthand: bool) -> Result<Statement, ParserError> {
16001        // parse one of keywords
16002        Ok(Statement::ShowCharset(ShowCharset {
16003            is_shorthand,
16004            filter: self.parse_show_statement_filter()?,
16005        }))
16006    }
16007
16008    fn parse_show_catalogs(&mut self, terse: bool) -> Result<Statement, ParserError> {
16009        let history = self.parse_keyword(Keyword::HISTORY);
16010        let show_options = self.parse_show_stmt_options()?;
16011        Ok(Statement::ShowCatalogs {
16012            terse,
16013            history,
16014            show_options,
16015        })
16016    }
16017
16018    fn parse_show_databases(&mut self, terse: bool) -> Result<Statement, ParserError> {
16019        let history = self.parse_keyword(Keyword::HISTORY);
16020        let show_options = self.parse_show_stmt_options()?;
16021        Ok(Statement::ShowDatabases {
16022            terse,
16023            history,
16024            show_options,
16025        })
16026    }
16027
16028    fn parse_show_schemas(&mut self, terse: bool) -> Result<Statement, ParserError> {
16029        let history = self.parse_keyword(Keyword::HISTORY);
16030        let show_options = self.parse_show_stmt_options()?;
16031        Ok(Statement::ShowSchemas {
16032            terse,
16033            history,
16034            show_options,
16035        })
16036    }
16037
16038    /// Parse `SHOW CREATE <object>` returning the corresponding `ShowCreate` statement.
16039    pub fn parse_show_create(&mut self) -> Result<Statement, ParserError> {
16040        let obj_type = match self.expect_one_of_keywords(&[
16041            Keyword::TABLE,
16042            Keyword::TRIGGER,
16043            Keyword::FUNCTION,
16044            Keyword::PROCEDURE,
16045            Keyword::EVENT,
16046            Keyword::VIEW,
16047        ])? {
16048            Keyword::TABLE => Ok(ShowCreateObject::Table),
16049            Keyword::TRIGGER => Ok(ShowCreateObject::Trigger),
16050            Keyword::FUNCTION => Ok(ShowCreateObject::Function),
16051            Keyword::PROCEDURE => Ok(ShowCreateObject::Procedure),
16052            Keyword::EVENT => Ok(ShowCreateObject::Event),
16053            Keyword::VIEW => Ok(ShowCreateObject::View),
16054            keyword => Err(ParserError::ParserError(format!(
16055                "Unable to map keyword to ShowCreateObject: {keyword:?}"
16056            ))),
16057        }?;
16058
16059        let obj_name = self.parse_object_name(false)?;
16060
16061        Ok(Statement::ShowCreate { obj_type, obj_name })
16062    }
16063
16064    /// Parse `SHOW COLUMNS`/`SHOW FIELDS` and return a `ShowColumns` statement.
16065    pub fn parse_show_columns(
16066        &mut self,
16067        extended: bool,
16068        full: bool,
16069    ) -> Result<Statement, ParserError> {
16070        let show_options = self.parse_show_stmt_options()?;
16071        Ok(Statement::ShowColumns {
16072            extended,
16073            full,
16074            show_options,
16075        })
16076    }
16077
16078    fn parse_show_tables(
16079        &mut self,
16080        terse: bool,
16081        extended: bool,
16082        full: bool,
16083        external: bool,
16084    ) -> Result<Statement, ParserError> {
16085        let history = !external && self.parse_keyword(Keyword::HISTORY);
16086        let show_options = self.parse_show_stmt_options()?;
16087        Ok(Statement::ShowTables {
16088            terse,
16089            history,
16090            extended,
16091            full,
16092            external,
16093            show_options,
16094        })
16095    }
16096
16097    fn parse_show_views(
16098        &mut self,
16099        terse: bool,
16100        materialized: bool,
16101    ) -> Result<Statement, ParserError> {
16102        let show_options = self.parse_show_stmt_options()?;
16103        Ok(Statement::ShowViews {
16104            materialized,
16105            terse,
16106            show_options,
16107        })
16108    }
16109
16110    /// Parse `SHOW FUNCTIONS` and optional filter.
16111    pub fn parse_show_functions(&mut self) -> Result<Statement, ParserError> {
16112        let filter = self.parse_show_statement_filter()?;
16113        Ok(Statement::ShowFunctions { filter })
16114    }
16115
16116    /// Parse `SHOW COLLATION` and optional filter.
16117    pub fn parse_show_collation(&mut self) -> Result<Statement, ParserError> {
16118        let filter = self.parse_show_statement_filter()?;
16119        Ok(Statement::ShowCollation { filter })
16120    }
16121
16122    /// Parse an optional filter used by `SHOW` statements (LIKE, ILIKE, WHERE, or literal).
16123    pub fn parse_show_statement_filter(
16124        &mut self,
16125    ) -> Result<Option<ShowStatementFilter>, ParserError> {
16126        if self.parse_keyword(Keyword::LIKE) {
16127            Ok(Some(ShowStatementFilter::Like(
16128                self.parse_literal_string()?,
16129            )))
16130        } else if self.parse_keyword(Keyword::ILIKE) {
16131            Ok(Some(ShowStatementFilter::ILike(
16132                self.parse_literal_string()?,
16133            )))
16134        } else if self.parse_keyword(Keyword::WHERE) {
16135            Ok(Some(ShowStatementFilter::Where(self.parse_expr()?)))
16136        } else {
16137            self.maybe_parse(|parser| -> Result<String, ParserError> {
16138                parser.parse_literal_string()
16139            })?
16140            .map_or(Ok(None), |filter| {
16141                Ok(Some(ShowStatementFilter::NoKeyword(filter)))
16142            })
16143        }
16144    }
16145
16146    /// Parse a `USE` statement (database/catalog/schema/warehouse/role selection).
16147    pub fn parse_use(&mut self) -> Result<Statement, ParserError> {
16148        // Determine which keywords are recognized by the current dialect
16149        let parsed_keyword = if dialect_of!(self is HiveDialect) {
16150            // HiveDialect accepts USE DEFAULT; statement without any db specified
16151            if self.parse_keyword(Keyword::DEFAULT) {
16152                return Ok(Statement::Use(Use::Default));
16153            }
16154            None // HiveDialect doesn't expect any other specific keyword after `USE`
16155        } else if dialect_of!(self is DatabricksDialect) {
16156            self.parse_one_of_keywords(&[Keyword::CATALOG, Keyword::DATABASE, Keyword::SCHEMA])
16157        } else if dialect_of!(self is SnowflakeDialect) {
16158            self.parse_one_of_keywords(&[
16159                Keyword::DATABASE,
16160                Keyword::SCHEMA,
16161                Keyword::WAREHOUSE,
16162                Keyword::ROLE,
16163                Keyword::SECONDARY,
16164            ])
16165        } else {
16166            None // No specific keywords for other dialects, including GenericDialect
16167        };
16168
16169        let result = if matches!(parsed_keyword, Some(Keyword::SECONDARY)) {
16170            self.parse_secondary_roles()?
16171        } else {
16172            let obj_name = self.parse_object_name(false)?;
16173            match parsed_keyword {
16174                Some(Keyword::CATALOG) => Use::Catalog(obj_name),
16175                Some(Keyword::DATABASE) => Use::Database(obj_name),
16176                Some(Keyword::SCHEMA) => Use::Schema(obj_name),
16177                Some(Keyword::WAREHOUSE) => Use::Warehouse(obj_name),
16178                Some(Keyword::ROLE) => Use::Role(obj_name),
16179                _ => Use::Object(obj_name),
16180            }
16181        };
16182
16183        Ok(Statement::Use(result))
16184    }
16185
16186    fn parse_secondary_roles(&mut self) -> Result<Use, ParserError> {
16187        self.expect_one_of_keywords(&[Keyword::ROLES, Keyword::ROLE])?;
16188        if self.parse_keyword(Keyword::NONE) {
16189            Ok(Use::SecondaryRoles(SecondaryRoles::None))
16190        } else if self.parse_keyword(Keyword::ALL) {
16191            Ok(Use::SecondaryRoles(SecondaryRoles::All))
16192        } else {
16193            let roles = self.parse_comma_separated(|parser| parser.parse_identifier())?;
16194            Ok(Use::SecondaryRoles(SecondaryRoles::List(roles)))
16195        }
16196    }
16197
16198    /// Parse a table factor followed by any join clauses, returning `TableWithJoins`.
16199    pub fn parse_table_and_joins(&mut self) -> Result<TableWithJoins, ParserError> {
16200        let relation = self.parse_table_factor()?;
16201        // Note that for keywords to be properly handled here, they need to be
16202        // added to `RESERVED_FOR_TABLE_ALIAS`, otherwise they may be parsed as
16203        // a table alias.
16204        let joins = self.parse_joins()?;
16205        Ok(TableWithJoins { relation, joins })
16206    }
16207
16208    fn parse_joins(&mut self) -> Result<Vec<Join>, ParserError> {
16209        let mut joins = vec![];
16210        loop {
16211            let global = self.parse_keyword(Keyword::GLOBAL);
16212            let join = if self.parse_keyword(Keyword::CROSS) {
16213                let join_operator = if self.parse_keyword(Keyword::JOIN) {
16214                    JoinOperator::CrossJoin(JoinConstraint::None)
16215                } else if self.parse_keyword(Keyword::APPLY) {
16216                    // MSSQL extension, similar to CROSS JOIN LATERAL
16217                    JoinOperator::CrossApply
16218                } else {
16219                    return self.expected_ref("JOIN or APPLY after CROSS", self.peek_token_ref());
16220                };
16221                let relation = self.parse_table_factor()?;
16222                let join_operator = if matches!(join_operator, JoinOperator::CrossJoin(_))
16223                    && self.dialect.supports_cross_join_constraint()
16224                {
16225                    let constraint = self.parse_join_constraint(false)?;
16226                    JoinOperator::CrossJoin(constraint)
16227                } else {
16228                    join_operator
16229                };
16230                Join {
16231                    relation,
16232                    global,
16233                    join_operator,
16234                }
16235            } else if self.parse_keyword(Keyword::OUTER) {
16236                // MSSQL extension, similar to LEFT JOIN LATERAL .. ON 1=1
16237                self.expect_keyword_is(Keyword::APPLY)?;
16238                Join {
16239                    relation: self.parse_table_factor()?,
16240                    global,
16241                    join_operator: JoinOperator::OuterApply,
16242                }
16243            } else if self.parse_keyword(Keyword::ASOF) {
16244                self.expect_keyword_is(Keyword::JOIN)?;
16245                let relation = self.parse_table_factor()?;
16246                self.expect_keyword_is(Keyword::MATCH_CONDITION)?;
16247                let match_condition = self.parse_parenthesized(Self::parse_expr)?;
16248                Join {
16249                    relation,
16250                    global,
16251                    join_operator: JoinOperator::AsOf {
16252                        match_condition,
16253                        constraint: self.parse_join_constraint(false)?,
16254                    },
16255                }
16256            } else if self.dialect.supports_array_join_syntax()
16257                && self.parse_keywords(&[Keyword::INNER, Keyword::ARRAY, Keyword::JOIN])
16258            {
16259                // ClickHouse: INNER ARRAY JOIN
16260                Join {
16261                    relation: self.parse_table_factor()?,
16262                    global,
16263                    join_operator: JoinOperator::InnerArrayJoin,
16264                }
16265            } else if self.dialect.supports_array_join_syntax()
16266                && self.parse_keywords(&[Keyword::LEFT, Keyword::ARRAY, Keyword::JOIN])
16267            {
16268                // ClickHouse: LEFT ARRAY JOIN
16269                Join {
16270                    relation: self.parse_table_factor()?,
16271                    global,
16272                    join_operator: JoinOperator::LeftArrayJoin,
16273                }
16274            } else if self.dialect.supports_array_join_syntax()
16275                && self.parse_keywords(&[Keyword::ARRAY, Keyword::JOIN])
16276            {
16277                // ClickHouse: ARRAY JOIN
16278                Join {
16279                    relation: self.parse_table_factor()?,
16280                    global,
16281                    join_operator: JoinOperator::ArrayJoin,
16282                }
16283            } else {
16284                let natural = self.parse_keyword(Keyword::NATURAL);
16285                let peek_keyword = if let Token::Word(w) = &self.peek_token_ref().token {
16286                    w.keyword
16287                } else {
16288                    Keyword::NoKeyword
16289                };
16290
16291                let join_operator_type = match peek_keyword {
16292                    Keyword::INNER | Keyword::JOIN => {
16293                        let inner = self.parse_keyword(Keyword::INNER); // [ INNER ]
16294                        self.expect_keyword_is(Keyword::JOIN)?;
16295                        if inner {
16296                            JoinOperator::Inner
16297                        } else {
16298                            JoinOperator::Join
16299                        }
16300                    }
16301                    kw @ Keyword::LEFT | kw @ Keyword::RIGHT => {
16302                        let _ = self.next_token(); // consume LEFT/RIGHT
16303                        let is_left = kw == Keyword::LEFT;
16304                        let join_type = self.parse_one_of_keywords(&[
16305                            Keyword::OUTER,
16306                            Keyword::SEMI,
16307                            Keyword::ANTI,
16308                            Keyword::JOIN,
16309                        ]);
16310                        match join_type {
16311                            Some(Keyword::OUTER) => {
16312                                self.expect_keyword_is(Keyword::JOIN)?;
16313                                if is_left {
16314                                    JoinOperator::LeftOuter
16315                                } else {
16316                                    JoinOperator::RightOuter
16317                                }
16318                            }
16319                            Some(Keyword::SEMI) => {
16320                                self.expect_keyword_is(Keyword::JOIN)?;
16321                                if is_left {
16322                                    JoinOperator::LeftSemi
16323                                } else {
16324                                    JoinOperator::RightSemi
16325                                }
16326                            }
16327                            Some(Keyword::ANTI) => {
16328                                self.expect_keyword_is(Keyword::JOIN)?;
16329                                if is_left {
16330                                    JoinOperator::LeftAnti
16331                                } else {
16332                                    JoinOperator::RightAnti
16333                                }
16334                            }
16335                            Some(Keyword::JOIN) => {
16336                                if is_left {
16337                                    JoinOperator::Left
16338                                } else {
16339                                    JoinOperator::Right
16340                                }
16341                            }
16342                            _ => {
16343                                return Err(ParserError::ParserError(format!(
16344                                    "expected OUTER, SEMI, ANTI or JOIN after {kw:?}"
16345                                )))
16346                            }
16347                        }
16348                    }
16349                    Keyword::ANTI => {
16350                        let _ = self.next_token(); // consume ANTI
16351                        self.expect_keyword_is(Keyword::JOIN)?;
16352                        JoinOperator::Anti
16353                    }
16354                    Keyword::SEMI => {
16355                        let _ = self.next_token(); // consume SEMI
16356                        self.expect_keyword_is(Keyword::JOIN)?;
16357                        JoinOperator::Semi
16358                    }
16359                    Keyword::FULL => {
16360                        let _ = self.next_token(); // consume FULL
16361                        let _ = self.parse_keyword(Keyword::OUTER); // [ OUTER ]
16362                        self.expect_keyword_is(Keyword::JOIN)?;
16363                        JoinOperator::FullOuter
16364                    }
16365                    Keyword::OUTER => {
16366                        return self.expected_ref("LEFT, RIGHT, or FULL", self.peek_token_ref());
16367                    }
16368                    Keyword::STRAIGHT_JOIN => {
16369                        let _ = self.next_token(); // consume STRAIGHT_JOIN
16370                        JoinOperator::StraightJoin
16371                    }
16372                    _ if natural => {
16373                        return self
16374                            .expected_ref("a join type after NATURAL", self.peek_token_ref());
16375                    }
16376                    _ => break,
16377                };
16378                let mut relation = self.parse_table_factor()?;
16379
16380                if !self
16381                    .dialect
16382                    .supports_left_associative_joins_without_parens()
16383                    && !natural
16384                    && self.peek_parens_less_nested_join()
16385                {
16386                    let joins = self.parse_joins()?;
16387                    relation = TableFactor::NestedJoin {
16388                        table_with_joins: Box::new(TableWithJoins { relation, joins }),
16389                        alias: None,
16390                    };
16391                }
16392
16393                let join_constraint = self.parse_join_constraint(natural)?;
16394                Join {
16395                    relation,
16396                    global,
16397                    join_operator: join_operator_type(join_constraint),
16398                }
16399            };
16400            joins.push(join);
16401        }
16402        Ok(joins)
16403    }
16404
16405    fn peek_parens_less_nested_join(&self) -> bool {
16406        matches!(
16407            self.peek_token_ref().token,
16408            Token::Word(Word {
16409                keyword: Keyword::JOIN
16410                    | Keyword::INNER
16411                    | Keyword::LEFT
16412                    | Keyword::RIGHT
16413                    | Keyword::FULL,
16414                ..
16415            })
16416        )
16417    }
16418
16419    /// A table name or a parenthesized subquery, followed by optional `[AS] alias`
16420    #[cfg_attr(feature = "recursive-protection", recursive::recursive)]
16421    pub fn parse_table_factor(&mut self) -> Result<TableFactor, ParserError> {
16422        let _guard = self.recursion_counter.try_decrease()?;
16423        if self.parse_keyword(Keyword::LATERAL) {
16424            // LATERAL must always be followed by a subquery or table function.
16425            if self.consume_token(&Token::LParen) {
16426                self.parse_derived_table_factor(Lateral)
16427            } else {
16428                let name = self.parse_object_name(false)?;
16429                self.expect_token(&Token::LParen)?;
16430                let args = self.parse_optional_args()?;
16431                let with_ordinality = self.parse_keywords(&[Keyword::WITH, Keyword::ORDINALITY]);
16432                let alias = self.maybe_parse_table_alias()?;
16433                Ok(TableFactor::Function {
16434                    lateral: true,
16435                    name,
16436                    args,
16437                    with_ordinality,
16438                    alias,
16439                })
16440            }
16441        } else if self.parse_keyword(Keyword::TABLE) {
16442            // parse table function (SELECT * FROM TABLE (<expr>) [ AS <alias> ])
16443            self.expect_token(&Token::LParen)?;
16444            let expr = self.parse_expr()?;
16445            self.expect_token(&Token::RParen)?;
16446            let alias = self.maybe_parse_table_alias()?;
16447            Ok(TableFactor::TableFunction { expr, alias })
16448        } else if self.consume_token(&Token::LParen) {
16449            // A left paren introduces either a derived table (i.e., a subquery)
16450            // or a nested join. It's nearly impossible to determine ahead of
16451            // time which it is... so we just try to parse both.
16452            //
16453            // Here's an example that demonstrates the complexity:
16454            //                     /-------------------------------------------------------\
16455            //                     | /-----------------------------------\                 |
16456            //     SELECT * FROM ( ( ( (SELECT 1) UNION (SELECT 2) ) AS t1 NATURAL JOIN t2 ) )
16457            //                   ^ ^ ^ ^
16458            //                   | | | |
16459            //                   | | | |
16460            //                   | | | (4) belongs to a SetExpr::Query inside the subquery
16461            //                   | | (3) starts a derived table (subquery)
16462            //                   | (2) starts a nested join
16463            //                   (1) an additional set of parens around a nested join
16464            //
16465
16466            // If the recently consumed '(' starts a derived table, the call to
16467            // `parse_derived_table_factor` below will return success after parsing the
16468            // subquery, followed by the closing ')', and the alias of the derived table.
16469            // In the example above this is case (3).
16470            //
16471            // Memoize failures to break the 2^N work on inputs like
16472            // `FROM ((((...`, where the nested-join fallback recurses back into
16473            // `parse_table_factor` and re-attempts the same speculative parse.
16474            let derived_pos = self.index;
16475            let derived = if self
16476                .failed_derived_table_factor_positions
16477                .contains(&derived_pos)
16478            {
16479                None
16480            } else {
16481                match self.maybe_parse(|parser| parser.parse_derived_table_factor(NotLateral))? {
16482                    Some(t) => Some(t),
16483                    None => {
16484                        self.failed_derived_table_factor_positions
16485                            .insert(derived_pos);
16486                        None
16487                    }
16488                }
16489            };
16490            if let Some(mut table) = derived {
16491                while let Some(kw) = self.parse_one_of_keywords(&[Keyword::PIVOT, Keyword::UNPIVOT])
16492                {
16493                    table = match kw {
16494                        Keyword::PIVOT => self.parse_pivot_table_factor(table)?,
16495                        Keyword::UNPIVOT => self.parse_unpivot_table_factor(table)?,
16496                        unexpected_keyword => return Err(ParserError::ParserError(
16497                            format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in pivot/unpivot"),
16498                        )),
16499                    }
16500                }
16501                return Ok(table);
16502            }
16503
16504            // A parsing error from `parse_derived_table_factor` indicates that the '(' we've
16505            // recently consumed does not start a derived table (cases 1, 2, or 4).
16506            // `maybe_parse` will ignore such an error and rewind to be after the opening '('.
16507
16508            // Inside the parentheses we expect to find an (A) table factor
16509            // followed by some joins or (B) another level of nesting.
16510            let mut table_and_joins = self.parse_table_and_joins()?;
16511
16512            #[allow(clippy::if_same_then_else)]
16513            if !table_and_joins.joins.is_empty() {
16514                self.expect_token(&Token::RParen)?;
16515                let alias = self.maybe_parse_table_alias()?;
16516                Ok(TableFactor::NestedJoin {
16517                    table_with_joins: Box::new(table_and_joins),
16518                    alias,
16519                }) // (A)
16520            } else if let TableFactor::NestedJoin {
16521                table_with_joins: _,
16522                alias: _,
16523            } = &table_and_joins.relation
16524            {
16525                // (B): `table_and_joins` (what we found inside the parentheses)
16526                // is a nested join `(foo JOIN bar)`, not followed by other joins.
16527                self.expect_token(&Token::RParen)?;
16528                let alias = self.maybe_parse_table_alias()?;
16529                Ok(TableFactor::NestedJoin {
16530                    table_with_joins: Box::new(table_and_joins),
16531                    alias,
16532                })
16533            } else if self.dialect.supports_parens_around_table_factor() {
16534                // Dialect-specific behavior: Snowflake diverges from the
16535                // standard and from most of the other implementations by
16536                // allowing extra parentheses not only around a join (B), but
16537                // around lone table names (e.g. `FROM (mytable [AS alias])`)
16538                // and around derived tables (e.g. `FROM ((SELECT ...)
16539                // [AS alias])`) as well.
16540                self.expect_token(&Token::RParen)?;
16541
16542                if let Some(outer_alias) = self.maybe_parse_table_alias()? {
16543                    // Snowflake also allows specifying an alias *after* parens
16544                    // e.g. `FROM (mytable) AS alias`
16545                    match &mut table_and_joins.relation {
16546                        TableFactor::Derived { alias, .. }
16547                        | TableFactor::Table { alias, .. }
16548                        | TableFactor::Function { alias, .. }
16549                        | TableFactor::UNNEST { alias, .. }
16550                        | TableFactor::JsonTable { alias, .. }
16551                        | TableFactor::XmlTable { alias, .. }
16552                        | TableFactor::OpenJsonTable { alias, .. }
16553                        | TableFactor::TableFunction { alias, .. }
16554                        | TableFactor::Pivot { alias, .. }
16555                        | TableFactor::Unpivot { alias, .. }
16556                        | TableFactor::MatchRecognize { alias, .. }
16557                        | TableFactor::SemanticView { alias, .. }
16558                        | TableFactor::NestedJoin { alias, .. } => {
16559                            // but not `FROM (mytable AS alias1) AS alias2`.
16560                            if let Some(inner_alias) = alias {
16561                                return Err(ParserError::ParserError(format!(
16562                                    "duplicate alias {inner_alias}"
16563                                )));
16564                            }
16565                            // Act as if the alias was specified normally next
16566                            // to the table name: `(mytable) AS alias` ->
16567                            // `(mytable AS alias)`
16568                            alias.replace(outer_alias);
16569                        }
16570                    };
16571                }
16572                // Do not store the extra set of parens in the AST
16573                Ok(table_and_joins.relation)
16574            } else {
16575                // The SQL spec prohibits derived tables and bare tables from
16576                // appearing alone in parentheses (e.g. `FROM (mytable)`)
16577                self.expected_ref("joined table", self.peek_token_ref())
16578            }
16579        } else if self.dialect.supports_values_as_table_factor()
16580            && matches!(
16581                self.peek_tokens(),
16582                [
16583                    Token::Word(Word {
16584                        keyword: Keyword::VALUES,
16585                        ..
16586                    }),
16587                    Token::LParen
16588                ]
16589            )
16590        {
16591            self.expect_keyword_is(Keyword::VALUES)?;
16592
16593            // Snowflake and Databricks allow syntax like below:
16594            // SELECT * FROM VALUES (1, 'a'), (2, 'b') AS t (col1, col2)
16595            // where there are no parentheses around the VALUES clause.
16596            let values = SetExpr::Values(self.parse_values(false, false)?);
16597            let alias = self.maybe_parse_table_alias()?;
16598            Ok(TableFactor::Derived {
16599                lateral: false,
16600                subquery: Box::new(Query {
16601                    with: None,
16602                    body: Box::new(values),
16603                    order_by: None,
16604                    limit_clause: None,
16605                    fetch: None,
16606                    locks: vec![],
16607                    for_clause: None,
16608                    settings: None,
16609                    format_clause: None,
16610                    pipe_operators: vec![],
16611                }),
16612                alias,
16613                sample: None,
16614            })
16615        } else if dialect_of!(self is BigQueryDialect | PostgreSqlDialect | GenericDialect)
16616            && self.parse_keyword(Keyword::UNNEST)
16617        {
16618            self.expect_token(&Token::LParen)?;
16619            let array_exprs = self.parse_comma_separated(Parser::parse_expr)?;
16620            self.expect_token(&Token::RParen)?;
16621
16622            let with_ordinality = self.parse_keywords(&[Keyword::WITH, Keyword::ORDINALITY]);
16623            let alias = match self.maybe_parse_table_alias() {
16624                Ok(Some(alias)) => Some(alias),
16625                Ok(None) => None,
16626                Err(e) => return Err(e),
16627            };
16628
16629            let with_offset = match self.expect_keywords(&[Keyword::WITH, Keyword::OFFSET]) {
16630                Ok(()) => true,
16631                Err(_) => false,
16632            };
16633
16634            let with_offset_alias = if with_offset {
16635                match self.parse_optional_alias(keywords::RESERVED_FOR_COLUMN_ALIAS) {
16636                    Ok(Some(alias)) => Some(alias),
16637                    Ok(None) => None,
16638                    Err(e) => return Err(e),
16639                }
16640            } else {
16641                None
16642            };
16643
16644            Ok(TableFactor::UNNEST {
16645                alias,
16646                array_exprs,
16647                with_offset,
16648                with_offset_alias,
16649                with_ordinality,
16650            })
16651        } else if self.parse_keyword_with_tokens(Keyword::JSON_TABLE, &[Token::LParen]) {
16652            let json_expr = self.parse_expr()?;
16653            self.expect_token(&Token::Comma)?;
16654            let json_path = self.parse_value()?;
16655            self.expect_keyword_is(Keyword::COLUMNS)?;
16656            self.expect_token(&Token::LParen)?;
16657            let columns = self.parse_comma_separated(Parser::parse_json_table_column_def)?;
16658            self.expect_token(&Token::RParen)?;
16659            self.expect_token(&Token::RParen)?;
16660            let alias = self.maybe_parse_table_alias()?;
16661            Ok(TableFactor::JsonTable {
16662                json_expr,
16663                json_path,
16664                columns,
16665                alias,
16666            })
16667        } else if self.parse_keyword_with_tokens(Keyword::OPENJSON, &[Token::LParen]) {
16668            self.prev_token();
16669            self.parse_open_json_table_factor()
16670        } else if self.parse_keyword_with_tokens(Keyword::XMLTABLE, &[Token::LParen]) {
16671            self.prev_token();
16672            self.parse_xml_table_factor()
16673        } else if self.dialect.supports_semantic_view_table_factor()
16674            && self.peek_keyword_with_tokens(Keyword::SEMANTIC_VIEW, &[Token::LParen])
16675        {
16676            self.parse_semantic_view_table_factor()
16677        } else if self.peek_token_ref().token == Token::AtSign {
16678            // Stage reference: @mystage or @namespace.stage (e.g. Snowflake)
16679            self.parse_snowflake_stage_table_factor()
16680        } else {
16681            let name = self.parse_object_name(true)?;
16682
16683            let json_path = match &self.peek_token_ref().token {
16684                Token::LBracket if self.dialect.supports_partiql() => Some(self.parse_json_path()?),
16685                _ => None,
16686            };
16687
16688            let partitions: Vec<Ident> = if dialect_of!(self is MySqlDialect | GenericDialect)
16689                && self.parse_keyword(Keyword::PARTITION)
16690            {
16691                self.parse_parenthesized_identifiers()?
16692            } else {
16693                vec![]
16694            };
16695
16696            // Parse potential version qualifier
16697            let version = self.maybe_parse_table_version()?;
16698
16699            // Postgres, MSSQL, ClickHouse: table-valued functions:
16700            let args = if self.consume_token(&Token::LParen) {
16701                Some(self.parse_table_function_args()?)
16702            } else {
16703                None
16704            };
16705
16706            let with_ordinality = self.parse_keywords(&[Keyword::WITH, Keyword::ORDINALITY]);
16707
16708            let mut sample = None;
16709            if self.dialect.supports_table_sample_before_alias() {
16710                if let Some(parsed_sample) = self.maybe_parse_table_sample()? {
16711                    sample = Some(TableSampleKind::BeforeTableAlias(parsed_sample));
16712                }
16713            }
16714
16715            let alias = self.maybe_parse_table_alias()?;
16716
16717            // MYSQL-specific table hints:
16718            let index_hints = if self.dialect.supports_table_hints() {
16719                self.maybe_parse(|p| p.parse_table_index_hints())?
16720                    .unwrap_or(vec![])
16721            } else {
16722                vec![]
16723            };
16724
16725            // MSSQL-specific table hints:
16726            let mut with_hints = vec![];
16727            if self.parse_keyword(Keyword::WITH) {
16728                if self.consume_token(&Token::LParen) {
16729                    with_hints = self.parse_comma_separated(Parser::parse_expr)?;
16730                    self.expect_token(&Token::RParen)?;
16731                } else {
16732                    // rewind, as WITH may belong to the next statement's CTE
16733                    self.prev_token();
16734                }
16735            };
16736
16737            if !self.dialect.supports_table_sample_before_alias() {
16738                if let Some(parsed_sample) = self.maybe_parse_table_sample()? {
16739                    sample = Some(TableSampleKind::AfterTableAlias(parsed_sample));
16740                }
16741            }
16742
16743            let mut table = TableFactor::Table {
16744                name,
16745                alias,
16746                args,
16747                with_hints,
16748                version,
16749                partitions,
16750                with_ordinality,
16751                json_path,
16752                sample,
16753                index_hints,
16754            };
16755
16756            while let Some(kw) = self.parse_one_of_keywords(&[Keyword::PIVOT, Keyword::UNPIVOT]) {
16757                table = match kw {
16758                    Keyword::PIVOT => self.parse_pivot_table_factor(table)?,
16759                    Keyword::UNPIVOT => self.parse_unpivot_table_factor(table)?,
16760                    unexpected_keyword => return Err(ParserError::ParserError(
16761                        format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in pivot/unpivot"),
16762                    )),
16763                }
16764            }
16765
16766            if self.dialect.supports_match_recognize()
16767                && self.parse_keyword(Keyword::MATCH_RECOGNIZE)
16768            {
16769                table = self.parse_match_recognize(table)?;
16770            }
16771
16772            Ok(table)
16773        }
16774    }
16775
16776    /// Parse a Snowflake stage reference as a table factor.
16777    /// Handles syntax like: `@mystage1 (file_format => 'myformat', pattern => '...')`
16778    ///
16779    /// See: <https://docs.snowflake.com/en/user-guide/querying-stage>
16780    fn parse_snowflake_stage_table_factor(&mut self) -> Result<TableFactor, ParserError> {
16781        // Parse the stage name starting with @
16782        let name = crate::dialect::parse_snowflake_stage_name(self)?;
16783
16784        // Parse optional stage options like (file_format => 'myformat', pattern => '...')
16785        let args = if self.consume_token(&Token::LParen) {
16786            Some(self.parse_table_function_args()?)
16787        } else {
16788            None
16789        };
16790
16791        let alias = self.maybe_parse_table_alias()?;
16792
16793        Ok(TableFactor::Table {
16794            name,
16795            alias,
16796            args,
16797            with_hints: vec![],
16798            version: None,
16799            partitions: vec![],
16800            with_ordinality: false,
16801            json_path: None,
16802            sample: None,
16803            index_hints: vec![],
16804        })
16805    }
16806
16807    fn maybe_parse_table_sample(&mut self) -> Result<Option<Box<TableSample>>, ParserError> {
16808        let modifier = if self.parse_keyword(Keyword::TABLESAMPLE) {
16809            TableSampleModifier::TableSample
16810        } else if self.parse_keyword(Keyword::SAMPLE) {
16811            TableSampleModifier::Sample
16812        } else {
16813            return Ok(None);
16814        };
16815        self.parse_table_sample(modifier).map(Some)
16816    }
16817
16818    fn parse_table_sample(
16819        &mut self,
16820        modifier: TableSampleModifier,
16821    ) -> Result<Box<TableSample>, ParserError> {
16822        let name = match self.parse_one_of_keywords(&[
16823            Keyword::BERNOULLI,
16824            Keyword::ROW,
16825            Keyword::SYSTEM,
16826            Keyword::BLOCK,
16827        ]) {
16828            Some(Keyword::BERNOULLI) => Some(TableSampleMethod::Bernoulli),
16829            Some(Keyword::ROW) => Some(TableSampleMethod::Row),
16830            Some(Keyword::SYSTEM) => Some(TableSampleMethod::System),
16831            Some(Keyword::BLOCK) => Some(TableSampleMethod::Block),
16832            _ => None,
16833        };
16834
16835        let parenthesized = self.consume_token(&Token::LParen);
16836
16837        let (quantity, bucket) = if parenthesized && self.parse_keyword(Keyword::BUCKET) {
16838            let selected_bucket = self.parse_number_value()?;
16839            self.expect_keywords(&[Keyword::OUT, Keyword::OF])?;
16840            let total = self.parse_number_value()?;
16841            let on = if self.parse_keyword(Keyword::ON) {
16842                Some(self.parse_expr()?)
16843            } else {
16844                None
16845            };
16846            (
16847                None,
16848                Some(TableSampleBucket {
16849                    bucket: selected_bucket,
16850                    total,
16851                    on,
16852                }),
16853            )
16854        } else {
16855            let value = match self.maybe_parse(|p| p.parse_expr())? {
16856                Some(num) => num,
16857                None => {
16858                    let next_token = self.next_token();
16859                    if let Token::Word(w) = next_token.token {
16860                        Expr::Value(Value::Placeholder(w.value).with_span(next_token.span))
16861                    } else {
16862                        return parser_err!(
16863                            "Expecting number or byte length e.g. 100M",
16864                            self.peek_token_ref().span.start
16865                        );
16866                    }
16867                }
16868            };
16869            let unit = if self.parse_keyword(Keyword::ROWS) {
16870                Some(TableSampleUnit::Rows)
16871            } else if self.parse_keyword(Keyword::PERCENT) {
16872                Some(TableSampleUnit::Percent)
16873            } else {
16874                None
16875            };
16876            (
16877                Some(TableSampleQuantity {
16878                    parenthesized,
16879                    value,
16880                    unit,
16881                }),
16882                None,
16883            )
16884        };
16885        if parenthesized {
16886            self.expect_token(&Token::RParen)?;
16887        }
16888
16889        let seed = if self.parse_keyword(Keyword::REPEATABLE) {
16890            Some(self.parse_table_sample_seed(TableSampleSeedModifier::Repeatable)?)
16891        } else if self.parse_keyword(Keyword::SEED) {
16892            Some(self.parse_table_sample_seed(TableSampleSeedModifier::Seed)?)
16893        } else {
16894            None
16895        };
16896
16897        let offset = if self.parse_keyword(Keyword::OFFSET) {
16898            Some(self.parse_expr()?)
16899        } else {
16900            None
16901        };
16902
16903        Ok(Box::new(TableSample {
16904            modifier,
16905            name,
16906            quantity,
16907            seed,
16908            bucket,
16909            offset,
16910        }))
16911    }
16912
16913    fn parse_table_sample_seed(
16914        &mut self,
16915        modifier: TableSampleSeedModifier,
16916    ) -> Result<TableSampleSeed, ParserError> {
16917        self.expect_token(&Token::LParen)?;
16918        let value = self.parse_number_value()?;
16919        self.expect_token(&Token::RParen)?;
16920        Ok(TableSampleSeed { modifier, value })
16921    }
16922
16923    /// Parses `OPENJSON( jsonExpression [ , path ] )  [ <with_clause> ]` clause,
16924    /// assuming the `OPENJSON` keyword was already consumed.
16925    fn parse_open_json_table_factor(&mut self) -> Result<TableFactor, ParserError> {
16926        self.expect_token(&Token::LParen)?;
16927        let json_expr = self.parse_expr()?;
16928        let json_path = if self.consume_token(&Token::Comma) {
16929            Some(self.parse_value()?)
16930        } else {
16931            None
16932        };
16933        self.expect_token(&Token::RParen)?;
16934        let columns = if self.parse_keyword(Keyword::WITH) {
16935            self.expect_token(&Token::LParen)?;
16936            let columns = self.parse_comma_separated(Parser::parse_openjson_table_column_def)?;
16937            self.expect_token(&Token::RParen)?;
16938            columns
16939        } else {
16940            Vec::new()
16941        };
16942        let alias = self.maybe_parse_table_alias()?;
16943        Ok(TableFactor::OpenJsonTable {
16944            json_expr,
16945            json_path,
16946            columns,
16947            alias,
16948        })
16949    }
16950
16951    fn parse_xml_table_factor(&mut self) -> Result<TableFactor, ParserError> {
16952        self.expect_token(&Token::LParen)?;
16953        let namespaces = if self.parse_keyword(Keyword::XMLNAMESPACES) {
16954            self.expect_token(&Token::LParen)?;
16955            let namespaces = self.parse_comma_separated(Parser::parse_xml_namespace_definition)?;
16956            self.expect_token(&Token::RParen)?;
16957            self.expect_token(&Token::Comma)?;
16958            namespaces
16959        } else {
16960            vec![]
16961        };
16962        let row_expression = self.parse_expr()?;
16963        let passing = self.parse_xml_passing_clause()?;
16964        self.expect_keyword_is(Keyword::COLUMNS)?;
16965        let columns = self.parse_comma_separated(Parser::parse_xml_table_column)?;
16966        self.expect_token(&Token::RParen)?;
16967        let alias = self.maybe_parse_table_alias()?;
16968        Ok(TableFactor::XmlTable {
16969            namespaces,
16970            row_expression,
16971            passing,
16972            columns,
16973            alias,
16974        })
16975    }
16976
16977    fn parse_xml_namespace_definition(&mut self) -> Result<XmlNamespaceDefinition, ParserError> {
16978        let uri = self.parse_expr()?;
16979        self.expect_keyword_is(Keyword::AS)?;
16980        let name = self.parse_identifier()?;
16981        Ok(XmlNamespaceDefinition { uri, name })
16982    }
16983
16984    fn parse_xml_table_column(&mut self) -> Result<XmlTableColumn, ParserError> {
16985        let name = self.parse_identifier()?;
16986
16987        let option = if self.parse_keyword(Keyword::FOR) {
16988            self.expect_keyword(Keyword::ORDINALITY)?;
16989            XmlTableColumnOption::ForOrdinality
16990        } else {
16991            let r#type = self.parse_data_type()?;
16992            let mut path = None;
16993            let mut default = None;
16994
16995            if self.parse_keyword(Keyword::PATH) {
16996                path = Some(self.parse_expr()?);
16997            }
16998
16999            if self.parse_keyword(Keyword::DEFAULT) {
17000                default = Some(self.parse_expr()?);
17001            }
17002
17003            let not_null = self.parse_keywords(&[Keyword::NOT, Keyword::NULL]);
17004            if !not_null {
17005                // NULL is the default but can be specified explicitly
17006                let _ = self.parse_keyword(Keyword::NULL);
17007            }
17008
17009            XmlTableColumnOption::NamedInfo {
17010                r#type,
17011                path,
17012                default,
17013                nullable: !not_null,
17014            }
17015        };
17016        Ok(XmlTableColumn { name, option })
17017    }
17018
17019    fn parse_xml_passing_clause(&mut self) -> Result<XmlPassingClause, ParserError> {
17020        let mut arguments = vec![];
17021        if self.parse_keyword(Keyword::PASSING) {
17022            loop {
17023                let by_value =
17024                    self.parse_keyword(Keyword::BY) && self.expect_keyword(Keyword::VALUE).is_ok();
17025                let expr = self.parse_expr()?;
17026                let alias = if self.parse_keyword(Keyword::AS) {
17027                    Some(self.parse_identifier()?)
17028                } else {
17029                    None
17030                };
17031                arguments.push(XmlPassingArgument {
17032                    expr,
17033                    alias,
17034                    by_value,
17035                });
17036                if !self.consume_token(&Token::Comma) {
17037                    break;
17038                }
17039            }
17040        }
17041        Ok(XmlPassingClause { arguments })
17042    }
17043
17044    /// Parse a [TableFactor::SemanticView]
17045    fn parse_semantic_view_table_factor(&mut self) -> Result<TableFactor, ParserError> {
17046        self.expect_keyword(Keyword::SEMANTIC_VIEW)?;
17047        self.expect_token(&Token::LParen)?;
17048
17049        let name = self.parse_object_name(true)?;
17050
17051        // Parse DIMENSIONS, METRICS, FACTS and WHERE clauses in flexible order
17052        let mut dimensions = Vec::new();
17053        let mut metrics = Vec::new();
17054        let mut facts = Vec::new();
17055        let mut where_clause = None;
17056
17057        while self.peek_token_ref().token != Token::RParen {
17058            if self.parse_keyword(Keyword::DIMENSIONS) {
17059                if !dimensions.is_empty() {
17060                    return Err(ParserError::ParserError(
17061                        "DIMENSIONS clause can only be specified once".to_string(),
17062                    ));
17063                }
17064                dimensions = self.parse_comma_separated(Parser::parse_wildcard_expr)?;
17065            } else if self.parse_keyword(Keyword::METRICS) {
17066                if !metrics.is_empty() {
17067                    return Err(ParserError::ParserError(
17068                        "METRICS clause can only be specified once".to_string(),
17069                    ));
17070                }
17071                metrics = self.parse_comma_separated(Parser::parse_wildcard_expr)?;
17072            } else if self.parse_keyword(Keyword::FACTS) {
17073                if !facts.is_empty() {
17074                    return Err(ParserError::ParserError(
17075                        "FACTS clause can only be specified once".to_string(),
17076                    ));
17077                }
17078                facts = self.parse_comma_separated(Parser::parse_wildcard_expr)?;
17079            } else if self.parse_keyword(Keyword::WHERE) {
17080                if where_clause.is_some() {
17081                    return Err(ParserError::ParserError(
17082                        "WHERE clause can only be specified once".to_string(),
17083                    ));
17084                }
17085                where_clause = Some(self.parse_expr()?);
17086            } else {
17087                let tok = self.peek_token_ref();
17088                return parser_err!(
17089                    format!(
17090                        "Expected one of DIMENSIONS, METRICS, FACTS or WHERE, got {}",
17091                        tok.token
17092                    ),
17093                    tok.span.start
17094                )?;
17095            }
17096        }
17097
17098        self.expect_token(&Token::RParen)?;
17099
17100        let alias = self.maybe_parse_table_alias()?;
17101
17102        Ok(TableFactor::SemanticView {
17103            name,
17104            dimensions,
17105            metrics,
17106            facts,
17107            where_clause,
17108            alias,
17109        })
17110    }
17111
17112    fn parse_match_recognize(&mut self, table: TableFactor) -> Result<TableFactor, ParserError> {
17113        self.expect_token(&Token::LParen)?;
17114
17115        let partition_by = if self.parse_keywords(&[Keyword::PARTITION, Keyword::BY]) {
17116            self.parse_comma_separated(Parser::parse_expr)?
17117        } else {
17118            vec![]
17119        };
17120
17121        let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
17122            self.parse_comma_separated(Parser::parse_order_by_expr)?
17123        } else {
17124            vec![]
17125        };
17126
17127        let measures = if self.parse_keyword(Keyword::MEASURES) {
17128            self.parse_comma_separated(|p| {
17129                let expr = p.parse_expr()?;
17130                let _ = p.parse_keyword(Keyword::AS);
17131                let alias = p.parse_identifier()?;
17132                Ok(Measure { expr, alias })
17133            })?
17134        } else {
17135            vec![]
17136        };
17137
17138        let rows_per_match =
17139            if self.parse_keywords(&[Keyword::ONE, Keyword::ROW, Keyword::PER, Keyword::MATCH]) {
17140                Some(RowsPerMatch::OneRow)
17141            } else if self.parse_keywords(&[
17142                Keyword::ALL,
17143                Keyword::ROWS,
17144                Keyword::PER,
17145                Keyword::MATCH,
17146            ]) {
17147                Some(RowsPerMatch::AllRows(
17148                    if self.parse_keywords(&[Keyword::SHOW, Keyword::EMPTY, Keyword::MATCHES]) {
17149                        Some(EmptyMatchesMode::Show)
17150                    } else if self.parse_keywords(&[
17151                        Keyword::OMIT,
17152                        Keyword::EMPTY,
17153                        Keyword::MATCHES,
17154                    ]) {
17155                        Some(EmptyMatchesMode::Omit)
17156                    } else if self.parse_keywords(&[
17157                        Keyword::WITH,
17158                        Keyword::UNMATCHED,
17159                        Keyword::ROWS,
17160                    ]) {
17161                        Some(EmptyMatchesMode::WithUnmatched)
17162                    } else {
17163                        None
17164                    },
17165                ))
17166            } else {
17167                None
17168            };
17169
17170        let after_match_skip =
17171            if self.parse_keywords(&[Keyword::AFTER, Keyword::MATCH, Keyword::SKIP]) {
17172                if self.parse_keywords(&[Keyword::PAST, Keyword::LAST, Keyword::ROW]) {
17173                    Some(AfterMatchSkip::PastLastRow)
17174                } else if self.parse_keywords(&[Keyword::TO, Keyword::NEXT, Keyword::ROW]) {
17175                    Some(AfterMatchSkip::ToNextRow)
17176                } else if self.parse_keywords(&[Keyword::TO, Keyword::FIRST]) {
17177                    Some(AfterMatchSkip::ToFirst(self.parse_identifier()?))
17178                } else if self.parse_keywords(&[Keyword::TO, Keyword::LAST]) {
17179                    Some(AfterMatchSkip::ToLast(self.parse_identifier()?))
17180                } else {
17181                    let found = self.next_token();
17182                    return self.expected("after match skip option", found);
17183                }
17184            } else {
17185                None
17186            };
17187
17188        self.expect_keyword_is(Keyword::PATTERN)?;
17189        let pattern = self.parse_parenthesized(Self::parse_pattern)?;
17190
17191        self.expect_keyword_is(Keyword::DEFINE)?;
17192
17193        let symbols = self.parse_comma_separated(|p| {
17194            let symbol = p.parse_identifier()?;
17195            p.expect_keyword_is(Keyword::AS)?;
17196            let definition = p.parse_expr()?;
17197            Ok(SymbolDefinition { symbol, definition })
17198        })?;
17199
17200        self.expect_token(&Token::RParen)?;
17201
17202        let alias = self.maybe_parse_table_alias()?;
17203
17204        Ok(TableFactor::MatchRecognize {
17205            table: Box::new(table),
17206            partition_by,
17207            order_by,
17208            measures,
17209            rows_per_match,
17210            after_match_skip,
17211            pattern,
17212            symbols,
17213            alias,
17214        })
17215    }
17216
17217    fn parse_base_pattern(&mut self) -> Result<MatchRecognizePattern, ParserError> {
17218        match self.next_token().token {
17219            Token::Caret => Ok(MatchRecognizePattern::Symbol(MatchRecognizeSymbol::Start)),
17220            Token::Placeholder(s) if s == "$" => {
17221                Ok(MatchRecognizePattern::Symbol(MatchRecognizeSymbol::End))
17222            }
17223            Token::LBrace => {
17224                self.expect_token(&Token::Minus)?;
17225                let symbol = self.parse_identifier().map(MatchRecognizeSymbol::Named)?;
17226                self.expect_token(&Token::Minus)?;
17227                self.expect_token(&Token::RBrace)?;
17228                Ok(MatchRecognizePattern::Exclude(symbol))
17229            }
17230            Token::Word(Word {
17231                value,
17232                quote_style: None,
17233                ..
17234            }) if value == "PERMUTE" => {
17235                self.expect_token(&Token::LParen)?;
17236                let symbols = self.parse_comma_separated(|p| {
17237                    p.parse_identifier().map(MatchRecognizeSymbol::Named)
17238                })?;
17239                self.expect_token(&Token::RParen)?;
17240                Ok(MatchRecognizePattern::Permute(symbols))
17241            }
17242            Token::LParen => {
17243                let pattern = self.parse_pattern()?;
17244                self.expect_token(&Token::RParen)?;
17245                Ok(MatchRecognizePattern::Group(Box::new(pattern)))
17246            }
17247            _ => {
17248                self.prev_token();
17249                self.parse_identifier()
17250                    .map(MatchRecognizeSymbol::Named)
17251                    .map(MatchRecognizePattern::Symbol)
17252            }
17253        }
17254    }
17255
17256    fn parse_repetition_pattern(&mut self) -> Result<MatchRecognizePattern, ParserError> {
17257        let mut pattern = self.parse_base_pattern()?;
17258        loop {
17259            let token = self.next_token();
17260            let quantifier = match token.token {
17261                Token::Mul => RepetitionQuantifier::ZeroOrMore,
17262                Token::Plus => RepetitionQuantifier::OneOrMore,
17263                Token::Placeholder(s) if s == "?" => RepetitionQuantifier::AtMostOne,
17264                Token::LBrace => {
17265                    // quantifier is a range like {n} or {n,} or {,m} or {n,m}
17266                    let token = self.next_token();
17267                    match token.token {
17268                        Token::Comma => {
17269                            let next_token = self.next_token();
17270                            let Token::Number(n, _) = next_token.token else {
17271                                return self.expected("literal number", next_token);
17272                            };
17273                            self.expect_token(&Token::RBrace)?;
17274                            RepetitionQuantifier::AtMost(Self::parse(n, token.span.start)?)
17275                        }
17276                        Token::Number(n, _) if self.consume_token(&Token::Comma) => {
17277                            let next_token = self.next_token();
17278                            match next_token.token {
17279                                Token::Number(m, _) => {
17280                                    self.expect_token(&Token::RBrace)?;
17281                                    RepetitionQuantifier::Range(
17282                                        Self::parse(n, token.span.start)?,
17283                                        Self::parse(m, token.span.start)?,
17284                                    )
17285                                }
17286                                Token::RBrace => {
17287                                    RepetitionQuantifier::AtLeast(Self::parse(n, token.span.start)?)
17288                                }
17289                                _ => {
17290                                    return self.expected("} or upper bound", next_token);
17291                                }
17292                            }
17293                        }
17294                        Token::Number(n, _) => {
17295                            self.expect_token(&Token::RBrace)?;
17296                            RepetitionQuantifier::Exactly(Self::parse(n, token.span.start)?)
17297                        }
17298                        _ => return self.expected("quantifier range", token),
17299                    }
17300                }
17301                _ => {
17302                    self.prev_token();
17303                    break;
17304                }
17305            };
17306            pattern = MatchRecognizePattern::Repetition(Box::new(pattern), quantifier);
17307        }
17308        Ok(pattern)
17309    }
17310
17311    fn parse_concat_pattern(&mut self) -> Result<MatchRecognizePattern, ParserError> {
17312        let mut patterns = vec![self.parse_repetition_pattern()?];
17313        while !matches!(self.peek_token_ref().token, Token::RParen | Token::Pipe) {
17314            patterns.push(self.parse_repetition_pattern()?);
17315        }
17316        match <[MatchRecognizePattern; 1]>::try_from(patterns) {
17317            Ok([pattern]) => Ok(pattern),
17318            Err(patterns) => Ok(MatchRecognizePattern::Concat(patterns)),
17319        }
17320    }
17321
17322    fn parse_pattern(&mut self) -> Result<MatchRecognizePattern, ParserError> {
17323        let pattern = self.parse_concat_pattern()?;
17324        if self.consume_token(&Token::Pipe) {
17325            match self.parse_pattern()? {
17326                // flatten nested alternations
17327                MatchRecognizePattern::Alternation(mut patterns) => {
17328                    patterns.insert(0, pattern);
17329                    Ok(MatchRecognizePattern::Alternation(patterns))
17330                }
17331                next => Ok(MatchRecognizePattern::Alternation(vec![pattern, next])),
17332            }
17333        } else {
17334            Ok(pattern)
17335        }
17336    }
17337
17338    /// Parses a the timestamp version specifier (i.e. query historical data)
17339    pub fn maybe_parse_table_version(&mut self) -> Result<Option<TableVersion>, ParserError> {
17340        if self.dialect.supports_table_versioning() {
17341            if self.parse_keywords(&[Keyword::FOR, Keyword::SYSTEM_TIME, Keyword::AS, Keyword::OF])
17342            {
17343                let expr = self.parse_expr()?;
17344                return Ok(Some(TableVersion::ForSystemTimeAsOf(expr)));
17345            } else if self.peek_keyword(Keyword::CHANGES) {
17346                return self.parse_table_version_changes().map(Some);
17347            } else if self.peek_keyword(Keyword::AT) || self.peek_keyword(Keyword::BEFORE) {
17348                let func_name = self.parse_object_name(true)?;
17349                let func = self.parse_function(func_name)?;
17350                return Ok(Some(TableVersion::Function(func)));
17351            } else if self.parse_keywords(&[Keyword::TIMESTAMP, Keyword::AS, Keyword::OF]) {
17352                let expr = self.parse_expr()?;
17353                return Ok(Some(TableVersion::TimestampAsOf(expr)));
17354            } else if self.parse_keywords(&[Keyword::VERSION, Keyword::AS, Keyword::OF]) {
17355                let expr = Expr::Value(self.parse_number_value()?);
17356                return Ok(Some(TableVersion::VersionAsOf(expr)));
17357            }
17358        }
17359        Ok(None)
17360    }
17361
17362    /// Parses the Snowflake `CHANGES` clause for change tracking queries.
17363    ///
17364    /// Syntax:
17365    /// ```sql
17366    /// CHANGES (INFORMATION => DEFAULT)
17367    ///   AT (TIMESTAMP => <expr>)
17368    ///   [END (TIMESTAMP => <expr>)]
17369    /// ```
17370    ///
17371    /// <https://docs.snowflake.com/en/sql-reference/constructs/changes>
17372    fn parse_table_version_changes(&mut self) -> Result<TableVersion, ParserError> {
17373        let changes_name = self.parse_object_name(true)?;
17374        let changes = self.parse_function(changes_name)?;
17375        let at_name = self.parse_object_name(true)?;
17376        let at = self.parse_function(at_name)?;
17377        let end = if self.peek_keyword(Keyword::END) {
17378            let end_name = self.parse_object_name(true)?;
17379            Some(self.parse_function(end_name)?)
17380        } else {
17381            None
17382        };
17383        Ok(TableVersion::Changes { changes, at, end })
17384    }
17385
17386    /// Parses MySQL's JSON_TABLE column definition.
17387    /// For example: `id INT EXISTS PATH '$' DEFAULT '0' ON EMPTY ERROR ON ERROR`
17388    pub fn parse_json_table_column_def(&mut self) -> Result<JsonTableColumn, ParserError> {
17389        if self.parse_keyword(Keyword::NESTED) {
17390            let _has_path_keyword = self.parse_keyword(Keyword::PATH);
17391            let path = self.parse_value()?;
17392            self.expect_keyword_is(Keyword::COLUMNS)?;
17393            let columns = self.parse_parenthesized(|p| {
17394                p.parse_comma_separated(Self::parse_json_table_column_def)
17395            })?;
17396            return Ok(JsonTableColumn::Nested(JsonTableNestedColumn {
17397                path,
17398                columns,
17399            }));
17400        }
17401        let name = self.parse_identifier()?;
17402        if self.parse_keyword(Keyword::FOR) {
17403            self.expect_keyword_is(Keyword::ORDINALITY)?;
17404            return Ok(JsonTableColumn::ForOrdinality(name));
17405        }
17406        let r#type = self.parse_data_type()?;
17407        let exists = self.parse_keyword(Keyword::EXISTS);
17408        self.expect_keyword_is(Keyword::PATH)?;
17409        let path = self.parse_value()?;
17410        let mut on_empty = None;
17411        let mut on_error = None;
17412        while let Some(error_handling) = self.parse_json_table_column_error_handling()? {
17413            if self.parse_keyword(Keyword::EMPTY) {
17414                on_empty = Some(error_handling);
17415            } else {
17416                self.expect_keyword_is(Keyword::ERROR)?;
17417                on_error = Some(error_handling);
17418            }
17419        }
17420        Ok(JsonTableColumn::Named(JsonTableNamedColumn {
17421            name,
17422            r#type,
17423            path,
17424            exists,
17425            on_empty,
17426            on_error,
17427        }))
17428    }
17429
17430    /// Parses MSSQL's `OPENJSON WITH` column definition.
17431    ///
17432    /// ```sql
17433    /// colName type [ column_path ] [ AS JSON ]
17434    /// ```
17435    ///
17436    /// Reference: <https://learn.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver16#syntax>
17437    pub fn parse_openjson_table_column_def(&mut self) -> Result<OpenJsonTableColumn, ParserError> {
17438        let name = self.parse_identifier()?;
17439        let r#type = self.parse_data_type()?;
17440        let path = if let Token::SingleQuotedString(path) = self.peek_token().token {
17441            self.next_token();
17442            Some(path)
17443        } else {
17444            None
17445        };
17446        let as_json = self.parse_keyword(Keyword::AS);
17447        if as_json {
17448            self.expect_keyword_is(Keyword::JSON)?;
17449        }
17450        Ok(OpenJsonTableColumn {
17451            name,
17452            r#type,
17453            path,
17454            as_json,
17455        })
17456    }
17457
17458    fn parse_json_table_column_error_handling(
17459        &mut self,
17460    ) -> Result<Option<JsonTableColumnErrorHandling>, ParserError> {
17461        let res = if self.parse_keyword(Keyword::NULL) {
17462            JsonTableColumnErrorHandling::Null
17463        } else if self.parse_keyword(Keyword::ERROR) {
17464            JsonTableColumnErrorHandling::Error
17465        } else if self.parse_keyword(Keyword::DEFAULT) {
17466            JsonTableColumnErrorHandling::Default(self.parse_value()?)
17467        } else {
17468            return Ok(None);
17469        };
17470        self.expect_keyword_is(Keyword::ON)?;
17471        Ok(Some(res))
17472    }
17473
17474    /// Parse a derived table factor (a parenthesized subquery), handling optional LATERAL.
17475    pub fn parse_derived_table_factor(
17476        &mut self,
17477        lateral: IsLateral,
17478    ) -> Result<TableFactor, ParserError> {
17479        let subquery = self.parse_query()?;
17480        self.expect_token(&Token::RParen)?;
17481        let alias = self.maybe_parse_table_alias()?;
17482
17483        // Parse optional SAMPLE clause after alias
17484        let sample = self
17485            .maybe_parse_table_sample()?
17486            .map(TableSampleKind::AfterTableAlias);
17487
17488        Ok(TableFactor::Derived {
17489            lateral: match lateral {
17490                Lateral => true,
17491                NotLateral => false,
17492            },
17493            subquery,
17494            alias,
17495            sample,
17496        })
17497    }
17498
17499    /// Parses an expression with an optional alias
17500    ///
17501    /// Examples:
17502    ///
17503    /// ```sql
17504    /// SUM(price) AS total_price
17505    /// ```
17506    /// ```sql
17507    /// SUM(price)
17508    /// ```
17509    ///
17510    /// Example
17511    /// ```
17512    /// # use sqlparser::parser::{Parser, ParserError};
17513    /// # use sqlparser::dialect::GenericDialect;
17514    /// # fn main() ->Result<(), ParserError> {
17515    /// let sql = r#"SUM("a") as "b""#;
17516    /// let mut parser = Parser::new(&GenericDialect).try_with_sql(sql)?;
17517    /// let expr_with_alias = parser.parse_expr_with_alias()?;
17518    /// assert_eq!(Some("b".to_string()), expr_with_alias.alias.map(|x|x.value));
17519    /// # Ok(())
17520    /// # }
17521    pub fn parse_expr_with_alias(&mut self) -> Result<ExprWithAlias, ParserError> {
17522        let expr = self.parse_expr()?;
17523        let alias = if self.parse_keyword(Keyword::AS) {
17524            Some(self.parse_identifier()?)
17525        } else {
17526            None
17527        };
17528
17529        Ok(ExprWithAlias { expr, alias })
17530    }
17531
17532    /// Parse an expression followed by an optional alias; Unlike
17533    /// [Self::parse_expr_with_alias] the "AS" keyword between the expression
17534    /// and the alias is optional.
17535    fn parse_expr_with_alias_optional_as_keyword(&mut self) -> Result<ExprWithAlias, ParserError> {
17536        let expr = self.parse_expr()?;
17537        let alias = self.parse_identifier_optional_alias()?;
17538        Ok(ExprWithAlias { expr, alias })
17539    }
17540
17541    /// Parses a plain function call with an optional alias for the `PIVOT` clause
17542    fn parse_pivot_aggregate_function(&mut self) -> Result<ExprWithAlias, ParserError> {
17543        let function_name = match self.next_token().token {
17544            Token::Word(w) => Ok(w.value),
17545            _ => self.expected_ref("a function identifier", self.peek_token_ref()),
17546        }?;
17547        let expr = self.parse_function(ObjectName::from(vec![Ident::new(function_name)]))?;
17548        let alias = {
17549            fn validator(explicit: bool, kw: &Keyword, parser: &mut Parser) -> bool {
17550                // ~ for a PIVOT aggregate function the alias must not be a "FOR"; in any dialect
17551                kw != &Keyword::FOR && parser.dialect.is_select_item_alias(explicit, kw, parser)
17552            }
17553            self.parse_optional_alias_inner(None, validator)?
17554        };
17555        Ok(ExprWithAlias { expr, alias })
17556    }
17557
17558    /// Parse a PIVOT table factor (ClickHouse/Oracle style pivot), returning a TableFactor.
17559    pub fn parse_pivot_table_factor(
17560        &mut self,
17561        table: TableFactor,
17562    ) -> Result<TableFactor, ParserError> {
17563        self.expect_token(&Token::LParen)?;
17564        let aggregate_functions =
17565            self.parse_comma_separated(Self::parse_pivot_aggregate_function)?;
17566        self.expect_keyword_is(Keyword::FOR)?;
17567        let value_column = if self.peek_token_ref().token == Token::LParen {
17568            self.parse_parenthesized_column_list_inner(Mandatory, false, |p| {
17569                p.parse_subexpr(self.dialect.prec_value(Precedence::Between))
17570            })?
17571        } else {
17572            vec![self.parse_subexpr(self.dialect.prec_value(Precedence::Between))?]
17573        };
17574        self.expect_keyword_is(Keyword::IN)?;
17575
17576        self.expect_token(&Token::LParen)?;
17577        let value_source = if self.parse_keyword(Keyword::ANY) {
17578            let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
17579                self.parse_comma_separated(Parser::parse_order_by_expr)?
17580            } else {
17581                vec![]
17582            };
17583            PivotValueSource::Any(order_by)
17584        } else if self.peek_sub_query() {
17585            PivotValueSource::Subquery(self.parse_query()?)
17586        } else {
17587            PivotValueSource::List(
17588                self.parse_comma_separated(Self::parse_expr_with_alias_optional_as_keyword)?,
17589            )
17590        };
17591        self.expect_token(&Token::RParen)?;
17592
17593        let default_on_null =
17594            if self.parse_keywords(&[Keyword::DEFAULT, Keyword::ON, Keyword::NULL]) {
17595                self.expect_token(&Token::LParen)?;
17596                let expr = self.parse_expr()?;
17597                self.expect_token(&Token::RParen)?;
17598                Some(expr)
17599            } else {
17600                None
17601            };
17602
17603        self.expect_token(&Token::RParen)?;
17604        let alias = self.maybe_parse_table_alias()?;
17605        Ok(TableFactor::Pivot {
17606            table: Box::new(table),
17607            aggregate_functions,
17608            value_column,
17609            value_source,
17610            default_on_null,
17611            alias,
17612        })
17613    }
17614
17615    /// Parse an UNPIVOT table factor, returning a TableFactor.
17616    pub fn parse_unpivot_table_factor(
17617        &mut self,
17618        table: TableFactor,
17619    ) -> Result<TableFactor, ParserError> {
17620        let null_inclusion = if self.parse_keyword(Keyword::INCLUDE) {
17621            self.expect_keyword_is(Keyword::NULLS)?;
17622            Some(NullInclusion::IncludeNulls)
17623        } else if self.parse_keyword(Keyword::EXCLUDE) {
17624            self.expect_keyword_is(Keyword::NULLS)?;
17625            Some(NullInclusion::ExcludeNulls)
17626        } else {
17627            None
17628        };
17629        self.expect_token(&Token::LParen)?;
17630        let value = self.parse_expr()?;
17631        self.expect_keyword_is(Keyword::FOR)?;
17632        let name = self.parse_identifier()?;
17633        self.expect_keyword_is(Keyword::IN)?;
17634        let columns = self.parse_parenthesized_column_list_inner(Mandatory, false, |p| {
17635            p.parse_expr_with_alias()
17636        })?;
17637        self.expect_token(&Token::RParen)?;
17638        let alias = self.maybe_parse_table_alias()?;
17639        Ok(TableFactor::Unpivot {
17640            table: Box::new(table),
17641            value,
17642            null_inclusion,
17643            name,
17644            columns,
17645            alias,
17646        })
17647    }
17648
17649    /// Parse a JOIN constraint (`NATURAL`, `ON <expr>`, `USING (...)`, or no constraint).
17650    pub fn parse_join_constraint(&mut self, natural: bool) -> Result<JoinConstraint, ParserError> {
17651        if natural {
17652            Ok(JoinConstraint::Natural)
17653        } else if self.parse_keyword(Keyword::ON) {
17654            let constraint = self.parse_expr()?;
17655            Ok(JoinConstraint::On(constraint))
17656        } else if self.parse_keyword(Keyword::USING) {
17657            let columns = self.parse_parenthesized_qualified_column_list(Mandatory, false)?;
17658            Ok(JoinConstraint::Using(columns))
17659        } else {
17660            Ok(JoinConstraint::None)
17661            //self.expected_ref("ON, or USING after JOIN", self.peek_token_ref())
17662        }
17663    }
17664
17665    /// Parse a GRANT statement.
17666    pub fn parse_grant(&mut self) -> Result<Grant, ParserError> {
17667        let (privileges, objects) = self.parse_grant_deny_revoke_privileges_objects()?;
17668
17669        self.expect_keyword_is(Keyword::TO)?;
17670        let grantees = self.parse_grantees()?;
17671
17672        let with_grant_option =
17673            self.parse_keywords(&[Keyword::WITH, Keyword::GRANT, Keyword::OPTION]);
17674
17675        let current_grants =
17676            if self.parse_keywords(&[Keyword::COPY, Keyword::CURRENT, Keyword::GRANTS]) {
17677                Some(CurrentGrantsKind::CopyCurrentGrants)
17678            } else if self.parse_keywords(&[Keyword::REVOKE, Keyword::CURRENT, Keyword::GRANTS]) {
17679                Some(CurrentGrantsKind::RevokeCurrentGrants)
17680            } else {
17681                None
17682            };
17683
17684        let as_grantor = if self.parse_keywords(&[Keyword::AS]) {
17685            Some(self.parse_identifier()?)
17686        } else {
17687            None
17688        };
17689
17690        let granted_by = if self.parse_keywords(&[Keyword::GRANTED, Keyword::BY]) {
17691            Some(self.parse_identifier()?)
17692        } else {
17693            None
17694        };
17695
17696        Ok(Grant {
17697            privileges,
17698            objects,
17699            grantees,
17700            with_grant_option,
17701            as_grantor,
17702            granted_by,
17703            current_grants,
17704        })
17705    }
17706
17707    fn parse_grantees(&mut self) -> Result<Vec<Grantee>, ParserError> {
17708        let mut values = vec![];
17709        let mut grantee_type = GranteesType::None;
17710        loop {
17711            let new_grantee_type = if self.parse_keyword(Keyword::ROLE) {
17712                GranteesType::Role
17713            } else if self.parse_keyword(Keyword::USER) {
17714                GranteesType::User
17715            } else if self.parse_keyword(Keyword::SHARE) {
17716                GranteesType::Share
17717            } else if self.parse_keyword(Keyword::GROUP) {
17718                GranteesType::Group
17719            } else if self.parse_keyword(Keyword::PUBLIC) {
17720                GranteesType::Public
17721            } else if self.parse_keywords(&[Keyword::DATABASE, Keyword::ROLE]) {
17722                GranteesType::DatabaseRole
17723            } else if self.parse_keywords(&[Keyword::APPLICATION, Keyword::ROLE]) {
17724                GranteesType::ApplicationRole
17725            } else if self.parse_keyword(Keyword::APPLICATION) {
17726                GranteesType::Application
17727            } else {
17728                grantee_type.clone() // keep from previous iteraton, if not specified
17729            };
17730
17731            if self
17732                .dialect
17733                .get_reserved_grantees_types()
17734                .contains(&new_grantee_type)
17735            {
17736                self.prev_token();
17737            } else {
17738                grantee_type = new_grantee_type;
17739            }
17740
17741            let grantee = if grantee_type == GranteesType::Public {
17742                Grantee {
17743                    grantee_type: grantee_type.clone(),
17744                    name: None,
17745                }
17746            } else {
17747                let mut name = self.parse_grantee_name()?;
17748                if self.consume_token(&Token::Colon) {
17749                    // Redshift supports namespace prefix for external users and groups:
17750                    // <Namespace>:<GroupName> or <Namespace>:<UserName>
17751                    // https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-iam-access-control-native-idp.html
17752                    let ident = self.parse_identifier()?;
17753                    if let GranteeName::ObjectName(namespace) = name {
17754                        name = GranteeName::ObjectName(ObjectName::from(vec![Ident::new(
17755                            format!("{namespace}:{ident}"),
17756                        )]));
17757                    };
17758                }
17759                Grantee {
17760                    grantee_type: grantee_type.clone(),
17761                    name: Some(name),
17762                }
17763            };
17764
17765            values.push(grantee);
17766
17767            if !self.consume_token(&Token::Comma) {
17768                break;
17769            }
17770        }
17771
17772        Ok(values)
17773    }
17774
17775    /// Parse privileges and optional target objects for GRANT/DENY/REVOKE statements.
17776    pub fn parse_grant_deny_revoke_privileges_objects(
17777        &mut self,
17778    ) -> Result<(Privileges, Option<GrantObjects>), ParserError> {
17779        let privileges = if self.parse_keyword(Keyword::ALL) {
17780            Privileges::All {
17781                with_privileges_keyword: self.parse_keyword(Keyword::PRIVILEGES),
17782            }
17783        } else {
17784            let actions = self.parse_actions_list()?;
17785            Privileges::Actions(actions)
17786        };
17787
17788        let objects = if self.parse_keyword(Keyword::ON) {
17789            if self.parse_keywords(&[Keyword::ALL, Keyword::TABLES, Keyword::IN, Keyword::SCHEMA]) {
17790                Some(GrantObjects::AllTablesInSchema {
17791                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17792                })
17793            } else if self.parse_keywords(&[
17794                Keyword::ALL,
17795                Keyword::EXTERNAL,
17796                Keyword::TABLES,
17797                Keyword::IN,
17798                Keyword::SCHEMA,
17799            ]) {
17800                Some(GrantObjects::AllExternalTablesInSchema {
17801                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17802                })
17803            } else if self.parse_keywords(&[
17804                Keyword::ALL,
17805                Keyword::VIEWS,
17806                Keyword::IN,
17807                Keyword::SCHEMA,
17808            ]) {
17809                Some(GrantObjects::AllViewsInSchema {
17810                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17811                })
17812            } else if self.parse_keywords(&[
17813                Keyword::ALL,
17814                Keyword::MATERIALIZED,
17815                Keyword::VIEWS,
17816                Keyword::IN,
17817                Keyword::SCHEMA,
17818            ]) {
17819                Some(GrantObjects::AllMaterializedViewsInSchema {
17820                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17821                })
17822            } else if self.parse_keywords(&[
17823                Keyword::ALL,
17824                Keyword::FUNCTIONS,
17825                Keyword::IN,
17826                Keyword::SCHEMA,
17827            ]) {
17828                Some(GrantObjects::AllFunctionsInSchema {
17829                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17830                })
17831            } else if self.parse_keywords(&[
17832                Keyword::FUTURE,
17833                Keyword::SCHEMAS,
17834                Keyword::IN,
17835                Keyword::DATABASE,
17836            ]) {
17837                Some(GrantObjects::FutureSchemasInDatabase {
17838                    databases: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17839                })
17840            } else if self.parse_keywords(&[
17841                Keyword::FUTURE,
17842                Keyword::TABLES,
17843                Keyword::IN,
17844                Keyword::SCHEMA,
17845            ]) {
17846                Some(GrantObjects::FutureTablesInSchema {
17847                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17848                })
17849            } else if self.parse_keywords(&[
17850                Keyword::FUTURE,
17851                Keyword::EXTERNAL,
17852                Keyword::TABLES,
17853                Keyword::IN,
17854                Keyword::SCHEMA,
17855            ]) {
17856                Some(GrantObjects::FutureExternalTablesInSchema {
17857                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17858                })
17859            } else if self.parse_keywords(&[
17860                Keyword::FUTURE,
17861                Keyword::VIEWS,
17862                Keyword::IN,
17863                Keyword::SCHEMA,
17864            ]) {
17865                Some(GrantObjects::FutureViewsInSchema {
17866                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17867                })
17868            } else if self.parse_keywords(&[
17869                Keyword::FUTURE,
17870                Keyword::MATERIALIZED,
17871                Keyword::VIEWS,
17872                Keyword::IN,
17873                Keyword::SCHEMA,
17874            ]) {
17875                Some(GrantObjects::FutureMaterializedViewsInSchema {
17876                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17877                })
17878            } else if self.parse_keywords(&[
17879                Keyword::ALL,
17880                Keyword::SEQUENCES,
17881                Keyword::IN,
17882                Keyword::SCHEMA,
17883            ]) {
17884                Some(GrantObjects::AllSequencesInSchema {
17885                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17886                })
17887            } else if self.parse_keywords(&[
17888                Keyword::FUTURE,
17889                Keyword::SEQUENCES,
17890                Keyword::IN,
17891                Keyword::SCHEMA,
17892            ]) {
17893                Some(GrantObjects::FutureSequencesInSchema {
17894                    schemas: self.parse_comma_separated(|p| p.parse_object_name(false))?,
17895                })
17896            } else if self.parse_keywords(&[Keyword::RESOURCE, Keyword::MONITOR]) {
17897                Some(GrantObjects::ResourceMonitors(
17898                    self.parse_comma_separated(|p| p.parse_object_name(false))?,
17899                ))
17900            } else if self.parse_keywords(&[Keyword::COMPUTE, Keyword::POOL]) {
17901                Some(GrantObjects::ComputePools(
17902                    self.parse_comma_separated(|p| p.parse_object_name(false))?,
17903                ))
17904            } else if self.parse_keywords(&[Keyword::FAILOVER, Keyword::GROUP]) {
17905                Some(GrantObjects::FailoverGroup(
17906                    self.parse_comma_separated(|p| p.parse_object_name(false))?,
17907                ))
17908            } else if self.parse_keywords(&[Keyword::REPLICATION, Keyword::GROUP]) {
17909                Some(GrantObjects::ReplicationGroup(
17910                    self.parse_comma_separated(|p| p.parse_object_name(false))?,
17911                ))
17912            } else if self.parse_keywords(&[Keyword::EXTERNAL, Keyword::VOLUME]) {
17913                Some(GrantObjects::ExternalVolumes(
17914                    self.parse_comma_separated(|p| p.parse_object_name(false))?,
17915                ))
17916            } else {
17917                let object_type = self.parse_one_of_keywords(&[
17918                    Keyword::SEQUENCE,
17919                    Keyword::DATABASE,
17920                    Keyword::SCHEMA,
17921                    Keyword::TABLE,
17922                    Keyword::VIEW,
17923                    Keyword::WAREHOUSE,
17924                    Keyword::INTEGRATION,
17925                    Keyword::VIEW,
17926                    Keyword::WAREHOUSE,
17927                    Keyword::INTEGRATION,
17928                    Keyword::USER,
17929                    Keyword::CONNECTION,
17930                    Keyword::PROCEDURE,
17931                    Keyword::FUNCTION,
17932                ]);
17933                let objects =
17934                    self.parse_comma_separated(|p| p.parse_object_name_inner(false, true));
17935                match object_type {
17936                    Some(Keyword::DATABASE) => Some(GrantObjects::Databases(objects?)),
17937                    Some(Keyword::SCHEMA) => Some(GrantObjects::Schemas(objects?)),
17938                    Some(Keyword::SEQUENCE) => Some(GrantObjects::Sequences(objects?)),
17939                    Some(Keyword::WAREHOUSE) => Some(GrantObjects::Warehouses(objects?)),
17940                    Some(Keyword::INTEGRATION) => Some(GrantObjects::Integrations(objects?)),
17941                    Some(Keyword::VIEW) => Some(GrantObjects::Views(objects?)),
17942                    Some(Keyword::USER) => Some(GrantObjects::Users(objects?)),
17943                    Some(Keyword::CONNECTION) => Some(GrantObjects::Connections(objects?)),
17944                    kw @ (Some(Keyword::PROCEDURE) | Some(Keyword::FUNCTION)) => {
17945                        if let Some(name) = objects?.first() {
17946                            self.parse_grant_procedure_or_function(name, &kw)?
17947                        } else {
17948                            self.expected_ref("procedure or function name", self.peek_token_ref())?
17949                        }
17950                    }
17951                    Some(Keyword::TABLE) | None => Some(GrantObjects::Tables(objects?)),
17952                    Some(unexpected_keyword) => return Err(ParserError::ParserError(
17953                        format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in grant objects"),
17954                    )),
17955                }
17956            }
17957        } else {
17958            None
17959        };
17960
17961        Ok((privileges, objects))
17962    }
17963
17964    fn parse_grant_procedure_or_function(
17965        &mut self,
17966        name: &ObjectName,
17967        kw: &Option<Keyword>,
17968    ) -> Result<Option<GrantObjects>, ParserError> {
17969        let arg_types = if self.consume_token(&Token::LParen) {
17970            let list = self.parse_comma_separated0(Self::parse_data_type, Token::RParen)?;
17971            self.expect_token(&Token::RParen)?;
17972            list
17973        } else {
17974            vec![]
17975        };
17976        match kw {
17977            Some(Keyword::PROCEDURE) => Ok(Some(GrantObjects::Procedure {
17978                name: name.clone(),
17979                arg_types,
17980            })),
17981            Some(Keyword::FUNCTION) => Ok(Some(GrantObjects::Function {
17982                name: name.clone(),
17983                arg_types,
17984            })),
17985            _ => self.expected_ref("procedure or function keywords", self.peek_token_ref())?,
17986        }
17987    }
17988
17989    /// Parse a single grantable permission/action (used within GRANT statements).
17990    pub fn parse_grant_permission(&mut self) -> Result<Action, ParserError> {
17991        fn parse_columns(parser: &mut Parser) -> Result<Option<Vec<Ident>>, ParserError> {
17992            let columns = parser.parse_parenthesized_column_list(Optional, false)?;
17993            if columns.is_empty() {
17994                Ok(None)
17995            } else {
17996                Ok(Some(columns))
17997            }
17998        }
17999
18000        // Multi-word privileges
18001        if self.parse_keywords(&[Keyword::IMPORTED, Keyword::PRIVILEGES]) {
18002            Ok(Action::ImportedPrivileges)
18003        } else if self.parse_keywords(&[Keyword::ADD, Keyword::SEARCH, Keyword::OPTIMIZATION]) {
18004            Ok(Action::AddSearchOptimization)
18005        } else if self.parse_keywords(&[Keyword::ATTACH, Keyword::LISTING]) {
18006            Ok(Action::AttachListing)
18007        } else if self.parse_keywords(&[Keyword::ATTACH, Keyword::POLICY]) {
18008            Ok(Action::AttachPolicy)
18009        } else if self.parse_keywords(&[Keyword::BIND, Keyword::SERVICE, Keyword::ENDPOINT]) {
18010            Ok(Action::BindServiceEndpoint)
18011        } else if self.parse_keywords(&[Keyword::DATABASE, Keyword::ROLE]) {
18012            let role = self.parse_object_name(false)?;
18013            Ok(Action::DatabaseRole { role })
18014        } else if self.parse_keywords(&[Keyword::EVOLVE, Keyword::SCHEMA]) {
18015            Ok(Action::EvolveSchema)
18016        } else if self.parse_keywords(&[Keyword::IMPORT, Keyword::SHARE]) {
18017            Ok(Action::ImportShare)
18018        } else if self.parse_keywords(&[Keyword::MANAGE, Keyword::VERSIONS]) {
18019            Ok(Action::ManageVersions)
18020        } else if self.parse_keywords(&[Keyword::MANAGE, Keyword::RELEASES]) {
18021            Ok(Action::ManageReleases)
18022        } else if self.parse_keywords(&[Keyword::OVERRIDE, Keyword::SHARE, Keyword::RESTRICTIONS]) {
18023            Ok(Action::OverrideShareRestrictions)
18024        } else if self.parse_keywords(&[
18025            Keyword::PURCHASE,
18026            Keyword::DATA,
18027            Keyword::EXCHANGE,
18028            Keyword::LISTING,
18029        ]) {
18030            Ok(Action::PurchaseDataExchangeListing)
18031        } else if self.parse_keywords(&[Keyword::RESOLVE, Keyword::ALL]) {
18032            Ok(Action::ResolveAll)
18033        } else if self.parse_keywords(&[Keyword::READ, Keyword::SESSION]) {
18034            Ok(Action::ReadSession)
18035
18036        // Single-word privileges
18037        } else if self.parse_keyword(Keyword::APPLY) {
18038            let apply_type = self.parse_action_apply_type()?;
18039            Ok(Action::Apply { apply_type })
18040        } else if self.parse_keyword(Keyword::APPLYBUDGET) {
18041            Ok(Action::ApplyBudget)
18042        } else if self.parse_keyword(Keyword::AUDIT) {
18043            Ok(Action::Audit)
18044        } else if self.parse_keyword(Keyword::CONNECT) {
18045            Ok(Action::Connect)
18046        } else if self.parse_keyword(Keyword::CREATE) {
18047            let obj_type = self.maybe_parse_action_create_object_type();
18048            Ok(Action::Create { obj_type })
18049        } else if self.parse_keyword(Keyword::DELETE) {
18050            Ok(Action::Delete)
18051        } else if self.parse_keyword(Keyword::EXEC) {
18052            let obj_type = self.maybe_parse_action_execute_obj_type();
18053            Ok(Action::Exec { obj_type })
18054        } else if self.parse_keyword(Keyword::EXECUTE) {
18055            let obj_type = self.maybe_parse_action_execute_obj_type();
18056            Ok(Action::Execute { obj_type })
18057        } else if self.parse_keyword(Keyword::FAILOVER) {
18058            Ok(Action::Failover)
18059        } else if self.parse_keyword(Keyword::INSERT) {
18060            Ok(Action::Insert {
18061                columns: parse_columns(self)?,
18062            })
18063        } else if self.parse_keyword(Keyword::MANAGE) {
18064            let manage_type = self.parse_action_manage_type()?;
18065            Ok(Action::Manage { manage_type })
18066        } else if self.parse_keyword(Keyword::MODIFY) {
18067            let modify_type = self.parse_action_modify_type();
18068            Ok(Action::Modify { modify_type })
18069        } else if self.parse_keyword(Keyword::MONITOR) {
18070            let monitor_type = self.parse_action_monitor_type();
18071            Ok(Action::Monitor { monitor_type })
18072        } else if self.parse_keyword(Keyword::OPERATE) {
18073            Ok(Action::Operate)
18074        } else if self.parse_keyword(Keyword::REFERENCES) {
18075            Ok(Action::References {
18076                columns: parse_columns(self)?,
18077            })
18078        } else if self.parse_keyword(Keyword::READ) {
18079            Ok(Action::Read)
18080        } else if self.parse_keyword(Keyword::REPLICATE) {
18081            Ok(Action::Replicate)
18082        } else if self.parse_keyword(Keyword::ROLE) {
18083            let role = self.parse_object_name(false)?;
18084            Ok(Action::Role { role })
18085        } else if self.parse_keyword(Keyword::SELECT) {
18086            Ok(Action::Select {
18087                columns: parse_columns(self)?,
18088            })
18089        } else if self.parse_keyword(Keyword::TEMPORARY) {
18090            Ok(Action::Temporary)
18091        } else if self.parse_keyword(Keyword::TRIGGER) {
18092            Ok(Action::Trigger)
18093        } else if self.parse_keyword(Keyword::TRUNCATE) {
18094            Ok(Action::Truncate)
18095        } else if self.parse_keyword(Keyword::UPDATE) {
18096            Ok(Action::Update {
18097                columns: parse_columns(self)?,
18098            })
18099        } else if self.parse_keyword(Keyword::USAGE) {
18100            Ok(Action::Usage)
18101        } else if self.parse_keyword(Keyword::OWNERSHIP) {
18102            Ok(Action::Ownership)
18103        } else if self.parse_keyword(Keyword::DROP) {
18104            Ok(Action::Drop)
18105        } else {
18106            self.expected_ref("a privilege keyword", self.peek_token_ref())?
18107        }
18108    }
18109
18110    fn maybe_parse_action_create_object_type(&mut self) -> Option<ActionCreateObjectType> {
18111        // Multi-word object types
18112        if self.parse_keywords(&[Keyword::APPLICATION, Keyword::PACKAGE]) {
18113            Some(ActionCreateObjectType::ApplicationPackage)
18114        } else if self.parse_keywords(&[Keyword::COMPUTE, Keyword::POOL]) {
18115            Some(ActionCreateObjectType::ComputePool)
18116        } else if self.parse_keywords(&[Keyword::DATA, Keyword::EXCHANGE, Keyword::LISTING]) {
18117            Some(ActionCreateObjectType::DataExchangeListing)
18118        } else if self.parse_keywords(&[Keyword::EXTERNAL, Keyword::VOLUME]) {
18119            Some(ActionCreateObjectType::ExternalVolume)
18120        } else if self.parse_keywords(&[Keyword::FAILOVER, Keyword::GROUP]) {
18121            Some(ActionCreateObjectType::FailoverGroup)
18122        } else if self.parse_keywords(&[Keyword::NETWORK, Keyword::POLICY]) {
18123            Some(ActionCreateObjectType::NetworkPolicy)
18124        } else if self.parse_keywords(&[Keyword::ORGANIZATION, Keyword::LISTING]) {
18125            Some(ActionCreateObjectType::OrganiationListing)
18126        } else if self.parse_keywords(&[Keyword::REPLICATION, Keyword::GROUP]) {
18127            Some(ActionCreateObjectType::ReplicationGroup)
18128        }
18129        // Single-word object types
18130        else if self.parse_keyword(Keyword::ACCOUNT) {
18131            Some(ActionCreateObjectType::Account)
18132        } else if self.parse_keyword(Keyword::APPLICATION) {
18133            Some(ActionCreateObjectType::Application)
18134        } else if self.parse_keyword(Keyword::DATABASE) {
18135            Some(ActionCreateObjectType::Database)
18136        } else if self.parse_keyword(Keyword::INTEGRATION) {
18137            Some(ActionCreateObjectType::Integration)
18138        } else if self.parse_keyword(Keyword::ROLE) {
18139            Some(ActionCreateObjectType::Role)
18140        } else if self.parse_keyword(Keyword::SCHEMA) {
18141            Some(ActionCreateObjectType::Schema)
18142        } else if self.parse_keyword(Keyword::SHARE) {
18143            Some(ActionCreateObjectType::Share)
18144        } else if self.parse_keyword(Keyword::USER) {
18145            Some(ActionCreateObjectType::User)
18146        } else if self.parse_keyword(Keyword::WAREHOUSE) {
18147            Some(ActionCreateObjectType::Warehouse)
18148        } else {
18149            None
18150        }
18151    }
18152
18153    fn parse_action_apply_type(&mut self) -> Result<ActionApplyType, ParserError> {
18154        if self.parse_keywords(&[Keyword::AGGREGATION, Keyword::POLICY]) {
18155            Ok(ActionApplyType::AggregationPolicy)
18156        } else if self.parse_keywords(&[Keyword::AUTHENTICATION, Keyword::POLICY]) {
18157            Ok(ActionApplyType::AuthenticationPolicy)
18158        } else if self.parse_keywords(&[Keyword::JOIN, Keyword::POLICY]) {
18159            Ok(ActionApplyType::JoinPolicy)
18160        } else if self.parse_keywords(&[Keyword::MASKING, Keyword::POLICY]) {
18161            Ok(ActionApplyType::MaskingPolicy)
18162        } else if self.parse_keywords(&[Keyword::PACKAGES, Keyword::POLICY]) {
18163            Ok(ActionApplyType::PackagesPolicy)
18164        } else if self.parse_keywords(&[Keyword::PASSWORD, Keyword::POLICY]) {
18165            Ok(ActionApplyType::PasswordPolicy)
18166        } else if self.parse_keywords(&[Keyword::PROJECTION, Keyword::POLICY]) {
18167            Ok(ActionApplyType::ProjectionPolicy)
18168        } else if self.parse_keywords(&[Keyword::ROW, Keyword::ACCESS, Keyword::POLICY]) {
18169            Ok(ActionApplyType::RowAccessPolicy)
18170        } else if self.parse_keywords(&[Keyword::SESSION, Keyword::POLICY]) {
18171            Ok(ActionApplyType::SessionPolicy)
18172        } else if self.parse_keyword(Keyword::TAG) {
18173            Ok(ActionApplyType::Tag)
18174        } else {
18175            self.expected_ref("GRANT APPLY type", self.peek_token_ref())
18176        }
18177    }
18178
18179    fn maybe_parse_action_execute_obj_type(&mut self) -> Option<ActionExecuteObjectType> {
18180        if self.parse_keywords(&[Keyword::DATA, Keyword::METRIC, Keyword::FUNCTION]) {
18181            Some(ActionExecuteObjectType::DataMetricFunction)
18182        } else if self.parse_keywords(&[Keyword::MANAGED, Keyword::ALERT]) {
18183            Some(ActionExecuteObjectType::ManagedAlert)
18184        } else if self.parse_keywords(&[Keyword::MANAGED, Keyword::TASK]) {
18185            Some(ActionExecuteObjectType::ManagedTask)
18186        } else if self.parse_keyword(Keyword::ALERT) {
18187            Some(ActionExecuteObjectType::Alert)
18188        } else if self.parse_keyword(Keyword::TASK) {
18189            Some(ActionExecuteObjectType::Task)
18190        } else {
18191            None
18192        }
18193    }
18194
18195    fn parse_action_manage_type(&mut self) -> Result<ActionManageType, ParserError> {
18196        if self.parse_keywords(&[Keyword::ACCOUNT, Keyword::SUPPORT, Keyword::CASES]) {
18197            Ok(ActionManageType::AccountSupportCases)
18198        } else if self.parse_keywords(&[Keyword::EVENT, Keyword::SHARING]) {
18199            Ok(ActionManageType::EventSharing)
18200        } else if self.parse_keywords(&[Keyword::LISTING, Keyword::AUTO, Keyword::FULFILLMENT]) {
18201            Ok(ActionManageType::ListingAutoFulfillment)
18202        } else if self.parse_keywords(&[Keyword::ORGANIZATION, Keyword::SUPPORT, Keyword::CASES]) {
18203            Ok(ActionManageType::OrganizationSupportCases)
18204        } else if self.parse_keywords(&[Keyword::USER, Keyword::SUPPORT, Keyword::CASES]) {
18205            Ok(ActionManageType::UserSupportCases)
18206        } else if self.parse_keyword(Keyword::GRANTS) {
18207            Ok(ActionManageType::Grants)
18208        } else if self.parse_keyword(Keyword::WAREHOUSES) {
18209            Ok(ActionManageType::Warehouses)
18210        } else {
18211            self.expected_ref("GRANT MANAGE type", self.peek_token_ref())
18212        }
18213    }
18214
18215    fn parse_action_modify_type(&mut self) -> Option<ActionModifyType> {
18216        if self.parse_keywords(&[Keyword::LOG, Keyword::LEVEL]) {
18217            Some(ActionModifyType::LogLevel)
18218        } else if self.parse_keywords(&[Keyword::TRACE, Keyword::LEVEL]) {
18219            Some(ActionModifyType::TraceLevel)
18220        } else if self.parse_keywords(&[Keyword::SESSION, Keyword::LOG, Keyword::LEVEL]) {
18221            Some(ActionModifyType::SessionLogLevel)
18222        } else if self.parse_keywords(&[Keyword::SESSION, Keyword::TRACE, Keyword::LEVEL]) {
18223            Some(ActionModifyType::SessionTraceLevel)
18224        } else {
18225            None
18226        }
18227    }
18228
18229    fn parse_action_monitor_type(&mut self) -> Option<ActionMonitorType> {
18230        if self.parse_keyword(Keyword::EXECUTION) {
18231            Some(ActionMonitorType::Execution)
18232        } else if self.parse_keyword(Keyword::SECURITY) {
18233            Some(ActionMonitorType::Security)
18234        } else if self.parse_keyword(Keyword::USAGE) {
18235            Some(ActionMonitorType::Usage)
18236        } else {
18237            None
18238        }
18239    }
18240
18241    /// Parse a grantee name, possibly with a host qualifier (user@host).
18242    pub fn parse_grantee_name(&mut self) -> Result<GranteeName, ParserError> {
18243        let mut name = self.parse_object_name(false)?;
18244        if self.dialect.supports_user_host_grantee()
18245            && name.0.len() == 1
18246            && name.0[0].as_ident().is_some()
18247            && self.consume_token(&Token::AtSign)
18248        {
18249            let user = name.0.pop().unwrap().as_ident().unwrap().clone();
18250            let host = self.parse_identifier()?;
18251            Ok(GranteeName::UserHost { user, host })
18252        } else {
18253            Ok(GranteeName::ObjectName(name))
18254        }
18255    }
18256
18257    /// Parse [`Statement::Deny`]
18258    pub fn parse_deny(&mut self) -> Result<Statement, ParserError> {
18259        self.expect_keyword(Keyword::DENY)?;
18260
18261        let (privileges, objects) = self.parse_grant_deny_revoke_privileges_objects()?;
18262        let objects = match objects {
18263            Some(o) => o,
18264            None => {
18265                return parser_err!(
18266                    "DENY statements must specify an object",
18267                    self.peek_token_ref().span.start
18268                )
18269            }
18270        };
18271
18272        self.expect_keyword_is(Keyword::TO)?;
18273        let grantees = self.parse_grantees()?;
18274        let cascade = self.parse_cascade_option();
18275        let granted_by = if self.parse_keywords(&[Keyword::AS]) {
18276            Some(self.parse_identifier()?)
18277        } else {
18278            None
18279        };
18280
18281        Ok(Statement::Deny(DenyStatement {
18282            privileges,
18283            objects,
18284            grantees,
18285            cascade,
18286            granted_by,
18287        }))
18288    }
18289
18290    /// Parse a REVOKE statement
18291    pub fn parse_revoke(&mut self) -> Result<Revoke, ParserError> {
18292        let (privileges, objects) = self.parse_grant_deny_revoke_privileges_objects()?;
18293
18294        self.expect_keyword_is(Keyword::FROM)?;
18295        let grantees = self.parse_grantees()?;
18296
18297        let granted_by = if self.parse_keywords(&[Keyword::GRANTED, Keyword::BY]) {
18298            Some(self.parse_identifier()?)
18299        } else {
18300            None
18301        };
18302
18303        let cascade = self.parse_cascade_option();
18304
18305        Ok(Revoke {
18306            privileges,
18307            objects,
18308            grantees,
18309            granted_by,
18310            cascade,
18311        })
18312    }
18313
18314    /// Parse an REPLACE statement
18315    pub fn parse_replace(
18316        &mut self,
18317        replace_token: TokenWithSpan,
18318    ) -> Result<Statement, ParserError> {
18319        if !dialect_of!(self is MySqlDialect | GenericDialect) {
18320            return parser_err!(
18321                "Unsupported statement REPLACE",
18322                self.peek_token_ref().span.start
18323            );
18324        }
18325
18326        let mut insert = self.parse_insert(replace_token)?;
18327        if let Statement::Insert(Insert { replace_into, .. }) = &mut insert {
18328            *replace_into = true;
18329        }
18330
18331        Ok(insert)
18332    }
18333
18334    /// Parse an INSERT statement, returning a `Box`ed SetExpr
18335    ///
18336    /// This is used to reduce the size of the stack frames in debug builds
18337    fn parse_insert_setexpr_boxed(
18338        &mut self,
18339        insert_token: TokenWithSpan,
18340    ) -> Result<Box<SetExpr>, ParserError> {
18341        Ok(Box::new(SetExpr::Insert(self.parse_insert(insert_token)?)))
18342    }
18343
18344    /// Parse an INSERT statement
18345    pub fn parse_insert(&mut self, insert_token: TokenWithSpan) -> Result<Statement, ParserError> {
18346        let optimizer_hints = self.maybe_parse_optimizer_hints()?;
18347        let or = self.parse_conflict_clause();
18348        let priority = if !dialect_of!(self is MySqlDialect | GenericDialect) {
18349            None
18350        } else if self.parse_keyword(Keyword::LOW_PRIORITY) {
18351            Some(MysqlInsertPriority::LowPriority)
18352        } else if self.parse_keyword(Keyword::DELAYED) {
18353            Some(MysqlInsertPriority::Delayed)
18354        } else if self.parse_keyword(Keyword::HIGH_PRIORITY) {
18355            Some(MysqlInsertPriority::HighPriority)
18356        } else {
18357            None
18358        };
18359
18360        let ignore = dialect_of!(self is MySqlDialect | GenericDialect)
18361            && self.parse_keyword(Keyword::IGNORE);
18362
18363        let replace_into = false;
18364
18365        let overwrite = self.parse_keyword(Keyword::OVERWRITE);
18366        let into = self.parse_keyword(Keyword::INTO);
18367
18368        let local = self.parse_keyword(Keyword::LOCAL);
18369
18370        if self.parse_keyword(Keyword::DIRECTORY) {
18371            let path = self.parse_literal_string()?;
18372            let file_format = if self.parse_keywords(&[Keyword::STORED, Keyword::AS]) {
18373                Some(self.parse_file_format()?)
18374            } else {
18375                None
18376            };
18377            let source = self.parse_query()?;
18378            Ok(Statement::Directory {
18379                local,
18380                path,
18381                overwrite,
18382                file_format,
18383                source,
18384            })
18385        } else {
18386            // Hive lets you put table here regardless
18387            let table = self.parse_keyword(Keyword::TABLE);
18388            let table_object = self.parse_table_object()?;
18389
18390            let table_alias = if self.dialect.supports_insert_table_alias()
18391                && !self.peek_sub_query()
18392                && self
18393                    .peek_one_of_keywords(&[Keyword::DEFAULT, Keyword::VALUES])
18394                    .is_none()
18395            {
18396                if self.parse_keyword(Keyword::AS) {
18397                    Some(TableAliasWithoutColumns {
18398                        explicit: true,
18399                        alias: self.parse_identifier()?,
18400                    })
18401                } else {
18402                    self.maybe_parse(|parser| parser.parse_identifier())?
18403                        .map(|alias| TableAliasWithoutColumns {
18404                            explicit: false,
18405                            alias,
18406                        })
18407                }
18408            } else {
18409                None
18410            };
18411
18412            let is_mysql = dialect_of!(self is MySqlDialect);
18413
18414            let (columns, partitioned, after_columns, output, source, assignments) = if self
18415                .parse_keywords(&[Keyword::DEFAULT, Keyword::VALUES])
18416            {
18417                (vec![], None, vec![], None, None, vec![])
18418            } else {
18419                let (columns, partitioned, after_columns) = if !self.peek_subquery_start() {
18420                    let columns =
18421                        self.parse_parenthesized_qualified_column_list(Optional, is_mysql)?;
18422
18423                    let partitioned = self.parse_insert_partition()?;
18424                    // Hive allows you to specify columns after partitions as well if you want.
18425                    let after_columns = if dialect_of!(self is HiveDialect) {
18426                        self.parse_parenthesized_column_list(Optional, false)?
18427                    } else {
18428                        vec![]
18429                    };
18430                    (columns, partitioned, after_columns)
18431                } else {
18432                    Default::default()
18433                };
18434
18435                let output = self.maybe_parse_output_clause()?;
18436
18437                let (source, assignments) = if self.peek_keyword(Keyword::FORMAT)
18438                    || self.peek_keyword(Keyword::SETTINGS)
18439                {
18440                    (None, vec![])
18441                } else if self.dialect.supports_insert_set() && self.parse_keyword(Keyword::SET) {
18442                    (None, self.parse_comma_separated(Parser::parse_assignment)?)
18443                } else {
18444                    (Some(self.parse_query()?), vec![])
18445                };
18446
18447                (
18448                    columns,
18449                    partitioned,
18450                    after_columns,
18451                    output,
18452                    source,
18453                    assignments,
18454                )
18455            };
18456
18457            let (format_clause, settings) = if self.dialect.supports_insert_format() {
18458                // Settings always comes before `FORMAT` for ClickHouse:
18459                // <https://clickhouse.com/docs/en/sql-reference/statements/insert-into>
18460                let settings = self.parse_settings()?;
18461
18462                let format = if self.parse_keyword(Keyword::FORMAT) {
18463                    Some(self.parse_input_format_clause()?)
18464                } else {
18465                    None
18466                };
18467
18468                (format, settings)
18469            } else {
18470                Default::default()
18471            };
18472
18473            let insert_alias = if dialect_of!(self is MySqlDialect | GenericDialect)
18474                && self.parse_keyword(Keyword::AS)
18475            {
18476                let row_alias = self.parse_object_name(false)?;
18477                let col_aliases = Some(self.parse_parenthesized_column_list(Optional, false)?);
18478                Some(InsertAliases {
18479                    row_alias,
18480                    col_aliases,
18481                })
18482            } else {
18483                None
18484            };
18485
18486            let on = if self.parse_keyword(Keyword::ON) {
18487                if self.parse_keyword(Keyword::CONFLICT) {
18488                    let conflict_target =
18489                        if self.parse_keywords(&[Keyword::ON, Keyword::CONSTRAINT]) {
18490                            Some(ConflictTarget::OnConstraint(self.parse_object_name(false)?))
18491                        } else if self.peek_token_ref().token == Token::LParen {
18492                            Some(ConflictTarget::Columns(
18493                                self.parse_parenthesized_column_list(IsOptional::Mandatory, false)?,
18494                            ))
18495                        } else {
18496                            None
18497                        };
18498
18499                    self.expect_keyword_is(Keyword::DO)?;
18500                    let action = if self.parse_keyword(Keyword::NOTHING) {
18501                        OnConflictAction::DoNothing
18502                    } else {
18503                        self.expect_keyword_is(Keyword::UPDATE)?;
18504                        self.expect_keyword_is(Keyword::SET)?;
18505                        let assignments = self.parse_comma_separated(Parser::parse_assignment)?;
18506                        let selection = if self.parse_keyword(Keyword::WHERE) {
18507                            Some(self.parse_expr()?)
18508                        } else {
18509                            None
18510                        };
18511                        OnConflictAction::DoUpdate(DoUpdate {
18512                            assignments,
18513                            selection,
18514                        })
18515                    };
18516
18517                    Some(OnInsert::OnConflict(OnConflict {
18518                        conflict_target,
18519                        action,
18520                    }))
18521                } else {
18522                    self.expect_keyword_is(Keyword::DUPLICATE)?;
18523                    self.expect_keyword_is(Keyword::KEY)?;
18524                    self.expect_keyword_is(Keyword::UPDATE)?;
18525                    let l = self.parse_comma_separated(Parser::parse_assignment)?;
18526
18527                    Some(OnInsert::DuplicateKeyUpdate(l))
18528                }
18529            } else {
18530                None
18531            };
18532
18533            let returning = if self.parse_keyword(Keyword::RETURNING) {
18534                Some(self.parse_comma_separated(Parser::parse_select_item)?)
18535            } else {
18536                None
18537            };
18538
18539            Ok(Insert {
18540                insert_token: insert_token.into(),
18541                optimizer_hints,
18542                or,
18543                table: table_object,
18544                table_alias,
18545                ignore,
18546                into,
18547                overwrite,
18548                partitioned,
18549                columns,
18550                after_columns,
18551                source,
18552                assignments,
18553                has_table_keyword: table,
18554                on,
18555                returning,
18556                output,
18557                replace_into,
18558                priority,
18559                insert_alias,
18560                settings,
18561                format_clause,
18562                multi_table_insert_type: None,
18563                multi_table_into_clauses: vec![],
18564                multi_table_when_clauses: vec![],
18565                multi_table_else_clause: None,
18566            }
18567            .into())
18568        }
18569    }
18570
18571    /// Parses input format clause used for ClickHouse.
18572    ///
18573    /// <https://clickhouse.com/docs/en/interfaces/formats>
18574    pub fn parse_input_format_clause(&mut self) -> Result<InputFormatClause, ParserError> {
18575        let ident = self.parse_identifier()?;
18576        let values = self
18577            .maybe_parse(|p| p.parse_comma_separated(|p| p.parse_expr()))?
18578            .unwrap_or_default();
18579
18580        Ok(InputFormatClause { ident, values })
18581    }
18582
18583    /// Returns true if the immediate tokens look like the
18584    /// beginning of a subquery. `(SELECT ...` or `((SELECT ...` etc.
18585    fn peek_subquery_start(&mut self) -> bool {
18586        // Handle (SELECT, ((SELECT, (((SELECT, etc.
18587        // This makes INSERT consistent with other contexts where nested
18588        // parentheses around subqueries are handled by recursive descent.
18589        let mut i = 0;
18590        loop {
18591            match &self.peek_nth_token_ref(i).token {
18592                Token::LParen => i += 1,
18593                Token::Word(w) if w.keyword == Keyword::SELECT => return i > 0,
18594                _ => return false,
18595            }
18596        }
18597    }
18598
18599    /// Returns true if the immediate tokens look like the
18600    /// beginning of a subquery possibly preceded by CTEs;
18601    /// i.e. `(WITH ...` or `(SELECT ...`.
18602    fn peek_subquery_or_cte_start(&mut self) -> bool {
18603        matches!(
18604            self.peek_tokens_ref(),
18605            [
18606                TokenWithSpan {
18607                    token: Token::LParen,
18608                    ..
18609                },
18610                TokenWithSpan {
18611                    token: Token::Word(Word {
18612                        keyword: Keyword::SELECT | Keyword::WITH,
18613                        ..
18614                    }),
18615                    ..
18616                },
18617            ]
18618        )
18619    }
18620
18621    fn parse_conflict_clause(&mut self) -> Option<SqliteOnConflict> {
18622        if self.parse_keywords(&[Keyword::OR, Keyword::REPLACE]) {
18623            Some(SqliteOnConflict::Replace)
18624        } else if self.parse_keywords(&[Keyword::OR, Keyword::ROLLBACK]) {
18625            Some(SqliteOnConflict::Rollback)
18626        } else if self.parse_keywords(&[Keyword::OR, Keyword::ABORT]) {
18627            Some(SqliteOnConflict::Abort)
18628        } else if self.parse_keywords(&[Keyword::OR, Keyword::FAIL]) {
18629            Some(SqliteOnConflict::Fail)
18630        } else if self.parse_keywords(&[Keyword::OR, Keyword::IGNORE]) {
18631            Some(SqliteOnConflict::Ignore)
18632        } else if self.parse_keyword(Keyword::REPLACE) {
18633            Some(SqliteOnConflict::Replace)
18634        } else {
18635            None
18636        }
18637    }
18638
18639    /// Parse an optional `PARTITION (...)` clause for INSERT statements.
18640    pub fn parse_insert_partition(&mut self) -> Result<Option<Vec<Expr>>, ParserError> {
18641        if self.parse_keyword(Keyword::PARTITION) {
18642            self.expect_token(&Token::LParen)?;
18643            let partition_cols = Some(self.parse_comma_separated(Parser::parse_expr)?);
18644            self.expect_token(&Token::RParen)?;
18645            Ok(partition_cols)
18646        } else {
18647            Ok(None)
18648        }
18649    }
18650
18651    /// Parse optional Hive `INPUTFORMAT ... SERDE ...` clause used by LOAD DATA.
18652    pub fn parse_load_data_table_format(
18653        &mut self,
18654    ) -> Result<Option<HiveLoadDataFormat>, ParserError> {
18655        if self.parse_keyword(Keyword::INPUTFORMAT) {
18656            let input_format = self.parse_expr()?;
18657            self.expect_keyword_is(Keyword::SERDE)?;
18658            let serde = self.parse_expr()?;
18659            Ok(Some(HiveLoadDataFormat {
18660                input_format,
18661                serde,
18662            }))
18663        } else {
18664            Ok(None)
18665        }
18666    }
18667
18668    /// Parse an UPDATE statement, returning a `Box`ed SetExpr
18669    ///
18670    /// This is used to reduce the size of the stack frames in debug builds
18671    fn parse_update_setexpr_boxed(
18672        &mut self,
18673        update_token: TokenWithSpan,
18674    ) -> Result<Box<SetExpr>, ParserError> {
18675        Ok(Box::new(SetExpr::Update(self.parse_update(update_token)?)))
18676    }
18677
18678    /// Parse an `UPDATE` statement and return `Statement::Update`.
18679    pub fn parse_update(&mut self, update_token: TokenWithSpan) -> Result<Statement, ParserError> {
18680        let optimizer_hints = self.maybe_parse_optimizer_hints()?;
18681        let or = self.parse_conflict_clause();
18682        let table = self.parse_table_and_joins()?;
18683        let from_before_set = if self.parse_keyword(Keyword::FROM) {
18684            Some(UpdateTableFromKind::BeforeSet(
18685                self.parse_table_with_joins()?,
18686            ))
18687        } else {
18688            None
18689        };
18690        self.expect_keyword(Keyword::SET)?;
18691        let assignments = self.parse_comma_separated(Parser::parse_assignment)?;
18692
18693        let output = self.maybe_parse_output_clause()?;
18694
18695        let from = if from_before_set.is_none() && self.parse_keyword(Keyword::FROM) {
18696            Some(UpdateTableFromKind::AfterSet(
18697                self.parse_table_with_joins()?,
18698            ))
18699        } else {
18700            from_before_set
18701        };
18702        let selection = if self.parse_keyword(Keyword::WHERE) {
18703            Some(self.parse_expr()?)
18704        } else {
18705            None
18706        };
18707        let returning = if self.parse_keyword(Keyword::RETURNING) {
18708            Some(self.parse_comma_separated(Parser::parse_select_item)?)
18709        } else {
18710            None
18711        };
18712        let order_by = if self.dialect.supports_update_order_by()
18713            && self.parse_keywords(&[Keyword::ORDER, Keyword::BY])
18714        {
18715            self.parse_comma_separated(Parser::parse_order_by_expr)?
18716        } else {
18717            vec![]
18718        };
18719        let limit = if self.parse_keyword(Keyword::LIMIT) {
18720            Some(self.parse_expr()?)
18721        } else {
18722            None
18723        };
18724        Ok(Update {
18725            update_token: update_token.into(),
18726            optimizer_hints,
18727            table,
18728            assignments,
18729            from,
18730            selection,
18731            returning,
18732            output,
18733            or,
18734            order_by,
18735            limit,
18736        }
18737        .into())
18738    }
18739
18740    /// Parse a `var = expr` assignment, used in an UPDATE statement
18741    pub fn parse_assignment(&mut self) -> Result<Assignment, ParserError> {
18742        let target = self.parse_assignment_target()?;
18743        self.expect_token(&Token::Eq)?;
18744        let value = self.parse_expr()?;
18745        Ok(Assignment { target, value })
18746    }
18747
18748    /// Parse the left-hand side of an assignment, used in an UPDATE statement
18749    pub fn parse_assignment_target(&mut self) -> Result<AssignmentTarget, ParserError> {
18750        if self.consume_token(&Token::LParen) {
18751            let columns = self.parse_comma_separated(|p| p.parse_object_name(false))?;
18752            self.expect_token(&Token::RParen)?;
18753            Ok(AssignmentTarget::Tuple(columns))
18754        } else {
18755            let column = self.parse_object_name(false)?;
18756            Ok(AssignmentTarget::ColumnName(column))
18757        }
18758    }
18759
18760    /// Parse a single function argument, handling named and unnamed variants.
18761    pub fn parse_function_args(&mut self) -> Result<FunctionArg, ParserError> {
18762        let arg = if self.dialect.supports_named_fn_args_with_expr_name() {
18763            self.maybe_parse(|p| {
18764                let name = p.parse_expr()?;
18765                let operator = p.parse_function_named_arg_operator()?;
18766                let arg = p.parse_wildcard_expr()?.into();
18767                Ok(FunctionArg::ExprNamed {
18768                    name,
18769                    arg,
18770                    operator,
18771                })
18772            })?
18773        } else {
18774            self.maybe_parse(|p| {
18775                let name = p.parse_identifier()?;
18776                let operator = p.parse_function_named_arg_operator()?;
18777                let arg = p.parse_wildcard_expr()?.into();
18778                Ok(FunctionArg::Named {
18779                    name,
18780                    arg,
18781                    operator,
18782                })
18783            })?
18784        };
18785        if let Some(arg) = arg {
18786            return Ok(arg);
18787        }
18788        let wildcard_expr = self.parse_wildcard_expr()?;
18789        let arg_expr: FunctionArgExpr = match wildcard_expr {
18790            Expr::Wildcard(ref token) if self.dialect.supports_select_wildcard_exclude() => {
18791                // Support `* EXCLUDE(col1, col2, ...)` inside function calls (e.g. Snowflake's
18792                // `HASH(* EXCLUDE(col))`).  Parse the options the same way SELECT items do.
18793                let opts = self.parse_wildcard_additional_options(token.0.clone())?;
18794                if opts.opt_exclude.is_some()
18795                    || opts.opt_except.is_some()
18796                    || opts.opt_replace.is_some()
18797                    || opts.opt_rename.is_some()
18798                    || opts.opt_ilike.is_some()
18799                {
18800                    FunctionArgExpr::WildcardWithOptions(opts)
18801                } else {
18802                    wildcard_expr.into()
18803                }
18804            }
18805            other => other.into(),
18806        };
18807        // Aliased argument, e.g. `XMLFOREST(a AS x)` in PostgreSQL
18808        let arg_expr = match arg_expr {
18809            FunctionArgExpr::Expr(expr)
18810                if self.dialect.supports_aliased_function_args()
18811                    && self.parse_keyword(Keyword::AS) =>
18812            {
18813                FunctionArgExpr::Expr(Expr::Named {
18814                    expr: expr.into(),
18815                    name: self.parse_identifier()?,
18816                })
18817            }
18818            other => other,
18819        };
18820        Ok(FunctionArg::Unnamed(arg_expr))
18821    }
18822
18823    fn parse_function_named_arg_operator(&mut self) -> Result<FunctionArgOperator, ParserError> {
18824        if self.parse_keyword(Keyword::VALUE) {
18825            return Ok(FunctionArgOperator::Value);
18826        }
18827        let tok = self.next_token();
18828        match tok.token {
18829            Token::RArrow if self.dialect.supports_named_fn_args_with_rarrow_operator() => {
18830                Ok(FunctionArgOperator::RightArrow)
18831            }
18832            Token::Eq if self.dialect.supports_named_fn_args_with_eq_operator() => {
18833                Ok(FunctionArgOperator::Equals)
18834            }
18835            Token::Assignment
18836                if self
18837                    .dialect
18838                    .supports_named_fn_args_with_assignment_operator() =>
18839            {
18840                Ok(FunctionArgOperator::Assignment)
18841            }
18842            Token::Colon if self.dialect.supports_named_fn_args_with_colon_operator() => {
18843                Ok(FunctionArgOperator::Colon)
18844            }
18845            _ => {
18846                self.prev_token();
18847                self.expected("argument operator", tok)
18848            }
18849        }
18850    }
18851
18852    /// Parse an optional, comma-separated list of function arguments (consumes closing paren).
18853    pub fn parse_optional_args(&mut self) -> Result<Vec<FunctionArg>, ParserError> {
18854        if self.consume_token(&Token::RParen) {
18855            Ok(vec![])
18856        } else {
18857            let args = self.parse_comma_separated(Parser::parse_function_args)?;
18858            self.expect_token(&Token::RParen)?;
18859            Ok(args)
18860        }
18861    }
18862
18863    fn parse_table_function_args(&mut self) -> Result<TableFunctionArgs, ParserError> {
18864        if self.consume_token(&Token::RParen) {
18865            return Ok(TableFunctionArgs {
18866                args: vec![],
18867                settings: None,
18868            });
18869        }
18870        let mut args = vec![];
18871        let settings = loop {
18872            if let Some(settings) = self.parse_settings()? {
18873                break Some(settings);
18874            }
18875            args.push(self.parse_function_args()?);
18876            if self.is_parse_comma_separated_end() {
18877                break None;
18878            }
18879        };
18880        self.expect_token(&Token::RParen)?;
18881        Ok(TableFunctionArgs { args, settings })
18882    }
18883
18884    /// Parses a potentially empty list of arguments to a function
18885    /// (including the closing parenthesis).
18886    ///
18887    /// Examples:
18888    /// ```sql
18889    /// FIRST_VALUE(x ORDER BY 1,2,3);
18890    /// FIRST_VALUE(x IGNORE NULL);
18891    /// ```
18892    fn parse_function_argument_list(&mut self) -> Result<FunctionArgumentList, ParserError> {
18893        let mut clauses = vec![];
18894
18895        // Handle clauses that may exist with an empty argument list
18896
18897        if let Some(null_clause) = self.parse_json_null_clause() {
18898            clauses.push(FunctionArgumentClause::JsonNullClause(null_clause));
18899        }
18900
18901        if let Some(json_returning_clause) = self.maybe_parse_json_returning_clause()? {
18902            clauses.push(FunctionArgumentClause::JsonReturningClause(
18903                json_returning_clause,
18904            ));
18905        }
18906
18907        if self.consume_token(&Token::RParen) {
18908            return Ok(FunctionArgumentList {
18909                duplicate_treatment: None,
18910                args: vec![],
18911                clauses,
18912            });
18913        }
18914
18915        let duplicate_treatment = self.parse_duplicate_treatment()?;
18916        let args = self.parse_comma_separated(Parser::parse_function_args)?;
18917
18918        if self.dialect.supports_window_function_null_treatment_arg() {
18919            if let Some(null_treatment) = self.parse_null_treatment()? {
18920                clauses.push(FunctionArgumentClause::IgnoreOrRespectNulls(null_treatment));
18921            }
18922        }
18923
18924        if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
18925            clauses.push(FunctionArgumentClause::OrderBy(
18926                self.parse_comma_separated(Parser::parse_order_by_expr)?,
18927            ));
18928        }
18929
18930        if self.parse_keyword(Keyword::LIMIT) {
18931            clauses.push(FunctionArgumentClause::Limit(self.parse_expr()?));
18932        }
18933
18934        if dialect_of!(self is GenericDialect | BigQueryDialect)
18935            && self.parse_keyword(Keyword::HAVING)
18936        {
18937            let kind = match self.expect_one_of_keywords(&[Keyword::MIN, Keyword::MAX])? {
18938                Keyword::MIN => HavingBoundKind::Min,
18939                Keyword::MAX => HavingBoundKind::Max,
18940                unexpected_keyword => return Err(ParserError::ParserError(
18941                    format!("Internal parser error: unexpected keyword `{unexpected_keyword}` in having bound"),
18942                )),
18943            };
18944            clauses.push(FunctionArgumentClause::Having(HavingBound(
18945                kind,
18946                self.parse_expr()?,
18947            )))
18948        }
18949
18950        if dialect_of!(self is GenericDialect | MySqlDialect)
18951            && self.parse_keyword(Keyword::SEPARATOR)
18952        {
18953            clauses.push(FunctionArgumentClause::Separator(self.parse_value()?));
18954        }
18955
18956        if let Some(on_overflow) = self.parse_listagg_on_overflow()? {
18957            clauses.push(FunctionArgumentClause::OnOverflow(on_overflow));
18958        }
18959
18960        if let Some(null_clause) = self.parse_json_null_clause() {
18961            clauses.push(FunctionArgumentClause::JsonNullClause(null_clause));
18962        }
18963
18964        if let Some(json_returning_clause) = self.maybe_parse_json_returning_clause()? {
18965            clauses.push(FunctionArgumentClause::JsonReturningClause(
18966                json_returning_clause,
18967            ));
18968        }
18969
18970        self.expect_token(&Token::RParen)?;
18971        Ok(FunctionArgumentList {
18972            duplicate_treatment,
18973            args,
18974            clauses,
18975        })
18976    }
18977
18978    fn parse_json_null_clause(&mut self) -> Option<JsonNullClause> {
18979        if self.parse_keywords(&[Keyword::ABSENT, Keyword::ON, Keyword::NULL]) {
18980            Some(JsonNullClause::AbsentOnNull)
18981        } else if self.parse_keywords(&[Keyword::NULL, Keyword::ON, Keyword::NULL]) {
18982            Some(JsonNullClause::NullOnNull)
18983        } else {
18984            None
18985        }
18986    }
18987
18988    fn maybe_parse_json_returning_clause(
18989        &mut self,
18990    ) -> Result<Option<JsonReturningClause>, ParserError> {
18991        if self.parse_keyword(Keyword::RETURNING) {
18992            let data_type = self.parse_data_type()?;
18993            Ok(Some(JsonReturningClause { data_type }))
18994        } else {
18995            Ok(None)
18996        }
18997    }
18998
18999    fn parse_duplicate_treatment(&mut self) -> Result<Option<DuplicateTreatment>, ParserError> {
19000        let loc = self.peek_token_ref().span.start;
19001        match (
19002            self.parse_keyword(Keyword::ALL),
19003            self.parse_keyword(Keyword::DISTINCT),
19004        ) {
19005            (true, false) => Ok(Some(DuplicateTreatment::All)),
19006            (false, true) => Ok(Some(DuplicateTreatment::Distinct)),
19007            (false, false) => Ok(None),
19008            (true, true) => parser_err!("Cannot specify both ALL and DISTINCT".to_string(), loc),
19009        }
19010    }
19011
19012    /// Parse a comma-delimited list of projections after SELECT
19013    pub fn parse_select_item(&mut self) -> Result<SelectItem, ParserError> {
19014        let prefix = self
19015            .parse_one_of_keywords(
19016                self.dialect
19017                    .get_reserved_keywords_for_select_item_operator(),
19018            )
19019            .map(|keyword| Ident::new(format!("{keyword:?}")));
19020
19021        match self.parse_wildcard_expr()? {
19022            Expr::QualifiedWildcard(prefix, token) => Ok(SelectItem::QualifiedWildcard(
19023                SelectItemQualifiedWildcardKind::ObjectName(prefix),
19024                self.parse_wildcard_additional_options(token.0)?,
19025            )),
19026            Expr::Wildcard(token) => Ok(SelectItem::Wildcard(
19027                self.parse_wildcard_additional_options(token.0)?,
19028            )),
19029            Expr::Identifier(v) if v.value.to_lowercase() == "from" && v.quote_style.is_none() => {
19030                parser_err!(
19031                    format!("Expected an expression, found: {}", v),
19032                    self.peek_token_ref().span.start
19033                )
19034            }
19035            Expr::BinaryOp {
19036                left,
19037                op: BinaryOperator::Eq,
19038                right,
19039            } if self.dialect.supports_eq_alias_assignment()
19040                && matches!(left.as_ref(), Expr::Identifier(_)) =>
19041            {
19042                let Expr::Identifier(alias) = *left else {
19043                    return parser_err!(
19044                        "BUG: expected identifier expression as alias",
19045                        self.peek_token_ref().span.start
19046                    );
19047                };
19048                Ok(SelectItem::ExprWithAlias {
19049                    expr: *right,
19050                    alias,
19051                })
19052            }
19053            expr if self.dialect.supports_select_expr_star()
19054                && self.consume_tokens(&[Token::Period, Token::Mul]) =>
19055            {
19056                let wildcard_token = self.get_previous_token().clone();
19057                Ok(SelectItem::QualifiedWildcard(
19058                    SelectItemQualifiedWildcardKind::Expr(expr),
19059                    self.parse_wildcard_additional_options(wildcard_token)?,
19060                ))
19061            }
19062            expr if self.dialect.supports_select_item_multi_column_alias()
19063                && self.peek_keyword(Keyword::AS)
19064                && self.peek_nth_token(1).token == Token::LParen =>
19065            {
19066                self.expect_keyword(Keyword::AS)?;
19067                self.expect_token(&Token::LParen)?;
19068                let aliases = self.parse_comma_separated(|p| p.parse_identifier())?;
19069                self.expect_token(&Token::RParen)?;
19070                Ok(SelectItem::ExprWithAliases {
19071                    expr: maybe_prefixed_expr(expr, prefix),
19072                    aliases,
19073                })
19074            }
19075            expr => self
19076                .maybe_parse_select_item_alias()
19077                .map(|alias| match alias {
19078                    Some(alias) => SelectItem::ExprWithAlias {
19079                        expr: maybe_prefixed_expr(expr, prefix),
19080                        alias,
19081                    },
19082                    None => SelectItem::UnnamedExpr(maybe_prefixed_expr(expr, prefix)),
19083                }),
19084        }
19085    }
19086
19087    /// Parse an [`WildcardAdditionalOptions`] information for wildcard select items.
19088    ///
19089    /// If it is not possible to parse it, will return an option.
19090    pub fn parse_wildcard_additional_options(
19091        &mut self,
19092        wildcard_token: TokenWithSpan,
19093    ) -> Result<WildcardAdditionalOptions, ParserError> {
19094        let opt_ilike = if self.dialect.supports_select_wildcard_ilike() {
19095            self.parse_optional_select_item_ilike()?
19096        } else {
19097            None
19098        };
19099        let opt_exclude = if opt_ilike.is_none() && self.dialect.supports_select_wildcard_exclude()
19100        {
19101            self.parse_optional_select_item_exclude()?
19102        } else {
19103            None
19104        };
19105        let opt_except = if self.dialect.supports_select_wildcard_except() {
19106            self.parse_optional_select_item_except()?
19107        } else {
19108            None
19109        };
19110        let opt_replace = if self.dialect.supports_select_wildcard_replace() {
19111            self.parse_optional_select_item_replace()?
19112        } else {
19113            None
19114        };
19115        let opt_rename = if self.dialect.supports_select_wildcard_rename() {
19116            self.parse_optional_select_item_rename()?
19117        } else {
19118            None
19119        };
19120
19121        let opt_alias = if self.dialect.supports_select_wildcard_with_alias() {
19122            self.maybe_parse_select_item_alias()?
19123        } else {
19124            None
19125        };
19126
19127        Ok(WildcardAdditionalOptions {
19128            wildcard_token: wildcard_token.into(),
19129            opt_ilike,
19130            opt_exclude,
19131            opt_except,
19132            opt_rename,
19133            opt_replace,
19134            opt_alias,
19135        })
19136    }
19137
19138    /// Parse an [`Ilike`](IlikeSelectItem) information for wildcard select items.
19139    ///
19140    /// If it is not possible to parse it, will return an option.
19141    pub fn parse_optional_select_item_ilike(
19142        &mut self,
19143    ) -> Result<Option<IlikeSelectItem>, ParserError> {
19144        let opt_ilike = if self.parse_keyword(Keyword::ILIKE) {
19145            let next_token = self.next_token();
19146            let pattern = match next_token.token {
19147                Token::SingleQuotedString(s) => s,
19148                _ => return self.expected("ilike pattern", next_token),
19149            };
19150            Some(IlikeSelectItem { pattern })
19151        } else {
19152            None
19153        };
19154        Ok(opt_ilike)
19155    }
19156
19157    /// Parse an [`Exclude`](ExcludeSelectItem) information for wildcard select items.
19158    ///
19159    /// If it is not possible to parse it, will return an option.
19160    pub fn parse_optional_select_item_exclude(
19161        &mut self,
19162    ) -> Result<Option<ExcludeSelectItem>, ParserError> {
19163        let opt_exclude = if self.parse_keyword(Keyword::EXCLUDE) {
19164            if self.consume_token(&Token::LParen) {
19165                let columns =
19166                    self.parse_comma_separated(|parser| parser.parse_object_name(false))?;
19167                self.expect_token(&Token::RParen)?;
19168                Some(ExcludeSelectItem::Multiple(columns))
19169            } else {
19170                let column = self.parse_object_name(false)?;
19171                Some(ExcludeSelectItem::Single(column))
19172            }
19173        } else {
19174            None
19175        };
19176
19177        Ok(opt_exclude)
19178    }
19179
19180    /// Parse an [`Except`](ExceptSelectItem) information for wildcard select items.
19181    ///
19182    /// If it is not possible to parse it, will return an option.
19183    pub fn parse_optional_select_item_except(
19184        &mut self,
19185    ) -> Result<Option<ExceptSelectItem>, ParserError> {
19186        let opt_except = if self.parse_keyword(Keyword::EXCEPT) {
19187            if self.peek_token_ref().token == Token::LParen {
19188                let idents = self.parse_parenthesized_column_list(Mandatory, false)?;
19189                match &idents[..] {
19190                    [] => {
19191                        return self.expected_ref(
19192                            "at least one column should be parsed by the expect clause",
19193                            self.peek_token_ref(),
19194                        )?;
19195                    }
19196                    [first, idents @ ..] => Some(ExceptSelectItem {
19197                        first_element: first.clone(),
19198                        additional_elements: idents.to_vec(),
19199                    }),
19200                }
19201            } else {
19202                // Clickhouse allows EXCEPT column_name
19203                let ident = self.parse_identifier()?;
19204                Some(ExceptSelectItem {
19205                    first_element: ident,
19206                    additional_elements: vec![],
19207                })
19208            }
19209        } else {
19210            None
19211        };
19212
19213        Ok(opt_except)
19214    }
19215
19216    /// Parse a [`Rename`](RenameSelectItem) information for wildcard select items.
19217    pub fn parse_optional_select_item_rename(
19218        &mut self,
19219    ) -> Result<Option<RenameSelectItem>, ParserError> {
19220        let opt_rename = if self.parse_keyword(Keyword::RENAME) {
19221            if self.consume_token(&Token::LParen) {
19222                let idents =
19223                    self.parse_comma_separated(|parser| parser.parse_identifier_with_alias())?;
19224                self.expect_token(&Token::RParen)?;
19225                Some(RenameSelectItem::Multiple(idents))
19226            } else {
19227                let ident = self.parse_identifier_with_alias()?;
19228                Some(RenameSelectItem::Single(ident))
19229            }
19230        } else {
19231            None
19232        };
19233
19234        Ok(opt_rename)
19235    }
19236
19237    /// Parse a [`Replace`](ReplaceSelectItem) information for wildcard select items.
19238    pub fn parse_optional_select_item_replace(
19239        &mut self,
19240    ) -> Result<Option<ReplaceSelectItem>, ParserError> {
19241        let opt_replace = if self.parse_keyword(Keyword::REPLACE) {
19242            if self.consume_token(&Token::LParen) {
19243                let items = self.parse_comma_separated(|parser| {
19244                    Ok(Box::new(parser.parse_replace_elements()?))
19245                })?;
19246                self.expect_token(&Token::RParen)?;
19247                Some(ReplaceSelectItem { items })
19248            } else {
19249                let tok = self.next_token();
19250                return self.expected("( after REPLACE but", tok);
19251            }
19252        } else {
19253            None
19254        };
19255
19256        Ok(opt_replace)
19257    }
19258    /// Parse a single element of a `REPLACE (...)` select-item clause.
19259    pub fn parse_replace_elements(&mut self) -> Result<ReplaceSelectElement, ParserError> {
19260        let expr = self.parse_expr()?;
19261        let as_keyword = self.parse_keyword(Keyword::AS);
19262        let ident = self.parse_identifier()?;
19263        Ok(ReplaceSelectElement {
19264            expr,
19265            column_name: ident,
19266            as_keyword,
19267        })
19268    }
19269
19270    /// Parse ASC or DESC, returns an Option with true if ASC, false of DESC or `None` if none of
19271    /// them.
19272    pub fn parse_asc_desc(&mut self) -> Option<bool> {
19273        if self.parse_keyword(Keyword::ASC) {
19274            Some(true)
19275        } else if self.parse_keyword(Keyword::DESC) {
19276            Some(false)
19277        } else {
19278            None
19279        }
19280    }
19281
19282    /// Parse ASC or DESC and map to [OrderBySort].
19283    fn parse_optional_order_by_sort(&mut self) -> Option<OrderBySort> {
19284        match self.parse_asc_desc() {
19285            Some(true) => Some(OrderBySort::Asc),
19286            Some(false) => Some(OrderBySort::Desc),
19287            None => None,
19288        }
19289    }
19290
19291    /// Parse an [OrderByExpr] expression.
19292    pub fn parse_order_by_expr(&mut self) -> Result<OrderByExpr, ParserError> {
19293        self.parse_order_by_expr_inner(false)
19294            .map(|(order_by, _)| order_by)
19295    }
19296
19297    /// Parse an [IndexColumn].
19298    pub fn parse_create_index_expr(&mut self) -> Result<IndexColumn, ParserError> {
19299        self.parse_order_by_expr_inner(true)
19300            .map(|(column, operator_class)| IndexColumn {
19301                column,
19302                operator_class,
19303            })
19304    }
19305
19306    fn parse_order_by_expr_inner(
19307        &mut self,
19308        with_operator_class: bool,
19309    ) -> Result<(OrderByExpr, Option<ObjectName>), ParserError> {
19310        let expr = self.parse_expr()?;
19311
19312        let operator_class: Option<ObjectName> = if with_operator_class {
19313            // We check that if non of the following keywords are present, then we parse an
19314            // identifier as operator class.
19315            if self
19316                .peek_one_of_keywords(&[Keyword::ASC, Keyword::DESC, Keyword::NULLS, Keyword::WITH])
19317                .is_some()
19318            {
19319                None
19320            } else {
19321                self.maybe_parse(|parser| parser.parse_object_name(false))?
19322            }
19323        } else {
19324            None
19325        };
19326
19327        let options = if !with_operator_class
19328            && self.dialect.supports_order_by_using_operator()
19329            && self.parse_keyword(Keyword::USING)
19330        {
19331            let op = self.parse_order_by_using_operator()?;
19332            OrderByOptions {
19333                sort: Some(OrderBySort::Using(op)),
19334                nulls_first: self.parse_null_ordering_modifier(),
19335            }
19336        } else {
19337            self.parse_order_by_options()?
19338        };
19339
19340        let with_fill = if self.dialect.supports_with_fill()
19341            && self.parse_keywords(&[Keyword::WITH, Keyword::FILL])
19342        {
19343            Some(self.parse_with_fill()?)
19344        } else {
19345            None
19346        };
19347
19348        Ok((
19349            OrderByExpr {
19350                expr,
19351                options,
19352                with_fill,
19353            },
19354            operator_class,
19355        ))
19356    }
19357
19358    fn parse_order_by_using_operator(&mut self) -> Result<ObjectName, ParserError> {
19359        if self.parse_keyword(Keyword::OPERATOR) {
19360            self.expect_token(&Token::LParen)?;
19361            let operator_name = self.parse_operator_name()?;
19362            self.expect_token(&Token::RParen)?;
19363            return Ok(operator_name);
19364        }
19365
19366        let token = self.next_token();
19367        Ok(ObjectName::from(vec![Ident::new(token.token.to_string())]))
19368    }
19369
19370    fn parse_null_ordering_modifier(&mut self) -> Option<bool> {
19371        if self.parse_keywords(&[Keyword::NULLS, Keyword::FIRST]) {
19372            Some(true)
19373        } else if self.parse_keywords(&[Keyword::NULLS, Keyword::LAST]) {
19374            Some(false)
19375        } else {
19376            None
19377        }
19378    }
19379
19380    fn parse_order_by_options(&mut self) -> Result<OrderByOptions, ParserError> {
19381        let sort = self.parse_optional_order_by_sort();
19382        let nulls_first = self.parse_null_ordering_modifier();
19383
19384        Ok(OrderByOptions { sort, nulls_first })
19385    }
19386
19387    // Parse a WITH FILL clause (ClickHouse dialect)
19388    // that follow the WITH FILL keywords in a ORDER BY clause
19389    /// Parse a `WITH FILL` clause used in ORDER BY (ClickHouse dialect).
19390    pub fn parse_with_fill(&mut self) -> Result<WithFill, ParserError> {
19391        let from = if self.parse_keyword(Keyword::FROM) {
19392            Some(self.parse_expr()?)
19393        } else {
19394            None
19395        };
19396
19397        let to = if self.parse_keyword(Keyword::TO) {
19398            Some(self.parse_expr()?)
19399        } else {
19400            None
19401        };
19402
19403        let step = if self.parse_keyword(Keyword::STEP) {
19404            Some(self.parse_expr()?)
19405        } else {
19406            None
19407        };
19408
19409        Ok(WithFill { from, to, step })
19410    }
19411
19412    /// Parse a set of comma separated INTERPOLATE expressions (ClickHouse dialect)
19413    /// that follow the INTERPOLATE keyword in an ORDER BY clause with the WITH FILL modifier
19414    pub fn parse_interpolations(&mut self) -> Result<Option<Interpolate>, ParserError> {
19415        if !self.parse_keyword(Keyword::INTERPOLATE) {
19416            return Ok(None);
19417        }
19418
19419        if self.consume_token(&Token::LParen) {
19420            let interpolations =
19421                self.parse_comma_separated0(|p| p.parse_interpolation(), Token::RParen)?;
19422            self.expect_token(&Token::RParen)?;
19423            // INTERPOLATE () and INTERPOLATE ( ... ) variants
19424            return Ok(Some(Interpolate {
19425                exprs: Some(interpolations),
19426            }));
19427        }
19428
19429        // INTERPOLATE
19430        Ok(Some(Interpolate { exprs: None }))
19431    }
19432
19433    /// Parse a INTERPOLATE expression (ClickHouse dialect)
19434    pub fn parse_interpolation(&mut self) -> Result<InterpolateExpr, ParserError> {
19435        let column = self.parse_identifier()?;
19436        let expr = if self.parse_keyword(Keyword::AS) {
19437            Some(self.parse_expr()?)
19438        } else {
19439            None
19440        };
19441        Ok(InterpolateExpr { column, expr })
19442    }
19443
19444    /// Parse a TOP clause, MSSQL equivalent of LIMIT,
19445    /// that follows after `SELECT [DISTINCT]`.
19446    pub fn parse_top(&mut self) -> Result<Top, ParserError> {
19447        let quantity = if self.consume_token(&Token::LParen) {
19448            let quantity = self.parse_expr()?;
19449            self.expect_token(&Token::RParen)?;
19450            Some(TopQuantity::Expr(quantity))
19451        } else {
19452            let next_token = self.next_token();
19453            let quantity = match next_token.token {
19454                Token::Number(s, _) => Self::parse::<u64>(s, next_token.span.start)?,
19455                _ => self.expected("literal int", next_token)?,
19456            };
19457            Some(TopQuantity::Constant(quantity))
19458        };
19459
19460        let percent = self.parse_keyword(Keyword::PERCENT);
19461
19462        let with_ties = self.parse_keywords(&[Keyword::WITH, Keyword::TIES]);
19463
19464        Ok(Top {
19465            with_ties,
19466            percent,
19467            quantity,
19468        })
19469    }
19470
19471    /// Parse a LIMIT clause
19472    pub fn parse_limit(&mut self) -> Result<Option<Expr>, ParserError> {
19473        if self.parse_keyword(Keyword::ALL) {
19474            Ok(None)
19475        } else {
19476            Ok(Some(self.parse_expr()?))
19477        }
19478    }
19479
19480    /// Parse an OFFSET clause
19481    pub fn parse_offset(&mut self) -> Result<Offset, ParserError> {
19482        let value = self.parse_expr()?;
19483        let rows = if self.parse_keyword(Keyword::ROW) {
19484            OffsetRows::Row
19485        } else if self.parse_keyword(Keyword::ROWS) {
19486            OffsetRows::Rows
19487        } else {
19488            OffsetRows::None
19489        };
19490        Ok(Offset { value, rows })
19491    }
19492
19493    /// Parse a FETCH clause
19494    pub fn parse_fetch(&mut self) -> Result<Fetch, ParserError> {
19495        let _ = self.parse_one_of_keywords(&[Keyword::FIRST, Keyword::NEXT]);
19496
19497        let (quantity, percent) = if self
19498            .parse_one_of_keywords(&[Keyword::ROW, Keyword::ROWS])
19499            .is_some()
19500        {
19501            (None, false)
19502        } else {
19503            let quantity = Expr::Value(self.parse_value()?);
19504            let percent = self.parse_keyword(Keyword::PERCENT);
19505            let _ = self.parse_one_of_keywords(&[Keyword::ROW, Keyword::ROWS]);
19506            (Some(quantity), percent)
19507        };
19508
19509        let with_ties = if self.parse_keyword(Keyword::ONLY) {
19510            false
19511        } else {
19512            self.parse_keywords(&[Keyword::WITH, Keyword::TIES])
19513        };
19514
19515        Ok(Fetch {
19516            with_ties,
19517            percent,
19518            quantity,
19519        })
19520    }
19521
19522    /// Parse a FOR UPDATE/FOR SHARE clause
19523    pub fn parse_lock(&mut self) -> Result<LockClause, ParserError> {
19524        let lock_type = match self.expect_one_of_keywords(&[Keyword::UPDATE, Keyword::SHARE])? {
19525            Keyword::UPDATE => LockType::Update,
19526            Keyword::SHARE => LockType::Share,
19527            unexpected_keyword => return Err(ParserError::ParserError(
19528                format!("Internal parser error: expected any of {{UPDATE, SHARE}}, got {unexpected_keyword:?}"),
19529            )),
19530        };
19531        let of = if self.parse_keyword(Keyword::OF) {
19532            Some(self.parse_object_name(false)?)
19533        } else {
19534            None
19535        };
19536        let nonblock = if self.parse_keyword(Keyword::NOWAIT) {
19537            Some(NonBlock::Nowait)
19538        } else if self.parse_keywords(&[Keyword::SKIP, Keyword::LOCKED]) {
19539            Some(NonBlock::SkipLocked)
19540        } else {
19541            None
19542        };
19543        Ok(LockClause {
19544            lock_type,
19545            of,
19546            nonblock,
19547        })
19548    }
19549
19550    /// Parse a PostgreSQL `LOCK` statement.
19551    pub fn parse_lock_statement(&mut self) -> Result<Lock, ParserError> {
19552        self.expect_keyword(Keyword::LOCK)?;
19553
19554        if self.peek_keyword(Keyword::TABLES) {
19555            return self.expected_ref("TABLE or a table name", self.peek_token_ref());
19556        }
19557
19558        let _ = self.parse_keyword(Keyword::TABLE);
19559        let tables = self.parse_comma_separated(Parser::parse_lock_table_target)?;
19560        let lock_mode = if self.parse_keyword(Keyword::IN) {
19561            let lock_mode = self.parse_lock_table_mode()?;
19562            self.expect_keyword(Keyword::MODE)?;
19563            Some(lock_mode)
19564        } else {
19565            None
19566        };
19567        let nowait = self.parse_keyword(Keyword::NOWAIT);
19568
19569        Ok(Lock {
19570            tables,
19571            lock_mode,
19572            nowait,
19573        })
19574    }
19575
19576    fn parse_lock_table_target(&mut self) -> Result<LockTableTarget, ParserError> {
19577        let only = self.parse_keyword(Keyword::ONLY);
19578        let name = self.parse_object_name(false)?;
19579        let has_asterisk = self.consume_token(&Token::Mul);
19580
19581        Ok(LockTableTarget {
19582            name,
19583            only,
19584            has_asterisk,
19585        })
19586    }
19587
19588    fn parse_lock_table_mode(&mut self) -> Result<LockTableMode, ParserError> {
19589        if self.parse_keywords(&[Keyword::ACCESS, Keyword::SHARE]) {
19590            Ok(LockTableMode::AccessShare)
19591        } else if self.parse_keywords(&[Keyword::ACCESS, Keyword::EXCLUSIVE]) {
19592            Ok(LockTableMode::AccessExclusive)
19593        } else if self.parse_keywords(&[Keyword::ROW, Keyword::SHARE]) {
19594            Ok(LockTableMode::RowShare)
19595        } else if self.parse_keywords(&[Keyword::ROW, Keyword::EXCLUSIVE]) {
19596            Ok(LockTableMode::RowExclusive)
19597        } else if self.parse_keywords(&[Keyword::SHARE, Keyword::UPDATE, Keyword::EXCLUSIVE]) {
19598            Ok(LockTableMode::ShareUpdateExclusive)
19599        } else if self.parse_keywords(&[Keyword::SHARE, Keyword::ROW, Keyword::EXCLUSIVE]) {
19600            Ok(LockTableMode::ShareRowExclusive)
19601        } else if self.parse_keyword(Keyword::SHARE) {
19602            Ok(LockTableMode::Share)
19603        } else if self.parse_keyword(Keyword::EXCLUSIVE) {
19604            Ok(LockTableMode::Exclusive)
19605        } else {
19606            self.expected_ref("a PostgreSQL LOCK TABLE mode", self.peek_token_ref())
19607        }
19608    }
19609
19610    /// Parse a VALUES clause
19611    pub fn parse_values(
19612        &mut self,
19613        allow_empty: bool,
19614        value_keyword: bool,
19615    ) -> Result<Values, ParserError> {
19616        let mut explicit_row = false;
19617
19618        let rows = self.parse_comma_separated(|parser| {
19619            if parser.parse_keyword(Keyword::ROW) {
19620                explicit_row = true;
19621            }
19622            Ok(Parens {
19623                opening_token: parser.expect_token(&Token::LParen)?.into(),
19624                content: if allow_empty && parser.peek_token_ref().token == Token::RParen {
19625                    vec![]
19626                } else {
19627                    parser.parse_comma_separated(Parser::parse_expr)?
19628                },
19629                closing_token: parser.expect_token(&Token::RParen)?.into(),
19630            })
19631        })?;
19632        Ok(Values {
19633            explicit_row,
19634            rows,
19635            value_keyword,
19636        })
19637    }
19638
19639    /// Parse a 'START TRANSACTION' statement
19640    pub fn parse_start_transaction(&mut self) -> Result<Statement, ParserError> {
19641        self.expect_keyword_is(Keyword::TRANSACTION)?;
19642        Ok(Statement::StartTransaction {
19643            modes: self.parse_transaction_modes()?,
19644            begin: false,
19645            transaction: Some(BeginTransactionKind::Transaction),
19646            modifier: None,
19647            statements: vec![],
19648            exception: None,
19649            has_end_keyword: false,
19650        })
19651    }
19652
19653    /// Parse a transaction modifier keyword that can follow a `BEGIN` statement.
19654    pub(crate) fn parse_transaction_modifier(&mut self) -> Option<TransactionModifier> {
19655        if !self.dialect.supports_start_transaction_modifier() {
19656            None
19657        } else if self.parse_keyword(Keyword::DEFERRED) {
19658            Some(TransactionModifier::Deferred)
19659        } else if self.parse_keyword(Keyword::IMMEDIATE) {
19660            Some(TransactionModifier::Immediate)
19661        } else if self.parse_keyword(Keyword::EXCLUSIVE) {
19662            Some(TransactionModifier::Exclusive)
19663        } else if self.parse_keyword(Keyword::TRY) {
19664            Some(TransactionModifier::Try)
19665        } else if self.parse_keyword(Keyword::CATCH) {
19666            Some(TransactionModifier::Catch)
19667        } else {
19668            None
19669        }
19670    }
19671
19672    /// Parse a 'BEGIN' statement
19673    pub fn parse_begin(&mut self) -> Result<Statement, ParserError> {
19674        let modifier = self.parse_transaction_modifier();
19675        let transaction =
19676            match self.parse_one_of_keywords(&[Keyword::TRANSACTION, Keyword::WORK, Keyword::TRAN])
19677            {
19678                Some(Keyword::TRANSACTION) => Some(BeginTransactionKind::Transaction),
19679                Some(Keyword::WORK) => Some(BeginTransactionKind::Work),
19680                Some(Keyword::TRAN) => Some(BeginTransactionKind::Tran),
19681                _ => None,
19682            };
19683        Ok(Statement::StartTransaction {
19684            modes: self.parse_transaction_modes()?,
19685            begin: true,
19686            transaction,
19687            modifier,
19688            statements: vec![],
19689            exception: None,
19690            has_end_keyword: false,
19691        })
19692    }
19693
19694    /// Parse a 'BEGIN ... EXCEPTION ... END' block
19695    pub fn parse_begin_exception_end(&mut self) -> Result<Statement, ParserError> {
19696        let statements = self.parse_statement_list(&[Keyword::EXCEPTION, Keyword::END])?;
19697
19698        let exception = if self.parse_keyword(Keyword::EXCEPTION) {
19699            let mut when = Vec::new();
19700
19701            // We can have multiple `WHEN` arms so we consume all cases until `END`
19702            while !self.peek_keyword(Keyword::END) {
19703                self.expect_keyword(Keyword::WHEN)?;
19704
19705                // Each `WHEN` case can have one or more conditions, e.g.
19706                // WHEN EXCEPTION_1 [OR EXCEPTION_2] THEN
19707                // So we parse identifiers until the `THEN` keyword.
19708                let mut idents = Vec::new();
19709
19710                while !self.parse_keyword(Keyword::THEN) {
19711                    let ident = self.parse_identifier()?;
19712                    idents.push(ident);
19713
19714                    self.maybe_parse(|p| p.expect_keyword(Keyword::OR))?;
19715                }
19716
19717                let statements = self.parse_statement_list(&[Keyword::WHEN, Keyword::END])?;
19718
19719                when.push(ExceptionWhen { idents, statements });
19720            }
19721
19722            Some(when)
19723        } else {
19724            None
19725        };
19726
19727        self.expect_keyword(Keyword::END)?;
19728
19729        Ok(Statement::StartTransaction {
19730            begin: true,
19731            statements,
19732            exception,
19733            has_end_keyword: true,
19734            transaction: None,
19735            modifier: None,
19736            modes: Default::default(),
19737        })
19738    }
19739
19740    /// Parse an 'END' statement
19741    pub fn parse_end(&mut self) -> Result<Statement, ParserError> {
19742        let modifier = if !self.dialect.supports_end_transaction_modifier() {
19743            None
19744        } else if self.parse_keyword(Keyword::TRY) {
19745            Some(TransactionModifier::Try)
19746        } else if self.parse_keyword(Keyword::CATCH) {
19747            Some(TransactionModifier::Catch)
19748        } else {
19749            None
19750        };
19751        Ok(Statement::Commit {
19752            chain: self.parse_commit_rollback_chain()?,
19753            end: true,
19754            modifier,
19755        })
19756    }
19757
19758    /// Parse a list of transaction modes
19759    pub fn parse_transaction_modes(&mut self) -> Result<Vec<TransactionMode>, ParserError> {
19760        let mut modes = vec![];
19761        let mut required = false;
19762        loop {
19763            let mode = if self.parse_keywords(&[Keyword::ISOLATION, Keyword::LEVEL]) {
19764                let iso_level = if self.parse_keywords(&[Keyword::READ, Keyword::UNCOMMITTED]) {
19765                    TransactionIsolationLevel::ReadUncommitted
19766                } else if self.parse_keywords(&[Keyword::READ, Keyword::COMMITTED]) {
19767                    TransactionIsolationLevel::ReadCommitted
19768                } else if self.parse_keywords(&[Keyword::REPEATABLE, Keyword::READ]) {
19769                    TransactionIsolationLevel::RepeatableRead
19770                } else if self.parse_keyword(Keyword::SERIALIZABLE) {
19771                    TransactionIsolationLevel::Serializable
19772                } else if self.parse_keyword(Keyword::SNAPSHOT) {
19773                    TransactionIsolationLevel::Snapshot
19774                } else {
19775                    self.expected_ref("isolation level", self.peek_token_ref())?
19776                };
19777                TransactionMode::IsolationLevel(iso_level)
19778            } else if self.parse_keywords(&[Keyword::READ, Keyword::ONLY]) {
19779                TransactionMode::AccessMode(TransactionAccessMode::ReadOnly)
19780            } else if self.parse_keywords(&[Keyword::READ, Keyword::WRITE]) {
19781                TransactionMode::AccessMode(TransactionAccessMode::ReadWrite)
19782            } else if required {
19783                self.expected_ref("transaction mode", self.peek_token_ref())?
19784            } else {
19785                break;
19786            };
19787            modes.push(mode);
19788            // ANSI requires a comma after each transaction mode, but
19789            // PostgreSQL, for historical reasons, does not. We follow
19790            // PostgreSQL in making the comma optional, since that is strictly
19791            // more general.
19792            required = self.consume_token(&Token::Comma);
19793        }
19794        Ok(modes)
19795    }
19796
19797    /// Parse a 'COMMIT' statement
19798    pub fn parse_commit(&mut self) -> Result<Statement, ParserError> {
19799        Ok(Statement::Commit {
19800            chain: self.parse_commit_rollback_chain()?,
19801            end: false,
19802            modifier: None,
19803        })
19804    }
19805
19806    /// Parse a 'ROLLBACK' statement
19807    pub fn parse_rollback(&mut self) -> Result<Statement, ParserError> {
19808        let chain = self.parse_commit_rollback_chain()?;
19809        let savepoint = self.parse_rollback_savepoint()?;
19810
19811        Ok(Statement::Rollback { chain, savepoint })
19812    }
19813
19814    /// Parse an 'ABORT' statement
19815    ///
19816    /// ```sql
19817    /// ABORT [ TRANSACTION | WORK ] [ AND [ NO ] CHAIN ]
19818    /// ```
19819    pub fn parse_abort(&mut self) -> Result<Statement, ParserError> {
19820        let chain = self.parse_commit_rollback_chain()?;
19821
19822        Ok(Statement::Rollback {
19823            chain,
19824            savepoint: None,
19825        })
19826    }
19827
19828    /// Parse an optional `AND [NO] CHAIN` clause for `COMMIT` and `ROLLBACK` statements
19829    pub fn parse_commit_rollback_chain(&mut self) -> Result<bool, ParserError> {
19830        let _ = self.parse_one_of_keywords(&[Keyword::TRANSACTION, Keyword::WORK, Keyword::TRAN]);
19831        if self.parse_keyword(Keyword::AND) {
19832            let chain = !self.parse_keyword(Keyword::NO);
19833            self.expect_keyword_is(Keyword::CHAIN)?;
19834            Ok(chain)
19835        } else {
19836            Ok(false)
19837        }
19838    }
19839
19840    /// Parse an optional 'TO SAVEPOINT savepoint_name' clause for ROLLBACK statements
19841    pub fn parse_rollback_savepoint(&mut self) -> Result<Option<Ident>, ParserError> {
19842        if self.parse_keyword(Keyword::TO) {
19843            let _ = self.parse_keyword(Keyword::SAVEPOINT);
19844            let savepoint = self.parse_identifier()?;
19845
19846            Ok(Some(savepoint))
19847        } else {
19848            Ok(None)
19849        }
19850    }
19851
19852    /// Parse a 'RAISERROR' statement
19853    pub fn parse_raiserror(&mut self) -> Result<Statement, ParserError> {
19854        self.expect_token(&Token::LParen)?;
19855        let message = Box::new(self.parse_expr()?);
19856        self.expect_token(&Token::Comma)?;
19857        let severity = Box::new(self.parse_expr()?);
19858        self.expect_token(&Token::Comma)?;
19859        let state = Box::new(self.parse_expr()?);
19860        let arguments = if self.consume_token(&Token::Comma) {
19861            self.parse_comma_separated(Parser::parse_expr)?
19862        } else {
19863            vec![]
19864        };
19865        self.expect_token(&Token::RParen)?;
19866        let options = if self.parse_keyword(Keyword::WITH) {
19867            self.parse_comma_separated(Parser::parse_raiserror_option)?
19868        } else {
19869            vec![]
19870        };
19871        Ok(Statement::RaisError {
19872            message,
19873            severity,
19874            state,
19875            arguments,
19876            options,
19877        })
19878    }
19879
19880    /// Parse a single `RAISERROR` option
19881    pub fn parse_raiserror_option(&mut self) -> Result<RaisErrorOption, ParserError> {
19882        match self.expect_one_of_keywords(&[Keyword::LOG, Keyword::NOWAIT, Keyword::SETERROR])? {
19883            Keyword::LOG => Ok(RaisErrorOption::Log),
19884            Keyword::NOWAIT => Ok(RaisErrorOption::NoWait),
19885            Keyword::SETERROR => Ok(RaisErrorOption::SetError),
19886            _ => self.expected_ref(
19887                "LOG, NOWAIT OR SETERROR raiserror option",
19888                self.peek_token_ref(),
19889            ),
19890        }
19891    }
19892
19893    /// Parse a MSSQL `THROW` statement.
19894    ///
19895    /// See [Statement::Throw]
19896    pub fn parse_throw(&mut self) -> Result<ThrowStatement, ParserError> {
19897        self.expect_keyword_is(Keyword::THROW)?;
19898
19899        let error_number = self.maybe_parse(|p| p.parse_expr().map(Box::new))?;
19900        let (message, state) = if error_number.is_some() {
19901            self.expect_token(&Token::Comma)?;
19902            let message = Box::new(self.parse_expr()?);
19903            self.expect_token(&Token::Comma)?;
19904            let state = Box::new(self.parse_expr()?);
19905            (Some(message), Some(state))
19906        } else {
19907            (None, None)
19908        };
19909
19910        Ok(ThrowStatement {
19911            error_number,
19912            message,
19913            state,
19914        })
19915    }
19916
19917    /// Parse a SQL `DEALLOCATE` statement
19918    pub fn parse_deallocate(&mut self) -> Result<Statement, ParserError> {
19919        let prepare = self.parse_keyword(Keyword::PREPARE);
19920        let name = self.parse_identifier()?;
19921        Ok(Statement::Deallocate { name, prepare })
19922    }
19923
19924    /// Parse a SQL `EXECUTE` statement
19925    pub fn parse_execute(&mut self) -> Result<Statement, ParserError> {
19926        let immediate =
19927            self.dialect.supports_execute_immediate() && self.parse_keyword(Keyword::IMMEDIATE);
19928
19929        // When `EXEC` is immediately followed by `(`, the content is a dynamic-SQL
19930        // expression — e.g. `EXEC (@sql)`, `EXEC ('SELECT ...')`, or
19931        // `EXEC ('SELECT ... FROM ' + @tbl + ' WHERE ...')`.
19932        // Skip name parsing; the expression ends up in `parameters` via the
19933        // `has_parentheses` path below, consistent with `EXECUTE IMMEDIATE <expr>`.
19934        let name = if immediate || matches!(self.peek_token_ref().token, Token::LParen) {
19935            None
19936        } else {
19937            Some(self.parse_object_name(false)?)
19938        };
19939
19940        let has_parentheses = self.consume_token(&Token::LParen);
19941
19942        let end_kws = &[Keyword::USING, Keyword::OUTPUT, Keyword::DEFAULT];
19943        let end_token = match (has_parentheses, self.peek_token().token) {
19944            (true, _) => Token::RParen,
19945            (false, Token::EOF) => Token::EOF,
19946            (false, Token::Word(w)) if end_kws.contains(&w.keyword) => Token::Word(w),
19947            (false, _) => Token::SemiColon,
19948        };
19949
19950        let parameters = self.parse_comma_separated0(Parser::parse_expr, end_token)?;
19951
19952        if has_parentheses {
19953            self.expect_token(&Token::RParen)?;
19954        }
19955
19956        let into = if self.parse_keyword(Keyword::INTO) {
19957            self.parse_comma_separated(Self::parse_identifier)?
19958        } else {
19959            vec![]
19960        };
19961
19962        let using = if self.parse_keyword(Keyword::USING) {
19963            self.parse_comma_separated(Self::parse_expr_with_alias)?
19964        } else {
19965            vec![]
19966        };
19967
19968        let output = self.parse_keyword(Keyword::OUTPUT);
19969
19970        let default = self.parse_keyword(Keyword::DEFAULT);
19971
19972        Ok(Statement::Execute {
19973            immediate,
19974            name,
19975            parameters,
19976            has_parentheses,
19977            into,
19978            using,
19979            output,
19980            default,
19981        })
19982    }
19983
19984    /// Parse a SQL `PREPARE` statement
19985    pub fn parse_prepare(&mut self) -> Result<Statement, ParserError> {
19986        let name = self.parse_identifier()?;
19987
19988        let mut data_types = vec![];
19989        if self.consume_token(&Token::LParen) {
19990            data_types = self.parse_comma_separated(Parser::parse_data_type)?;
19991            self.expect_token(&Token::RParen)?;
19992        }
19993
19994        self.expect_keyword_is(Keyword::AS)?;
19995        let statement = Box::new(self.parse_statement()?);
19996        Ok(Statement::Prepare {
19997            name,
19998            data_types,
19999            statement,
20000        })
20001    }
20002
20003    /// Parse a SQL `UNLOAD` statement
20004    pub fn parse_unload(&mut self) -> Result<Statement, ParserError> {
20005        self.expect_keyword(Keyword::UNLOAD)?;
20006        self.expect_token(&Token::LParen)?;
20007        let (query, query_text) =
20008            if matches!(self.peek_token_ref().token, Token::SingleQuotedString(_)) {
20009                (None, Some(self.parse_literal_string()?))
20010            } else {
20011                (Some(self.parse_query()?), None)
20012            };
20013        self.expect_token(&Token::RParen)?;
20014
20015        self.expect_keyword_is(Keyword::TO)?;
20016        let to = self.parse_identifier()?;
20017        let auth = if self.parse_keyword(Keyword::IAM_ROLE) {
20018            Some(self.parse_iam_role_kind()?)
20019        } else {
20020            None
20021        };
20022        let with = self.parse_options(Keyword::WITH)?;
20023        let mut options = vec![];
20024        while let Some(opt) = self.maybe_parse(|parser| parser.parse_copy_legacy_option())? {
20025            options.push(opt);
20026        }
20027        Ok(Statement::Unload {
20028            query,
20029            query_text,
20030            to,
20031            auth,
20032            with,
20033            options,
20034        })
20035    }
20036
20037    fn parse_select_into(&mut self) -> Result<SelectInto, ParserError> {
20038        let temporary = self
20039            .parse_one_of_keywords(&[Keyword::TEMP, Keyword::TEMPORARY])
20040            .is_some();
20041        let unlogged = self.parse_keyword(Keyword::UNLOGGED);
20042        let table = self.parse_keyword(Keyword::TABLE);
20043        let targets = self.parse_comma_separated(Parser::parse_expr)?;
20044
20045        Ok(SelectInto {
20046            temporary,
20047            unlogged,
20048            table,
20049            targets,
20050        })
20051    }
20052
20053    fn parse_pragma_value(&mut self) -> Result<ValueWithSpan, ParserError> {
20054        let v = self.parse_value()?;
20055        match &v.value {
20056            Value::SingleQuotedString(_) => Ok(v),
20057            Value::DoubleQuotedString(_) => Ok(v),
20058            Value::Number(_, _) => Ok(v),
20059            Value::Placeholder(_) => Ok(v),
20060            _ => {
20061                self.prev_token();
20062                self.expected_ref("number or string or ? placeholder", self.peek_token_ref())
20063            }
20064        }
20065    }
20066
20067    /// PRAGMA [schema-name '.'] pragma-name [('=' pragma-value) | '(' pragma-value ')']
20068    pub fn parse_pragma(&mut self) -> Result<Statement, ParserError> {
20069        let name = self.parse_object_name(false)?;
20070        if self.consume_token(&Token::LParen) {
20071            let value = self.parse_pragma_value()?;
20072            self.expect_token(&Token::RParen)?;
20073            Ok(Statement::Pragma {
20074                name,
20075                value: Some(value),
20076                is_eq: false,
20077            })
20078        } else if self.consume_token(&Token::Eq) {
20079            Ok(Statement::Pragma {
20080                name,
20081                value: Some(self.parse_pragma_value()?),
20082                is_eq: true,
20083            })
20084        } else {
20085            Ok(Statement::Pragma {
20086                name,
20087                value: None,
20088                is_eq: false,
20089            })
20090        }
20091    }
20092
20093    /// `INSTALL [extension_name]`
20094    pub fn parse_install(&mut self) -> Result<Statement, ParserError> {
20095        let extension_name = self.parse_identifier()?;
20096
20097        Ok(Statement::Install { extension_name })
20098    }
20099
20100    /// Parse a SQL LOAD statement
20101    pub fn parse_load(&mut self) -> Result<Statement, ParserError> {
20102        if self.dialect.supports_load_extension() {
20103            let extension_name = self.parse_identifier()?;
20104            Ok(Statement::Load { extension_name })
20105        } else if self.parse_keyword(Keyword::DATA) && self.dialect.supports_load_data() {
20106            let local = self.parse_one_of_keywords(&[Keyword::LOCAL]).is_some();
20107            self.expect_keyword_is(Keyword::INPATH)?;
20108            let inpath = self.parse_literal_string()?;
20109            let overwrite = self.parse_one_of_keywords(&[Keyword::OVERWRITE]).is_some();
20110            self.expect_keyword_is(Keyword::INTO)?;
20111            self.expect_keyword_is(Keyword::TABLE)?;
20112            let table_name = self.parse_object_name(false)?;
20113            let partitioned = self.parse_insert_partition()?;
20114            let table_format = self.parse_load_data_table_format()?;
20115            Ok(Statement::LoadData {
20116                local,
20117                inpath,
20118                overwrite,
20119                table_name,
20120                partitioned,
20121                table_format,
20122            })
20123        } else {
20124            self.expected_ref(
20125                "`DATA` or an extension name after `LOAD`",
20126                self.peek_token_ref(),
20127            )
20128        }
20129    }
20130
20131    /// ClickHouse:
20132    /// ```sql
20133    /// OPTIMIZE TABLE [db.]name [ON CLUSTER cluster] [PARTITION partition | PARTITION ID 'partition_id'] [FINAL] [DEDUPLICATE [BY expression]]
20134    /// ```
20135    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/optimize)
20136    ///
20137    /// Databricks:
20138    /// ```sql
20139    /// OPTIMIZE table_name [WHERE predicate] [ZORDER BY (col_name1 [, ...])]
20140    /// ```
20141    /// [Databricks](https://docs.databricks.com/en/sql/language-manual/delta-optimize.html)
20142    pub fn parse_optimize_table(&mut self) -> Result<Statement, ParserError> {
20143        let has_table_keyword = self.parse_keyword(Keyword::TABLE);
20144
20145        let name = self.parse_object_name(false)?;
20146
20147        // ClickHouse-specific options
20148        let on_cluster = self.parse_optional_on_cluster()?;
20149
20150        let partition = if self.parse_keyword(Keyword::PARTITION) {
20151            if self.parse_keyword(Keyword::ID) {
20152                Some(Partition::Identifier(self.parse_identifier()?))
20153            } else {
20154                Some(Partition::Expr(self.parse_expr()?))
20155            }
20156        } else {
20157            None
20158        };
20159
20160        let include_final = self.parse_keyword(Keyword::FINAL);
20161
20162        let deduplicate = if self.parse_keyword(Keyword::DEDUPLICATE) {
20163            if self.parse_keyword(Keyword::BY) {
20164                Some(Deduplicate::ByExpression(self.parse_expr()?))
20165            } else {
20166                Some(Deduplicate::All)
20167            }
20168        } else {
20169            None
20170        };
20171
20172        // Databricks-specific options
20173        let predicate = if self.parse_keyword(Keyword::WHERE) {
20174            Some(self.parse_expr()?)
20175        } else {
20176            None
20177        };
20178
20179        let zorder = if self.parse_keywords(&[Keyword::ZORDER, Keyword::BY]) {
20180            self.expect_token(&Token::LParen)?;
20181            let columns = self.parse_comma_separated(|p| p.parse_expr())?;
20182            self.expect_token(&Token::RParen)?;
20183            Some(columns)
20184        } else {
20185            None
20186        };
20187
20188        Ok(Statement::OptimizeTable {
20189            name,
20190            has_table_keyword,
20191            on_cluster,
20192            partition,
20193            include_final,
20194            deduplicate,
20195            predicate,
20196            zorder,
20197        })
20198    }
20199
20200    /// ```sql
20201    /// CREATE [ { TEMPORARY | TEMP } ] SEQUENCE [ IF NOT EXISTS ] <sequence_name>
20202    /// ```
20203    ///
20204    /// See [Postgres docs](https://www.postgresql.org/docs/current/sql-createsequence.html) for more details.
20205    pub fn parse_create_sequence(&mut self, temporary: bool) -> Result<Statement, ParserError> {
20206        //[ IF NOT EXISTS ]
20207        let if_not_exists = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
20208        //name
20209        let name = self.parse_object_name(false)?;
20210        //[ AS data_type ]
20211        let mut data_type: Option<DataType> = None;
20212        if self.parse_keywords(&[Keyword::AS]) {
20213            data_type = Some(self.parse_data_type()?)
20214        }
20215        let sequence_options = self.parse_create_sequence_options()?;
20216        // [ OWNED BY { table_name.column_name | NONE } ]
20217        let owned_by = if self.parse_keywords(&[Keyword::OWNED, Keyword::BY]) {
20218            if self.parse_keywords(&[Keyword::NONE]) {
20219                Some(ObjectName::from(vec![Ident::new("NONE")]))
20220            } else {
20221                Some(self.parse_object_name(false)?)
20222            }
20223        } else {
20224            None
20225        };
20226        Ok(Statement::CreateSequence {
20227            temporary,
20228            if_not_exists,
20229            name,
20230            data_type,
20231            sequence_options,
20232            owned_by,
20233        })
20234    }
20235
20236    fn parse_create_sequence_options(&mut self) -> Result<Vec<SequenceOptions>, ParserError> {
20237        let mut sequence_options = vec![];
20238        //[ INCREMENT [ BY ] increment ]
20239        if self.parse_keywords(&[Keyword::INCREMENT]) {
20240            if self.parse_keywords(&[Keyword::BY]) {
20241                sequence_options.push(SequenceOptions::IncrementBy(self.parse_number()?, true));
20242            } else {
20243                sequence_options.push(SequenceOptions::IncrementBy(self.parse_number()?, false));
20244            }
20245        }
20246        //[ MINVALUE minvalue | NO MINVALUE ]
20247        if self.parse_keyword(Keyword::MINVALUE) {
20248            sequence_options.push(SequenceOptions::MinValue(Some(self.parse_number()?)));
20249        } else if self.parse_keywords(&[Keyword::NO, Keyword::MINVALUE]) {
20250            sequence_options.push(SequenceOptions::MinValue(None));
20251        }
20252        //[ MAXVALUE maxvalue | NO MAXVALUE ]
20253        if self.parse_keywords(&[Keyword::MAXVALUE]) {
20254            sequence_options.push(SequenceOptions::MaxValue(Some(self.parse_number()?)));
20255        } else if self.parse_keywords(&[Keyword::NO, Keyword::MAXVALUE]) {
20256            sequence_options.push(SequenceOptions::MaxValue(None));
20257        }
20258
20259        //[ START [ WITH ] start ]
20260        if self.parse_keywords(&[Keyword::START]) {
20261            if self.parse_keywords(&[Keyword::WITH]) {
20262                sequence_options.push(SequenceOptions::StartWith(self.parse_number()?, true));
20263            } else {
20264                sequence_options.push(SequenceOptions::StartWith(self.parse_number()?, false));
20265            }
20266        }
20267        //[ CACHE cache ]
20268        if self.parse_keywords(&[Keyword::CACHE]) {
20269            sequence_options.push(SequenceOptions::Cache(self.parse_number()?));
20270        }
20271        // [ [ NO ] CYCLE ]
20272        if self.parse_keywords(&[Keyword::NO, Keyword::CYCLE]) {
20273            sequence_options.push(SequenceOptions::Cycle(true));
20274        } else if self.parse_keywords(&[Keyword::CYCLE]) {
20275            sequence_options.push(SequenceOptions::Cycle(false));
20276        }
20277
20278        Ok(sequence_options)
20279    }
20280
20281    ///   Parse a `CREATE SERVER` statement.
20282    ///
20283    ///  See [Statement::CreateServer]
20284    pub fn parse_pg_create_server(&mut self) -> Result<Statement, ParserError> {
20285        let ine = self.parse_keywords(&[Keyword::IF, Keyword::NOT, Keyword::EXISTS]);
20286        let name = self.parse_object_name(false)?;
20287
20288        let server_type = if self.parse_keyword(Keyword::TYPE) {
20289            Some(self.parse_identifier()?)
20290        } else {
20291            None
20292        };
20293
20294        let version = if self.parse_keyword(Keyword::VERSION) {
20295            Some(self.parse_identifier()?)
20296        } else {
20297            None
20298        };
20299
20300        self.expect_keywords(&[Keyword::FOREIGN, Keyword::DATA, Keyword::WRAPPER])?;
20301        let foreign_data_wrapper = self.parse_object_name(false)?;
20302
20303        let mut options = None;
20304        if self.parse_keyword(Keyword::OPTIONS) {
20305            self.expect_token(&Token::LParen)?;
20306            options = Some(self.parse_comma_separated(|p| {
20307                let key = p.parse_identifier()?;
20308                let value = p.parse_identifier()?;
20309                Ok(CreateServerOption { key, value })
20310            })?);
20311            self.expect_token(&Token::RParen)?;
20312        }
20313
20314        Ok(Statement::CreateServer(CreateServerStatement {
20315            name,
20316            if_not_exists: ine,
20317            server_type,
20318            version,
20319            foreign_data_wrapper,
20320            options,
20321        }))
20322    }
20323
20324    /// The index of the first unprocessed token.
20325    pub fn index(&self) -> usize {
20326        self.index
20327    }
20328
20329    /// Parse a named window definition.
20330    pub fn parse_named_window(&mut self) -> Result<NamedWindowDefinition, ParserError> {
20331        let ident = self.parse_identifier()?;
20332        self.expect_keyword_is(Keyword::AS)?;
20333
20334        let window_expr = if self.consume_token(&Token::LParen) {
20335            NamedWindowExpr::WindowSpec(self.parse_window_spec()?)
20336        } else if self.dialect.supports_window_clause_named_window_reference() {
20337            NamedWindowExpr::NamedWindow(self.parse_identifier()?)
20338        } else {
20339            return self.expected_ref("(", self.peek_token_ref());
20340        };
20341
20342        Ok(NamedWindowDefinition(ident, window_expr))
20343    }
20344
20345    /// Parse `CREATE PROCEDURE` statement.
20346    pub fn parse_create_procedure(&mut self, or_alter: bool) -> Result<Statement, ParserError> {
20347        let name = self.parse_object_name(false)?;
20348        let params = self.parse_optional_procedure_parameters()?;
20349
20350        let language = if self.parse_keyword(Keyword::LANGUAGE) {
20351            Some(self.parse_identifier()?)
20352        } else {
20353            None
20354        };
20355
20356        self.expect_keyword_is(Keyword::AS)?;
20357
20358        let body = self.parse_conditional_statements(&[Keyword::END])?;
20359
20360        Ok(Statement::CreateProcedure {
20361            name,
20362            or_alter,
20363            params,
20364            language,
20365            body,
20366        })
20367    }
20368
20369    /// Parse a window specification.
20370    pub fn parse_window_spec(&mut self) -> Result<WindowSpec, ParserError> {
20371        let window_name = match &self.peek_token_ref().token {
20372            Token::Word(word) if word.keyword == Keyword::NoKeyword => {
20373                self.parse_optional_ident()?
20374            }
20375            _ => None,
20376        };
20377
20378        let partition_by = if self.parse_keywords(&[Keyword::PARTITION, Keyword::BY]) {
20379            self.parse_comma_separated(Parser::parse_expr)?
20380        } else {
20381            vec![]
20382        };
20383        let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
20384            self.parse_comma_separated(Parser::parse_order_by_expr)?
20385        } else {
20386            vec![]
20387        };
20388
20389        let window_frame = if !self.consume_token(&Token::RParen) {
20390            let window_frame = self.parse_window_frame()?;
20391            self.expect_token(&Token::RParen)?;
20392            Some(window_frame)
20393        } else {
20394            None
20395        };
20396        Ok(WindowSpec {
20397            window_name,
20398            partition_by,
20399            order_by,
20400            window_frame,
20401        })
20402    }
20403
20404    /// Parse `CREATE TYPE` statement.
20405    pub fn parse_create_type(&mut self) -> Result<Statement, ParserError> {
20406        let name = self.parse_object_name(false)?;
20407
20408        // Check if we have AS keyword
20409        let has_as = self.parse_keyword(Keyword::AS);
20410
20411        if !has_as {
20412            // Two cases: CREATE TYPE name; or CREATE TYPE name (options);
20413            if self.consume_token(&Token::LParen) {
20414                // CREATE TYPE name (options) - SQL definition without AS
20415                let options = self.parse_create_type_sql_definition_options()?;
20416                self.expect_token(&Token::RParen)?;
20417                return Ok(Statement::CreateType {
20418                    name,
20419                    representation: Some(UserDefinedTypeRepresentation::SqlDefinition { options }),
20420                });
20421            }
20422
20423            // CREATE TYPE name; - no representation
20424            return Ok(Statement::CreateType {
20425                name,
20426                representation: None,
20427            });
20428        }
20429
20430        // We have AS keyword
20431        if self.parse_keyword(Keyword::ENUM) {
20432            // CREATE TYPE name AS ENUM (labels)
20433            self.parse_create_type_enum(name)
20434        } else if self.parse_keyword(Keyword::RANGE) {
20435            // CREATE TYPE name AS RANGE (options)
20436            self.parse_create_type_range(name)
20437        } else if self.consume_token(&Token::LParen) {
20438            // CREATE TYPE name AS (attributes) - Composite
20439            self.parse_create_type_composite(name)
20440        } else {
20441            self.expected_ref("ENUM, RANGE, or '(' after AS", self.peek_token_ref())
20442        }
20443    }
20444
20445    /// Parse remainder of `CREATE TYPE AS (attributes)` statement (composite type)
20446    ///
20447    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtype.html)
20448    fn parse_create_type_composite(&mut self, name: ObjectName) -> Result<Statement, ParserError> {
20449        if self.consume_token(&Token::RParen) {
20450            // Empty composite type
20451            return Ok(Statement::CreateType {
20452                name,
20453                representation: Some(UserDefinedTypeRepresentation::Composite {
20454                    attributes: vec![],
20455                }),
20456            });
20457        }
20458
20459        let mut attributes = vec![];
20460        loop {
20461            let attr_name = self.parse_identifier()?;
20462            let attr_data_type = self.parse_data_type()?;
20463            let attr_collation = if self.parse_keyword(Keyword::COLLATE) {
20464                Some(self.parse_object_name(false)?)
20465            } else {
20466                None
20467            };
20468            attributes.push(UserDefinedTypeCompositeAttributeDef {
20469                name: attr_name,
20470                data_type: attr_data_type,
20471                collation: attr_collation,
20472            });
20473
20474            if !self.consume_token(&Token::Comma) {
20475                break;
20476            }
20477        }
20478        self.expect_token(&Token::RParen)?;
20479
20480        Ok(Statement::CreateType {
20481            name,
20482            representation: Some(UserDefinedTypeRepresentation::Composite { attributes }),
20483        })
20484    }
20485
20486    /// Parse remainder of `CREATE TYPE AS ENUM` statement (see [Statement::CreateType] and [Self::parse_create_type])
20487    ///
20488    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtype.html)
20489    pub fn parse_create_type_enum(&mut self, name: ObjectName) -> Result<Statement, ParserError> {
20490        self.expect_token(&Token::LParen)?;
20491        let labels = self.parse_comma_separated0(|p| p.parse_identifier(), Token::RParen)?;
20492        self.expect_token(&Token::RParen)?;
20493
20494        Ok(Statement::CreateType {
20495            name,
20496            representation: Some(UserDefinedTypeRepresentation::Enum { labels }),
20497        })
20498    }
20499
20500    /// Parse remainder of `CREATE TYPE AS RANGE` statement
20501    ///
20502    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtype.html)
20503    fn parse_create_type_range(&mut self, name: ObjectName) -> Result<Statement, ParserError> {
20504        self.expect_token(&Token::LParen)?;
20505        let options = self.parse_comma_separated0(|p| p.parse_range_option(), Token::RParen)?;
20506        self.expect_token(&Token::RParen)?;
20507
20508        Ok(Statement::CreateType {
20509            name,
20510            representation: Some(UserDefinedTypeRepresentation::Range { options }),
20511        })
20512    }
20513
20514    /// Parse a single range option for a `CREATE TYPE AS RANGE` statement
20515    fn parse_range_option(&mut self) -> Result<UserDefinedTypeRangeOption, ParserError> {
20516        let keyword = self.parse_one_of_keywords(&[
20517            Keyword::SUBTYPE,
20518            Keyword::SUBTYPE_OPCLASS,
20519            Keyword::COLLATION,
20520            Keyword::CANONICAL,
20521            Keyword::SUBTYPE_DIFF,
20522            Keyword::MULTIRANGE_TYPE_NAME,
20523        ]);
20524
20525        match keyword {
20526            Some(Keyword::SUBTYPE) => {
20527                self.expect_token(&Token::Eq)?;
20528                let data_type = self.parse_data_type()?;
20529                Ok(UserDefinedTypeRangeOption::Subtype(data_type))
20530            }
20531            Some(Keyword::SUBTYPE_OPCLASS) => {
20532                self.expect_token(&Token::Eq)?;
20533                let name = self.parse_object_name(false)?;
20534                Ok(UserDefinedTypeRangeOption::SubtypeOpClass(name))
20535            }
20536            Some(Keyword::COLLATION) => {
20537                self.expect_token(&Token::Eq)?;
20538                let name = self.parse_object_name(false)?;
20539                Ok(UserDefinedTypeRangeOption::Collation(name))
20540            }
20541            Some(Keyword::CANONICAL) => {
20542                self.expect_token(&Token::Eq)?;
20543                let name = self.parse_object_name(false)?;
20544                Ok(UserDefinedTypeRangeOption::Canonical(name))
20545            }
20546            Some(Keyword::SUBTYPE_DIFF) => {
20547                self.expect_token(&Token::Eq)?;
20548                let name = self.parse_object_name(false)?;
20549                Ok(UserDefinedTypeRangeOption::SubtypeDiff(name))
20550            }
20551            Some(Keyword::MULTIRANGE_TYPE_NAME) => {
20552                self.expect_token(&Token::Eq)?;
20553                let name = self.parse_object_name(false)?;
20554                Ok(UserDefinedTypeRangeOption::MultirangeTypeName(name))
20555            }
20556            _ => self.expected_ref("range option keyword", self.peek_token_ref()),
20557        }
20558    }
20559
20560    /// Parse SQL definition options for CREATE TYPE (options)
20561    fn parse_create_type_sql_definition_options(
20562        &mut self,
20563    ) -> Result<Vec<UserDefinedTypeSqlDefinitionOption>, ParserError> {
20564        self.parse_comma_separated0(|p| p.parse_sql_definition_option(), Token::RParen)
20565    }
20566
20567    /// Parse a single SQL definition option for CREATE TYPE (options)
20568    fn parse_sql_definition_option(
20569        &mut self,
20570    ) -> Result<UserDefinedTypeSqlDefinitionOption, ParserError> {
20571        let keyword = self.parse_one_of_keywords(&[
20572            Keyword::INPUT,
20573            Keyword::OUTPUT,
20574            Keyword::RECEIVE,
20575            Keyword::SEND,
20576            Keyword::TYPMOD_IN,
20577            Keyword::TYPMOD_OUT,
20578            Keyword::ANALYZE,
20579            Keyword::SUBSCRIPT,
20580            Keyword::INTERNALLENGTH,
20581            Keyword::PASSEDBYVALUE,
20582            Keyword::ALIGNMENT,
20583            Keyword::STORAGE,
20584            Keyword::LIKE,
20585            Keyword::CATEGORY,
20586            Keyword::PREFERRED,
20587            Keyword::DEFAULT,
20588            Keyword::ELEMENT,
20589            Keyword::DELIMITER,
20590            Keyword::COLLATABLE,
20591        ]);
20592
20593        match keyword {
20594            Some(Keyword::INPUT) => {
20595                self.expect_token(&Token::Eq)?;
20596                let name = self.parse_object_name(false)?;
20597                Ok(UserDefinedTypeSqlDefinitionOption::Input(name))
20598            }
20599            Some(Keyword::OUTPUT) => {
20600                self.expect_token(&Token::Eq)?;
20601                let name = self.parse_object_name(false)?;
20602                Ok(UserDefinedTypeSqlDefinitionOption::Output(name))
20603            }
20604            Some(Keyword::RECEIVE) => {
20605                self.expect_token(&Token::Eq)?;
20606                let name = self.parse_object_name(false)?;
20607                Ok(UserDefinedTypeSqlDefinitionOption::Receive(name))
20608            }
20609            Some(Keyword::SEND) => {
20610                self.expect_token(&Token::Eq)?;
20611                let name = self.parse_object_name(false)?;
20612                Ok(UserDefinedTypeSqlDefinitionOption::Send(name))
20613            }
20614            Some(Keyword::TYPMOD_IN) => {
20615                self.expect_token(&Token::Eq)?;
20616                let name = self.parse_object_name(false)?;
20617                Ok(UserDefinedTypeSqlDefinitionOption::TypmodIn(name))
20618            }
20619            Some(Keyword::TYPMOD_OUT) => {
20620                self.expect_token(&Token::Eq)?;
20621                let name = self.parse_object_name(false)?;
20622                Ok(UserDefinedTypeSqlDefinitionOption::TypmodOut(name))
20623            }
20624            Some(Keyword::ANALYZE) => {
20625                self.expect_token(&Token::Eq)?;
20626                let name = self.parse_object_name(false)?;
20627                Ok(UserDefinedTypeSqlDefinitionOption::Analyze(name))
20628            }
20629            Some(Keyword::SUBSCRIPT) => {
20630                self.expect_token(&Token::Eq)?;
20631                let name = self.parse_object_name(false)?;
20632                Ok(UserDefinedTypeSqlDefinitionOption::Subscript(name))
20633            }
20634            Some(Keyword::INTERNALLENGTH) => {
20635                self.expect_token(&Token::Eq)?;
20636                if self.parse_keyword(Keyword::VARIABLE) {
20637                    Ok(UserDefinedTypeSqlDefinitionOption::InternalLength(
20638                        UserDefinedTypeInternalLength::Variable,
20639                    ))
20640                } else {
20641                    let value = self.parse_literal_uint()?;
20642                    Ok(UserDefinedTypeSqlDefinitionOption::InternalLength(
20643                        UserDefinedTypeInternalLength::Fixed(value),
20644                    ))
20645                }
20646            }
20647            Some(Keyword::PASSEDBYVALUE) => Ok(UserDefinedTypeSqlDefinitionOption::PassedByValue),
20648            Some(Keyword::ALIGNMENT) => {
20649                self.expect_token(&Token::Eq)?;
20650                let align_keyword = self.parse_one_of_keywords(&[
20651                    Keyword::CHAR,
20652                    Keyword::INT2,
20653                    Keyword::INT4,
20654                    Keyword::DOUBLE,
20655                ]);
20656                match align_keyword {
20657                    Some(Keyword::CHAR) => Ok(UserDefinedTypeSqlDefinitionOption::Alignment(
20658                        Alignment::Char,
20659                    )),
20660                    Some(Keyword::INT2) => Ok(UserDefinedTypeSqlDefinitionOption::Alignment(
20661                        Alignment::Int2,
20662                    )),
20663                    Some(Keyword::INT4) => Ok(UserDefinedTypeSqlDefinitionOption::Alignment(
20664                        Alignment::Int4,
20665                    )),
20666                    Some(Keyword::DOUBLE) => Ok(UserDefinedTypeSqlDefinitionOption::Alignment(
20667                        Alignment::Double,
20668                    )),
20669                    _ => self.expected_ref(
20670                        "alignment value (char, int2, int4, or double)",
20671                        self.peek_token_ref(),
20672                    ),
20673                }
20674            }
20675            Some(Keyword::STORAGE) => {
20676                self.expect_token(&Token::Eq)?;
20677                let storage_keyword = self.parse_one_of_keywords(&[
20678                    Keyword::PLAIN,
20679                    Keyword::EXTERNAL,
20680                    Keyword::EXTENDED,
20681                    Keyword::MAIN,
20682                ]);
20683                match storage_keyword {
20684                    Some(Keyword::PLAIN) => Ok(UserDefinedTypeSqlDefinitionOption::Storage(
20685                        UserDefinedTypeStorage::Plain,
20686                    )),
20687                    Some(Keyword::EXTERNAL) => Ok(UserDefinedTypeSqlDefinitionOption::Storage(
20688                        UserDefinedTypeStorage::External,
20689                    )),
20690                    Some(Keyword::EXTENDED) => Ok(UserDefinedTypeSqlDefinitionOption::Storage(
20691                        UserDefinedTypeStorage::Extended,
20692                    )),
20693                    Some(Keyword::MAIN) => Ok(UserDefinedTypeSqlDefinitionOption::Storage(
20694                        UserDefinedTypeStorage::Main,
20695                    )),
20696                    _ => self.expected_ref(
20697                        "storage value (plain, external, extended, or main)",
20698                        self.peek_token_ref(),
20699                    ),
20700                }
20701            }
20702            Some(Keyword::LIKE) => {
20703                self.expect_token(&Token::Eq)?;
20704                let name = self.parse_object_name(false)?;
20705                Ok(UserDefinedTypeSqlDefinitionOption::Like(name))
20706            }
20707            Some(Keyword::CATEGORY) => {
20708                self.expect_token(&Token::Eq)?;
20709                let category_str = self.parse_literal_string()?;
20710                let category_char = category_str.chars().next().ok_or_else(|| {
20711                    ParserError::ParserError(
20712                        "CATEGORY value must be a single character".to_string(),
20713                    )
20714                })?;
20715                Ok(UserDefinedTypeSqlDefinitionOption::Category(category_char))
20716            }
20717            Some(Keyword::PREFERRED) => {
20718                self.expect_token(&Token::Eq)?;
20719                let value =
20720                    self.parse_keyword(Keyword::TRUE) || !self.parse_keyword(Keyword::FALSE);
20721                Ok(UserDefinedTypeSqlDefinitionOption::Preferred(value))
20722            }
20723            Some(Keyword::DEFAULT) => {
20724                self.expect_token(&Token::Eq)?;
20725                let expr = self.parse_expr()?;
20726                Ok(UserDefinedTypeSqlDefinitionOption::Default(expr))
20727            }
20728            Some(Keyword::ELEMENT) => {
20729                self.expect_token(&Token::Eq)?;
20730                let data_type = self.parse_data_type()?;
20731                Ok(UserDefinedTypeSqlDefinitionOption::Element(data_type))
20732            }
20733            Some(Keyword::DELIMITER) => {
20734                self.expect_token(&Token::Eq)?;
20735                let delimiter = self.parse_literal_string()?;
20736                Ok(UserDefinedTypeSqlDefinitionOption::Delimiter(delimiter))
20737            }
20738            Some(Keyword::COLLATABLE) => {
20739                self.expect_token(&Token::Eq)?;
20740                let value =
20741                    self.parse_keyword(Keyword::TRUE) || !self.parse_keyword(Keyword::FALSE);
20742                Ok(UserDefinedTypeSqlDefinitionOption::Collatable(value))
20743            }
20744            _ => self.expected_ref("SQL definition option keyword", self.peek_token_ref()),
20745        }
20746    }
20747
20748    fn parse_parenthesized_identifiers(&mut self) -> Result<Vec<Ident>, ParserError> {
20749        self.expect_token(&Token::LParen)?;
20750        let idents = self.parse_comma_separated0(|p| p.parse_identifier(), Token::RParen)?;
20751        self.expect_token(&Token::RParen)?;
20752        Ok(idents)
20753    }
20754
20755    fn parse_column_position(&mut self) -> Result<Option<MySQLColumnPosition>, ParserError> {
20756        if dialect_of!(self is MySqlDialect | GenericDialect) {
20757            if self.parse_keyword(Keyword::FIRST) {
20758                Ok(Some(MySQLColumnPosition::First))
20759            } else if self.parse_keyword(Keyword::AFTER) {
20760                let ident = self.parse_identifier()?;
20761                Ok(Some(MySQLColumnPosition::After(ident)))
20762            } else {
20763                Ok(None)
20764            }
20765        } else {
20766            Ok(None)
20767        }
20768    }
20769
20770    /// Parse [Statement::Print]
20771    fn parse_print(&mut self) -> Result<Statement, ParserError> {
20772        Ok(Statement::Print(PrintStatement {
20773            message: Box::new(self.parse_expr()?),
20774        }))
20775    }
20776
20777    /// Parse [Statement::WaitFor]
20778    ///
20779    /// See: <https://learn.microsoft.com/en-us/sql/t-sql/language-elements/waitfor-transact-sql>
20780    fn parse_waitfor(&mut self) -> Result<Statement, ParserError> {
20781        let wait_type = if self.parse_keyword(Keyword::DELAY) {
20782            WaitForType::Delay
20783        } else if self.parse_keyword(Keyword::TIME) {
20784            WaitForType::Time
20785        } else {
20786            return self.expected_ref("DELAY or TIME", self.peek_token_ref());
20787        };
20788        let expr = self.parse_expr()?;
20789        Ok(Statement::WaitFor(WaitForStatement { wait_type, expr }))
20790    }
20791
20792    /// Parse [Statement::Return]
20793    fn parse_return(&mut self) -> Result<Statement, ParserError> {
20794        match self.maybe_parse(|p| p.parse_expr())? {
20795            Some(expr) => Ok(Statement::Return(ReturnStatement {
20796                value: Some(ReturnStatementValue::Expr(expr)),
20797            })),
20798            None => Ok(Statement::Return(ReturnStatement { value: None })),
20799        }
20800    }
20801
20802    /// /// Parse a `EXPORT DATA` statement.
20803    ///
20804    /// See [Statement::ExportData]
20805    fn parse_export_data(&mut self) -> Result<Statement, ParserError> {
20806        self.expect_keywords(&[Keyword::EXPORT, Keyword::DATA])?;
20807
20808        let connection = if self.parse_keywords(&[Keyword::WITH, Keyword::CONNECTION]) {
20809            Some(self.parse_object_name(false)?)
20810        } else {
20811            None
20812        };
20813        self.expect_keyword(Keyword::OPTIONS)?;
20814        self.expect_token(&Token::LParen)?;
20815        let options = self.parse_comma_separated(|p| p.parse_sql_option())?;
20816        self.expect_token(&Token::RParen)?;
20817        self.expect_keyword(Keyword::AS)?;
20818        let query = self.parse_query()?;
20819        Ok(Statement::ExportData(ExportData {
20820            options,
20821            query,
20822            connection,
20823        }))
20824    }
20825
20826    fn parse_vacuum(&mut self) -> Result<Statement, ParserError> {
20827        self.expect_keyword(Keyword::VACUUM)?;
20828        let full = self.parse_keyword(Keyword::FULL);
20829        let sort_only = self.parse_keywords(&[Keyword::SORT, Keyword::ONLY]);
20830        let delete_only = self.parse_keywords(&[Keyword::DELETE, Keyword::ONLY]);
20831        let reindex = self.parse_keyword(Keyword::REINDEX);
20832        let recluster = self.parse_keyword(Keyword::RECLUSTER);
20833        let (table_name, threshold, boost) =
20834            match self.maybe_parse(|p| p.parse_object_name(false))? {
20835                Some(table_name) => {
20836                    let threshold = if self.parse_keyword(Keyword::TO) {
20837                        let value = self.parse_value()?;
20838                        self.expect_keyword(Keyword::PERCENT)?;
20839                        Some(value)
20840                    } else {
20841                        None
20842                    };
20843                    let boost = self.parse_keyword(Keyword::BOOST);
20844                    (Some(table_name), threshold, boost)
20845                }
20846                _ => (None, None, false),
20847            };
20848        Ok(Statement::Vacuum(VacuumStatement {
20849            full,
20850            sort_only,
20851            delete_only,
20852            reindex,
20853            recluster,
20854            table_name,
20855            threshold,
20856            boost,
20857        }))
20858    }
20859
20860    /// Consume the parser and return its underlying token buffer
20861    pub fn into_tokens(self) -> Vec<TokenWithSpan> {
20862        self.tokens
20863    }
20864
20865    /// Returns true if the next keyword indicates a sub query, i.e. SELECT or WITH
20866    fn peek_sub_query(&mut self) -> bool {
20867        self.peek_one_of_keywords(&[Keyword::SELECT, Keyword::WITH])
20868            .is_some()
20869    }
20870
20871    pub(crate) fn parse_show_stmt_options(&mut self) -> Result<ShowStatementOptions, ParserError> {
20872        let show_in;
20873        let mut filter_position = None;
20874        if self.dialect.supports_show_like_before_in() {
20875            if let Some(filter) = self.parse_show_statement_filter()? {
20876                filter_position = Some(ShowStatementFilterPosition::Infix(filter));
20877            }
20878            show_in = self.maybe_parse_show_stmt_in()?;
20879        } else {
20880            show_in = self.maybe_parse_show_stmt_in()?;
20881            if let Some(filter) = self.parse_show_statement_filter()? {
20882                filter_position = Some(ShowStatementFilterPosition::Suffix(filter));
20883            }
20884        }
20885        let starts_with = self.maybe_parse_show_stmt_starts_with()?;
20886        let limit = self.maybe_parse_show_stmt_limit()?;
20887        let from = self.maybe_parse_show_stmt_from()?;
20888        Ok(ShowStatementOptions {
20889            filter_position,
20890            show_in,
20891            starts_with,
20892            limit,
20893            limit_from: from,
20894        })
20895    }
20896
20897    fn maybe_parse_show_stmt_in(&mut self) -> Result<Option<ShowStatementIn>, ParserError> {
20898        let clause = match self.parse_one_of_keywords(&[Keyword::FROM, Keyword::IN]) {
20899            Some(Keyword::FROM) => ShowStatementInClause::FROM,
20900            Some(Keyword::IN) => ShowStatementInClause::IN,
20901            None => return Ok(None),
20902            _ => return self.expected_ref("FROM or IN", self.peek_token_ref()),
20903        };
20904
20905        let (parent_type, parent_name) = match self.parse_one_of_keywords(&[
20906            Keyword::ACCOUNT,
20907            Keyword::DATABASE,
20908            Keyword::SCHEMA,
20909            Keyword::TABLE,
20910            Keyword::VIEW,
20911        ]) {
20912            // If we see these next keywords it means we don't have a parent name
20913            Some(Keyword::DATABASE)
20914                if self.peek_keywords(&[Keyword::STARTS, Keyword::WITH])
20915                    | self.peek_keyword(Keyword::LIMIT) =>
20916            {
20917                (Some(ShowStatementInParentType::Database), None)
20918            }
20919            Some(Keyword::SCHEMA)
20920                if self.peek_keywords(&[Keyword::STARTS, Keyword::WITH])
20921                    | self.peek_keyword(Keyword::LIMIT) =>
20922            {
20923                (Some(ShowStatementInParentType::Schema), None)
20924            }
20925            Some(parent_kw) => {
20926                // The parent name here is still optional, for example:
20927                // SHOW TABLES IN ACCOUNT, so parsing the object name
20928                // may fail because the statement ends.
20929                let parent_name = self.maybe_parse(|p| p.parse_object_name(false))?;
20930                match parent_kw {
20931                    Keyword::ACCOUNT => (Some(ShowStatementInParentType::Account), parent_name),
20932                    Keyword::DATABASE => (Some(ShowStatementInParentType::Database), parent_name),
20933                    Keyword::SCHEMA => (Some(ShowStatementInParentType::Schema), parent_name),
20934                    Keyword::TABLE => (Some(ShowStatementInParentType::Table), parent_name),
20935                    Keyword::VIEW => (Some(ShowStatementInParentType::View), parent_name),
20936                    _ => {
20937                        return self.expected_ref(
20938                            "one of ACCOUNT, DATABASE, SCHEMA, TABLE or VIEW",
20939                            self.peek_token_ref(),
20940                        )
20941                    }
20942                }
20943            }
20944            None => {
20945                // Parsing MySQL style FROM tbl_name FROM db_name
20946                // which is equivalent to FROM tbl_name.db_name
20947                let mut parent_name = self.parse_object_name(false)?;
20948                if self
20949                    .parse_one_of_keywords(&[Keyword::FROM, Keyword::IN])
20950                    .is_some()
20951                {
20952                    parent_name
20953                        .0
20954                        .insert(0, ObjectNamePart::Identifier(self.parse_identifier()?));
20955                }
20956                (None, Some(parent_name))
20957            }
20958        };
20959
20960        Ok(Some(ShowStatementIn {
20961            clause,
20962            parent_type,
20963            parent_name,
20964        }))
20965    }
20966
20967    fn maybe_parse_show_stmt_starts_with(&mut self) -> Result<Option<ValueWithSpan>, ParserError> {
20968        if self.parse_keywords(&[Keyword::STARTS, Keyword::WITH]) {
20969            Ok(Some(self.parse_value()?))
20970        } else {
20971            Ok(None)
20972        }
20973    }
20974
20975    fn maybe_parse_show_stmt_limit(&mut self) -> Result<Option<Expr>, ParserError> {
20976        if self.parse_keyword(Keyword::LIMIT) {
20977            Ok(self.parse_limit()?)
20978        } else {
20979            Ok(None)
20980        }
20981    }
20982
20983    fn maybe_parse_show_stmt_from(&mut self) -> Result<Option<ValueWithSpan>, ParserError> {
20984        if self.parse_keyword(Keyword::FROM) {
20985            Ok(Some(self.parse_value()?))
20986        } else {
20987            Ok(None)
20988        }
20989    }
20990
20991    pub(crate) fn in_column_definition_state(&self) -> bool {
20992        matches!(self.state, ColumnDefinition)
20993    }
20994
20995    /// Parses options provided in key-value format.
20996    ///
20997    /// * `parenthesized` - true if the options are enclosed in parenthesis
20998    /// * `end_words` - a list of keywords that any of them indicates the end of the options section
20999    pub(crate) fn parse_key_value_options(
21000        &mut self,
21001        parenthesized: bool,
21002        end_words: &[Keyword],
21003    ) -> Result<KeyValueOptions, ParserError> {
21004        let mut options: Vec<KeyValueOption> = Vec::new();
21005        let mut delimiter = KeyValueOptionsDelimiter::Space;
21006        if parenthesized {
21007            self.expect_token(&Token::LParen)?;
21008        }
21009        loop {
21010            match self.next_token().token {
21011                Token::RParen => {
21012                    if parenthesized {
21013                        break;
21014                    } else {
21015                        return self.expected_ref(" another option or EOF", self.peek_token_ref());
21016                    }
21017                }
21018                Token::EOF => break,
21019                Token::SemiColon => {
21020                    self.prev_token();
21021                    break;
21022                }
21023                Token::Comma => {
21024                    delimiter = KeyValueOptionsDelimiter::Comma;
21025                    continue;
21026                }
21027                Token::Word(w) if !end_words.contains(&w.keyword) => {
21028                    options.push(self.parse_key_value_option(&w)?)
21029                }
21030                Token::Word(w) if end_words.contains(&w.keyword) => {
21031                    self.prev_token();
21032                    break;
21033                }
21034                _ => {
21035                    return self.expected_ref(
21036                        "another option, EOF, SemiColon, Comma or ')'",
21037                        self.peek_token_ref(),
21038                    )
21039                }
21040            };
21041        }
21042
21043        Ok(KeyValueOptions { delimiter, options })
21044    }
21045
21046    /// Parses a `KEY = VALUE` construct based on the specified key
21047    pub(crate) fn parse_key_value_option(
21048        &mut self,
21049        key: &Word,
21050    ) -> Result<KeyValueOption, ParserError> {
21051        self.expect_token(&Token::Eq)?;
21052        let peeked_token = self.peek_token();
21053        match peeked_token.token {
21054            Token::SingleQuotedString(_) => Ok(KeyValueOption {
21055                option_name: key.value.clone(),
21056                option_value: KeyValueOptionKind::Single(self.parse_value()?),
21057            }),
21058            Token::Word(word)
21059                if word.keyword == Keyword::TRUE || word.keyword == Keyword::FALSE =>
21060            {
21061                Ok(KeyValueOption {
21062                    option_name: key.value.clone(),
21063                    option_value: KeyValueOptionKind::Single(self.parse_value()?),
21064                })
21065            }
21066            Token::Number(..) => Ok(KeyValueOption {
21067                option_name: key.value.clone(),
21068                option_value: KeyValueOptionKind::Single(self.parse_value()?),
21069            }),
21070            Token::Word(word) => {
21071                self.next_token();
21072                Ok(KeyValueOption {
21073                    option_name: key.value.clone(),
21074                    option_value: KeyValueOptionKind::Single(
21075                        Value::Placeholder(word.value.clone()).with_span(peeked_token.span),
21076                    ),
21077                })
21078            }
21079            Token::LParen => {
21080                // Can be a list of values or a list of key value properties.
21081                // Try to parse a list of values and if that fails, try to parse
21082                // a list of key-value properties.
21083                match self.maybe_parse(|parser| {
21084                    parser.expect_token(&Token::LParen)?;
21085                    let values = parser.parse_comma_separated0(|p| p.parse_value(), Token::RParen);
21086                    parser.expect_token(&Token::RParen)?;
21087                    values
21088                })? {
21089                    Some(values) => Ok(KeyValueOption {
21090                        option_name: key.value.clone(),
21091                        option_value: KeyValueOptionKind::Multi(values),
21092                    }),
21093                    None => Ok(KeyValueOption {
21094                        option_name: key.value.clone(),
21095                        option_value: KeyValueOptionKind::KeyValueOptions(Box::new(
21096                            self.parse_key_value_options(true, &[])?,
21097                        )),
21098                    }),
21099                }
21100            }
21101            _ => self.expected_ref("expected option value", self.peek_token_ref()),
21102        }
21103    }
21104
21105    /// Parses a RESET statement
21106    fn parse_reset(&mut self) -> Result<ResetStatement, ParserError> {
21107        if self.parse_keyword(Keyword::ALL) {
21108            return Ok(ResetStatement { reset: Reset::ALL });
21109        }
21110
21111        let obj = self.parse_object_name(false)?;
21112        Ok(ResetStatement {
21113            reset: Reset::ConfigurationParameter(obj),
21114        })
21115    }
21116}
21117
21118fn maybe_prefixed_expr(expr: Expr, prefix: Option<Ident>) -> Expr {
21119    if let Some(prefix) = prefix {
21120        Expr::Prefixed {
21121            prefix,
21122            value: Box::new(expr),
21123        }
21124    } else {
21125        expr
21126    }
21127}
21128
21129impl Word {
21130    /// Convert a reference to this word into an [`Ident`] by cloning the value.
21131    ///
21132    /// Use this method when you need to keep the original `Word` around.
21133    /// If you can consume the `Word`, prefer [`into_ident`](Self::into_ident) instead
21134    /// to avoid cloning.
21135    pub fn to_ident(&self, span: Span) -> Ident {
21136        Ident {
21137            value: self.value.clone(),
21138            quote_style: self.quote_style,
21139            span,
21140        }
21141    }
21142
21143    /// Convert this word into an [`Ident`] identifier, consuming the `Word`.
21144    ///
21145    /// This avoids cloning the string value. If you need to keep the original
21146    /// `Word`, use [`to_ident`](Self::to_ident) instead.
21147    pub fn into_ident(self, span: Span) -> Ident {
21148        Ident {
21149            value: self.value,
21150            quote_style: self.quote_style,
21151            span,
21152        }
21153    }
21154}
21155
21156#[cfg(test)]
21157mod tests {
21158    use crate::test_utils::{all_dialects, TestedDialects};
21159
21160    use super::*;
21161
21162    #[test]
21163    fn test_prev_index() {
21164        let sql = "SELECT version";
21165        all_dialects().run_parser_method(sql, |parser| {
21166            assert_eq!(parser.peek_token(), Token::make_keyword("SELECT"));
21167            assert_eq!(parser.next_token(), Token::make_keyword("SELECT"));
21168            parser.prev_token();
21169            assert_eq!(parser.next_token(), Token::make_keyword("SELECT"));
21170            assert_eq!(parser.next_token(), Token::make_word("version", None));
21171            parser.prev_token();
21172            assert_eq!(parser.peek_token(), Token::make_word("version", None));
21173            assert_eq!(parser.next_token(), Token::make_word("version", None));
21174            assert_eq!(parser.peek_token(), Token::EOF);
21175            parser.prev_token();
21176            assert_eq!(parser.next_token(), Token::make_word("version", None));
21177            assert_eq!(parser.next_token(), Token::EOF);
21178            assert_eq!(parser.next_token(), Token::EOF);
21179            parser.prev_token();
21180        });
21181    }
21182
21183    #[test]
21184    fn test_peek_tokens() {
21185        all_dialects().run_parser_method("SELECT foo AS bar FROM baz", |parser| {
21186            assert!(matches!(
21187                parser.peek_tokens(),
21188                [Token::Word(Word {
21189                    keyword: Keyword::SELECT,
21190                    ..
21191                })]
21192            ));
21193
21194            assert!(matches!(
21195                parser.peek_tokens(),
21196                [
21197                    Token::Word(Word {
21198                        keyword: Keyword::SELECT,
21199                        ..
21200                    }),
21201                    Token::Word(_),
21202                    Token::Word(Word {
21203                        keyword: Keyword::AS,
21204                        ..
21205                    }),
21206                ]
21207            ));
21208
21209            for _ in 0..4 {
21210                parser.next_token();
21211            }
21212
21213            assert!(matches!(
21214                parser.peek_tokens(),
21215                [
21216                    Token::Word(Word {
21217                        keyword: Keyword::FROM,
21218                        ..
21219                    }),
21220                    Token::Word(_),
21221                    Token::EOF,
21222                    Token::EOF,
21223                ]
21224            ))
21225        })
21226    }
21227
21228    #[cfg(test)]
21229    mod test_parse_data_type {
21230        use crate::ast::{
21231            CharLengthUnits, CharacterLength, DataType, ExactNumberInfo, ObjectName, TimezoneInfo,
21232        };
21233        use crate::dialect::{AnsiDialect, GenericDialect, PostgreSqlDialect};
21234        use crate::test_utils::TestedDialects;
21235
21236        macro_rules! test_parse_data_type {
21237            ($dialect:expr, $input:expr, $expected_type:expr $(,)?) => {{
21238                $dialect.run_parser_method(&*$input, |parser| {
21239                    let data_type = parser.parse_data_type().unwrap();
21240                    assert_eq!($expected_type, data_type);
21241                    assert_eq!($input.to_string(), data_type.to_string());
21242                });
21243            }};
21244        }
21245
21246        #[test]
21247        fn test_ansii_character_string_types() {
21248            // Character string types: <https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#character-string-type>
21249            let dialect =
21250                TestedDialects::new(vec![Box::new(GenericDialect {}), Box::new(AnsiDialect {})]);
21251
21252            test_parse_data_type!(dialect, "CHARACTER", DataType::Character(None));
21253
21254            test_parse_data_type!(
21255                dialect,
21256                "CHARACTER(20)",
21257                DataType::Character(Some(CharacterLength::IntegerLength {
21258                    length: 20,
21259                    unit: None
21260                }))
21261            );
21262
21263            test_parse_data_type!(
21264                dialect,
21265                "CHARACTER(20 CHARACTERS)",
21266                DataType::Character(Some(CharacterLength::IntegerLength {
21267                    length: 20,
21268                    unit: Some(CharLengthUnits::Characters)
21269                }))
21270            );
21271
21272            test_parse_data_type!(
21273                dialect,
21274                "CHARACTER(20 OCTETS)",
21275                DataType::Character(Some(CharacterLength::IntegerLength {
21276                    length: 20,
21277                    unit: Some(CharLengthUnits::Octets)
21278                }))
21279            );
21280
21281            test_parse_data_type!(dialect, "CHAR", DataType::Char(None));
21282
21283            test_parse_data_type!(
21284                dialect,
21285                "CHAR(20)",
21286                DataType::Char(Some(CharacterLength::IntegerLength {
21287                    length: 20,
21288                    unit: None
21289                }))
21290            );
21291
21292            test_parse_data_type!(
21293                dialect,
21294                "CHAR(20 CHARACTERS)",
21295                DataType::Char(Some(CharacterLength::IntegerLength {
21296                    length: 20,
21297                    unit: Some(CharLengthUnits::Characters)
21298                }))
21299            );
21300
21301            test_parse_data_type!(
21302                dialect,
21303                "CHAR(20 OCTETS)",
21304                DataType::Char(Some(CharacterLength::IntegerLength {
21305                    length: 20,
21306                    unit: Some(CharLengthUnits::Octets)
21307                }))
21308            );
21309
21310            test_parse_data_type!(
21311                dialect,
21312                "CHARACTER VARYING(20)",
21313                DataType::CharacterVarying(Some(CharacterLength::IntegerLength {
21314                    length: 20,
21315                    unit: None
21316                }))
21317            );
21318
21319            test_parse_data_type!(
21320                dialect,
21321                "CHARACTER VARYING(20 CHARACTERS)",
21322                DataType::CharacterVarying(Some(CharacterLength::IntegerLength {
21323                    length: 20,
21324                    unit: Some(CharLengthUnits::Characters)
21325                }))
21326            );
21327
21328            test_parse_data_type!(
21329                dialect,
21330                "CHARACTER VARYING(20 OCTETS)",
21331                DataType::CharacterVarying(Some(CharacterLength::IntegerLength {
21332                    length: 20,
21333                    unit: Some(CharLengthUnits::Octets)
21334                }))
21335            );
21336
21337            test_parse_data_type!(
21338                dialect,
21339                "CHAR VARYING(20)",
21340                DataType::CharVarying(Some(CharacterLength::IntegerLength {
21341                    length: 20,
21342                    unit: None
21343                }))
21344            );
21345
21346            test_parse_data_type!(
21347                dialect,
21348                "CHAR VARYING(20 CHARACTERS)",
21349                DataType::CharVarying(Some(CharacterLength::IntegerLength {
21350                    length: 20,
21351                    unit: Some(CharLengthUnits::Characters)
21352                }))
21353            );
21354
21355            test_parse_data_type!(
21356                dialect,
21357                "CHAR VARYING(20 OCTETS)",
21358                DataType::CharVarying(Some(CharacterLength::IntegerLength {
21359                    length: 20,
21360                    unit: Some(CharLengthUnits::Octets)
21361                }))
21362            );
21363
21364            test_parse_data_type!(
21365                dialect,
21366                "VARCHAR(20)",
21367                DataType::Varchar(Some(CharacterLength::IntegerLength {
21368                    length: 20,
21369                    unit: None
21370                }))
21371            );
21372        }
21373
21374        #[test]
21375        fn test_ansii_character_large_object_types() {
21376            // Character large object types: <https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#character-large-object-length>
21377            let dialect =
21378                TestedDialects::new(vec![Box::new(GenericDialect {}), Box::new(AnsiDialect {})]);
21379
21380            test_parse_data_type!(
21381                dialect,
21382                "CHARACTER LARGE OBJECT",
21383                DataType::CharacterLargeObject(None)
21384            );
21385            test_parse_data_type!(
21386                dialect,
21387                "CHARACTER LARGE OBJECT(20)",
21388                DataType::CharacterLargeObject(Some(20))
21389            );
21390
21391            test_parse_data_type!(
21392                dialect,
21393                "CHAR LARGE OBJECT",
21394                DataType::CharLargeObject(None)
21395            );
21396            test_parse_data_type!(
21397                dialect,
21398                "CHAR LARGE OBJECT(20)",
21399                DataType::CharLargeObject(Some(20))
21400            );
21401
21402            test_parse_data_type!(dialect, "CLOB", DataType::Clob(None));
21403            test_parse_data_type!(dialect, "CLOB(20)", DataType::Clob(Some(20)));
21404        }
21405
21406        #[test]
21407        fn test_parse_custom_types() {
21408            let dialect =
21409                TestedDialects::new(vec![Box::new(GenericDialect {}), Box::new(AnsiDialect {})]);
21410
21411            test_parse_data_type!(
21412                dialect,
21413                "GEOMETRY",
21414                DataType::Custom(ObjectName::from(vec!["GEOMETRY".into()]), vec![])
21415            );
21416
21417            test_parse_data_type!(
21418                dialect,
21419                "GEOMETRY(POINT)",
21420                DataType::Custom(
21421                    ObjectName::from(vec!["GEOMETRY".into()]),
21422                    vec!["POINT".to_string()]
21423                )
21424            );
21425
21426            test_parse_data_type!(
21427                dialect,
21428                "GEOMETRY(POINT, 4326)",
21429                DataType::Custom(
21430                    ObjectName::from(vec!["GEOMETRY".into()]),
21431                    vec!["POINT".to_string(), "4326".to_string()]
21432                )
21433            );
21434        }
21435
21436        #[test]
21437        fn test_ansii_exact_numeric_types() {
21438            // Exact numeric types: <https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#exact-numeric-type>
21439            let dialect = TestedDialects::new(vec![
21440                Box::new(GenericDialect {}),
21441                Box::new(AnsiDialect {}),
21442                Box::new(PostgreSqlDialect {}),
21443            ]);
21444
21445            test_parse_data_type!(dialect, "NUMERIC", DataType::Numeric(ExactNumberInfo::None));
21446
21447            test_parse_data_type!(
21448                dialect,
21449                "NUMERIC(2)",
21450                DataType::Numeric(ExactNumberInfo::Precision(2))
21451            );
21452
21453            test_parse_data_type!(
21454                dialect,
21455                "NUMERIC(2,10)",
21456                DataType::Numeric(ExactNumberInfo::PrecisionAndScale(2, 10))
21457            );
21458
21459            test_parse_data_type!(dialect, "DECIMAL", DataType::Decimal(ExactNumberInfo::None));
21460
21461            test_parse_data_type!(
21462                dialect,
21463                "DECIMAL(2)",
21464                DataType::Decimal(ExactNumberInfo::Precision(2))
21465            );
21466
21467            test_parse_data_type!(
21468                dialect,
21469                "DECIMAL(2,10)",
21470                DataType::Decimal(ExactNumberInfo::PrecisionAndScale(2, 10))
21471            );
21472
21473            test_parse_data_type!(dialect, "DEC", DataType::Dec(ExactNumberInfo::None));
21474
21475            test_parse_data_type!(
21476                dialect,
21477                "DEC(2)",
21478                DataType::Dec(ExactNumberInfo::Precision(2))
21479            );
21480
21481            test_parse_data_type!(
21482                dialect,
21483                "DEC(2,10)",
21484                DataType::Dec(ExactNumberInfo::PrecisionAndScale(2, 10))
21485            );
21486
21487            // Test negative scale values.
21488            test_parse_data_type!(
21489                dialect,
21490                "NUMERIC(10,-2)",
21491                DataType::Numeric(ExactNumberInfo::PrecisionAndScale(10, -2))
21492            );
21493
21494            test_parse_data_type!(
21495                dialect,
21496                "DECIMAL(1000,-10)",
21497                DataType::Decimal(ExactNumberInfo::PrecisionAndScale(1000, -10))
21498            );
21499
21500            test_parse_data_type!(
21501                dialect,
21502                "DEC(5,-1000)",
21503                DataType::Dec(ExactNumberInfo::PrecisionAndScale(5, -1000))
21504            );
21505
21506            test_parse_data_type!(
21507                dialect,
21508                "NUMERIC(10,-5)",
21509                DataType::Numeric(ExactNumberInfo::PrecisionAndScale(10, -5))
21510            );
21511
21512            test_parse_data_type!(
21513                dialect,
21514                "DECIMAL(20,-10)",
21515                DataType::Decimal(ExactNumberInfo::PrecisionAndScale(20, -10))
21516            );
21517
21518            test_parse_data_type!(
21519                dialect,
21520                "DEC(5,-2)",
21521                DataType::Dec(ExactNumberInfo::PrecisionAndScale(5, -2))
21522            );
21523
21524            dialect.run_parser_method("NUMERIC(10,+5)", |parser| {
21525                let data_type = parser.parse_data_type().unwrap();
21526                assert_eq!(
21527                    DataType::Numeric(ExactNumberInfo::PrecisionAndScale(10, 5)),
21528                    data_type
21529                );
21530                // Note: Explicit '+' sign is not preserved in output, which is correct
21531                assert_eq!("NUMERIC(10,5)", data_type.to_string());
21532            });
21533        }
21534
21535        #[test]
21536        fn test_ansii_date_type() {
21537            // Datetime types: <https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#datetime-type>
21538            let dialect =
21539                TestedDialects::new(vec![Box::new(GenericDialect {}), Box::new(AnsiDialect {})]);
21540
21541            test_parse_data_type!(dialect, "DATE", DataType::Date);
21542
21543            test_parse_data_type!(dialect, "TIME", DataType::Time(None, TimezoneInfo::None));
21544
21545            test_parse_data_type!(
21546                dialect,
21547                "TIME(6)",
21548                DataType::Time(Some(6), TimezoneInfo::None)
21549            );
21550
21551            test_parse_data_type!(
21552                dialect,
21553                "TIME WITH TIME ZONE",
21554                DataType::Time(None, TimezoneInfo::WithTimeZone)
21555            );
21556
21557            test_parse_data_type!(
21558                dialect,
21559                "TIME(6) WITH TIME ZONE",
21560                DataType::Time(Some(6), TimezoneInfo::WithTimeZone)
21561            );
21562
21563            test_parse_data_type!(
21564                dialect,
21565                "TIME WITHOUT TIME ZONE",
21566                DataType::Time(None, TimezoneInfo::WithoutTimeZone)
21567            );
21568
21569            test_parse_data_type!(
21570                dialect,
21571                "TIME(6) WITHOUT TIME ZONE",
21572                DataType::Time(Some(6), TimezoneInfo::WithoutTimeZone)
21573            );
21574
21575            test_parse_data_type!(
21576                dialect,
21577                "TIMESTAMP",
21578                DataType::Timestamp(None, TimezoneInfo::None)
21579            );
21580
21581            test_parse_data_type!(
21582                dialect,
21583                "TIMESTAMP(22)",
21584                DataType::Timestamp(Some(22), TimezoneInfo::None)
21585            );
21586
21587            test_parse_data_type!(
21588                dialect,
21589                "TIMESTAMP(22) WITH TIME ZONE",
21590                DataType::Timestamp(Some(22), TimezoneInfo::WithTimeZone)
21591            );
21592
21593            test_parse_data_type!(
21594                dialect,
21595                "TIMESTAMP(33) WITHOUT TIME ZONE",
21596                DataType::Timestamp(Some(33), TimezoneInfo::WithoutTimeZone)
21597            );
21598        }
21599    }
21600
21601    #[test]
21602    fn test_parse_schema_name() {
21603        // The expected name should be identical as the input name, that's why I don't receive both
21604        macro_rules! test_parse_schema_name {
21605            ($input:expr, $expected_name:expr $(,)?) => {{
21606                all_dialects().run_parser_method(&*$input, |parser| {
21607                    let schema_name = parser.parse_schema_name().unwrap();
21608                    // Validate that the structure is the same as expected
21609                    assert_eq!(schema_name, $expected_name);
21610                    // Validate that the input and the expected structure serialization are the same
21611                    assert_eq!(schema_name.to_string(), $input.to_string());
21612                });
21613            }};
21614        }
21615
21616        let dummy_name = ObjectName::from(vec![Ident::new("dummy_name")]);
21617        let dummy_authorization = Ident::new("dummy_authorization");
21618
21619        test_parse_schema_name!(
21620            format!("{dummy_name}"),
21621            SchemaName::Simple(dummy_name.clone())
21622        );
21623
21624        test_parse_schema_name!(
21625            format!("AUTHORIZATION {dummy_authorization}"),
21626            SchemaName::UnnamedAuthorization(dummy_authorization.clone()),
21627        );
21628        test_parse_schema_name!(
21629            format!("{dummy_name} AUTHORIZATION {dummy_authorization}"),
21630            SchemaName::NamedAuthorization(dummy_name.clone(), dummy_authorization.clone()),
21631        );
21632    }
21633
21634    #[test]
21635    fn mysql_parse_index_table_constraint() {
21636        macro_rules! test_parse_table_constraint {
21637            ($dialect:expr, $input:expr, $expected:expr $(,)?) => {{
21638                $dialect.run_parser_method(&*$input, |parser| {
21639                    let constraint = parser.parse_optional_table_constraint().unwrap().unwrap();
21640                    // Validate that the structure is the same as expected
21641                    assert_eq!(constraint, $expected);
21642                    // Validate that the input and the expected structure serialization are the same
21643                    assert_eq!(constraint.to_string(), $input.to_string());
21644                });
21645            }};
21646        }
21647
21648        fn mk_expected_col(name: &str) -> IndexColumn {
21649            IndexColumn {
21650                column: OrderByExpr {
21651                    expr: Expr::Identifier(name.into()),
21652                    options: OrderByOptions {
21653                        sort: None,
21654                        nulls_first: None,
21655                    },
21656                    with_fill: None,
21657                },
21658                operator_class: None,
21659            }
21660        }
21661
21662        let dialect =
21663            TestedDialects::new(vec![Box::new(GenericDialect {}), Box::new(MySqlDialect {})]);
21664
21665        test_parse_table_constraint!(
21666            dialect,
21667            "INDEX (c1)",
21668            IndexConstraint {
21669                display_as_key: false,
21670                name: None,
21671                index_type: None,
21672                columns: vec![mk_expected_col("c1")],
21673                index_options: vec![],
21674            }
21675            .into()
21676        );
21677
21678        test_parse_table_constraint!(
21679            dialect,
21680            "KEY (c1)",
21681            IndexConstraint {
21682                display_as_key: true,
21683                name: None,
21684                index_type: None,
21685                columns: vec![mk_expected_col("c1")],
21686                index_options: vec![],
21687            }
21688            .into()
21689        );
21690
21691        test_parse_table_constraint!(
21692            dialect,
21693            "INDEX 'index' (c1, c2)",
21694            TableConstraint::Index(IndexConstraint {
21695                display_as_key: false,
21696                name: Some(Ident::with_quote('\'', "index")),
21697                index_type: None,
21698                columns: vec![mk_expected_col("c1"), mk_expected_col("c2")],
21699                index_options: vec![],
21700            })
21701        );
21702
21703        test_parse_table_constraint!(
21704            dialect,
21705            "INDEX USING BTREE (c1)",
21706            IndexConstraint {
21707                display_as_key: false,
21708                name: None,
21709                index_type: Some(IndexType::BTree),
21710                columns: vec![mk_expected_col("c1")],
21711                index_options: vec![],
21712            }
21713            .into()
21714        );
21715
21716        test_parse_table_constraint!(
21717            dialect,
21718            "INDEX USING HASH (c1)",
21719            IndexConstraint {
21720                display_as_key: false,
21721                name: None,
21722                index_type: Some(IndexType::Hash),
21723                columns: vec![mk_expected_col("c1")],
21724                index_options: vec![],
21725            }
21726            .into()
21727        );
21728
21729        test_parse_table_constraint!(
21730            dialect,
21731            "INDEX idx_name USING BTREE (c1)",
21732            IndexConstraint {
21733                display_as_key: false,
21734                name: Some(Ident::new("idx_name")),
21735                index_type: Some(IndexType::BTree),
21736                columns: vec![mk_expected_col("c1")],
21737                index_options: vec![],
21738            }
21739            .into()
21740        );
21741
21742        test_parse_table_constraint!(
21743            dialect,
21744            "INDEX idx_name USING HASH (c1)",
21745            IndexConstraint {
21746                display_as_key: false,
21747                name: Some(Ident::new("idx_name")),
21748                index_type: Some(IndexType::Hash),
21749                columns: vec![mk_expected_col("c1")],
21750                index_options: vec![],
21751            }
21752            .into()
21753        );
21754    }
21755
21756    #[test]
21757    fn test_tokenizer_error_loc() {
21758        let sql = "foo '";
21759        let ast = Parser::parse_sql(&GenericDialect, sql);
21760        assert_eq!(
21761            ast,
21762            Err(ParserError::TokenizerError(
21763                "Unterminated string literal at Line: 1, Column: 5".to_string()
21764            ))
21765        );
21766    }
21767
21768    #[test]
21769    fn test_parser_error_loc() {
21770        let sql = "SELECT this is a syntax error";
21771        let ast = Parser::parse_sql(&GenericDialect, sql);
21772        assert_eq!(
21773            ast,
21774            Err(ParserError::ParserError(
21775                "Expected: [NOT] NULL | TRUE | FALSE | DISTINCT | [form] NORMALIZED FROM after IS, found: a at Line: 1, Column: 16"
21776                    .to_string()
21777            ))
21778        );
21779    }
21780
21781    #[test]
21782    fn test_nested_explain_error() {
21783        let sql = "EXPLAIN EXPLAIN SELECT 1";
21784        let ast = Parser::parse_sql(&GenericDialect, sql);
21785        assert_eq!(
21786            ast,
21787            Err(ParserError::ParserError(
21788                "Explain must be root of the plan".to_string()
21789            ))
21790        );
21791    }
21792
21793    #[test]
21794    fn test_parse_multipart_identifier_positive() {
21795        let dialect = TestedDialects::new(vec![Box::new(GenericDialect {})]);
21796
21797        // parse multipart with quotes
21798        let expected = vec![
21799            Ident {
21800                value: "CATALOG".to_string(),
21801                quote_style: None,
21802                span: Span::empty(),
21803            },
21804            Ident {
21805                value: "F(o)o. \"bar".to_string(),
21806                quote_style: Some('"'),
21807                span: Span::empty(),
21808            },
21809            Ident {
21810                value: "table".to_string(),
21811                quote_style: None,
21812                span: Span::empty(),
21813            },
21814        ];
21815        dialect.run_parser_method(r#"CATALOG."F(o)o. ""bar".table"#, |parser| {
21816            let actual = parser.parse_multipart_identifier().unwrap();
21817            assert_eq!(expected, actual);
21818        });
21819
21820        // allow whitespace between ident parts
21821        let expected = vec![
21822            Ident {
21823                value: "CATALOG".to_string(),
21824                quote_style: None,
21825                span: Span::empty(),
21826            },
21827            Ident {
21828                value: "table".to_string(),
21829                quote_style: None,
21830                span: Span::empty(),
21831            },
21832        ];
21833        dialect.run_parser_method("CATALOG . table", |parser| {
21834            let actual = parser.parse_multipart_identifier().unwrap();
21835            assert_eq!(expected, actual);
21836        });
21837    }
21838
21839    #[test]
21840    fn test_parse_multipart_identifier_negative() {
21841        macro_rules! test_parse_multipart_identifier_error {
21842            ($input:expr, $expected_err:expr $(,)?) => {{
21843                all_dialects().run_parser_method(&*$input, |parser| {
21844                    let actual_err = parser.parse_multipart_identifier().unwrap_err();
21845                    assert_eq!(actual_err.to_string(), $expected_err);
21846                });
21847            }};
21848        }
21849
21850        test_parse_multipart_identifier_error!(
21851            "",
21852            "sql parser error: Empty input when parsing identifier",
21853        );
21854
21855        test_parse_multipart_identifier_error!(
21856            "*schema.table",
21857            "sql parser error: Unexpected token in identifier: *",
21858        );
21859
21860        test_parse_multipart_identifier_error!(
21861            "schema.table*",
21862            "sql parser error: Unexpected token in identifier: *",
21863        );
21864
21865        test_parse_multipart_identifier_error!(
21866            "schema.table.",
21867            "sql parser error: Trailing period in identifier",
21868        );
21869
21870        test_parse_multipart_identifier_error!(
21871            "schema.*",
21872            "sql parser error: Unexpected token following period in identifier: *",
21873        );
21874    }
21875
21876    #[test]
21877    fn test_mysql_partition_selection() {
21878        let sql = "SELECT * FROM employees PARTITION (p0, p2)";
21879        let expected = vec!["p0", "p2"];
21880
21881        let ast: Vec<Statement> = Parser::parse_sql(&MySqlDialect {}, sql).unwrap();
21882        assert_eq!(ast.len(), 1);
21883        if let Statement::Query(v) = &ast[0] {
21884            if let SetExpr::Select(select) = &*v.body {
21885                assert_eq!(select.from.len(), 1);
21886                let from: &TableWithJoins = &select.from[0];
21887                let table_factor = &from.relation;
21888                if let TableFactor::Table { partitions, .. } = table_factor {
21889                    let actual: Vec<&str> = partitions
21890                        .iter()
21891                        .map(|ident| ident.value.as_str())
21892                        .collect();
21893                    assert_eq!(expected, actual);
21894                }
21895            }
21896        } else {
21897            panic!("fail to parse mysql partition selection");
21898        }
21899    }
21900
21901    #[test]
21902    fn test_replace_into_placeholders() {
21903        let sql = "REPLACE INTO t (a) VALUES (&a)";
21904
21905        assert!(Parser::parse_sql(&GenericDialect {}, sql).is_err());
21906    }
21907
21908    #[test]
21909    fn test_replace_into_set_placeholder() {
21910        let sql = "REPLACE INTO t SET ?";
21911
21912        assert!(Parser::parse_sql(&GenericDialect {}, sql).is_err());
21913    }
21914
21915    #[test]
21916    fn test_replace_incomplete() {
21917        let sql = r#"REPLACE"#;
21918
21919        assert!(Parser::parse_sql(&MySqlDialect {}, sql).is_err());
21920    }
21921
21922    #[test]
21923    fn test_placeholder_invalid_whitespace() {
21924        for w in ["  ", "/*invalid*/"] {
21925            let sql = format!("\nSELECT\n  :{w}fooBar");
21926            assert!(Parser::parse_sql(&GenericDialect, &sql).is_err());
21927        }
21928    }
21929}