Skip to main content

sqlparser/ast/
mod.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! SQL Abstract Syntax Tree (AST) types
19#[cfg(not(feature = "std"))]
20use alloc::{
21    boxed::Box,
22    format,
23    string::{String, ToString},
24    vec,
25    vec::Vec,
26};
27use helpers::{
28    attached_token::AttachedToken,
29    stmt_data_loading::{FileStagingCommand, StageLoadSelectItemKind},
30};
31
32use core::cmp::Ordering;
33use core::ops::{Deref, DerefMut};
34use core::{
35    fmt::{self, Display},
36    hash,
37};
38
39#[cfg(feature = "serde")]
40use serde::{Deserialize, Serialize};
41
42#[cfg(feature = "visitor")]
43use core::ops::ControlFlow;
44#[cfg(feature = "visitor")]
45use sqlparser_derive::{Visit, VisitMut};
46
47use crate::{
48    display_utils::SpaceOrNewline,
49    tokenizer::{Span, Token, OPERATOR_CHARS},
50};
51use crate::{
52    display_utils::{first_char, Indent, NewLine},
53    keywords::Keyword,
54};
55
56pub use self::data_type::{
57    ArrayElemTypeDef, BinaryLength, CharLengthUnits, CharacterLength, DataType, EnumMember,
58    ExactNumberInfo, IntervalFields, MapBracketKind, StructBracketKind, TimezoneInfo, TypeModifier,
59};
60pub use self::dcl::{
61    AlterDefaultPrivileges, AlterDefaultPrivilegesOperation, AlterRoleOperation, CreateRole,
62    DefaultPrivilegesObjectType, DefaultPrivilegesOption, Grant, GrantRole, ResetConfig, Revoke,
63    RevokeRole, RoleGrantOption, RoleGrantOptionValue, RoleKeyword, RoleOption, SecondaryRoles,
64    SetConfigValue, Use,
65};
66pub use self::ddl::{
67    AggregateModifyKind, Alignment, AlterCollation, AlterCollationOperation, AlterColumnOperation,
68    AlterConnectorOwner, AlterFunction, AlterFunctionAction, AlterFunctionKind,
69    AlterFunctionOperation, AlterGenericOption, AlterIndexOperation, AlterOperator,
70    AlterOperatorClass, AlterOperatorClassOperation, AlterOperatorFamily,
71    AlterOperatorFamilyOperation, AlterOperatorOperation, AlterPolicy, AlterPolicyOperation,
72    AlterSchema, AlterSchemaOperation, AlterTable, AlterTableAlgorithm, AlterTableLock,
73    AlterTableOperation, AlterTableType, AlterTextSearch, AlterTextSearchOperation,
74    AlterTextSearchOption, AlterTrigger, AlterTriggerOperation, AlterType, AlterTypeAddValue,
75    AlterTypeAddValuePosition, AlterTypeOperation, AlterTypeRename, AlterTypeRenameValue,
76    AlterView, AlterViewOperation, ClusteredBy, ColumnDef, ColumnOption, ColumnOptionDef,
77    ColumnOptions, ColumnPolicy, ColumnPolicyProperty, ConstraintCharacteristics, CreateAggregate,
78    CreateAggregateArgs, CreateAggregateOption, CreateCollation, CreateCollationDefinition,
79    CreateConnector, CreateDomain, CreateExtension, CreateForeignDataWrapper, CreateForeignTable,
80    CreateFunction, CreateIndex, CreateOperator, CreateOperatorClass, CreateOperatorFamily,
81    CreatePolicy, CreatePolicyCommand, CreatePolicyType, CreateRule, CreateRuleAction,
82    CreateRuleDoKind, CreateRuleEvent, CreateTable, CreateTextSearch, CreateTrigger,
83    CreateUserMapping, CreateView, Deduplicate, DeferrableInitial, DetachPartitionMode, DistStyle,
84    DropBehavior, DropExtension, DropFunction, DropOperator, DropOperatorClass, DropOperatorFamily,
85    DropOperatorSignature, DropPolicy, DropRule, DropTrigger, ForValues,
86    ForeignDataWrapperRoutineClause, FunctionReturnType, GeneratedAs, GeneratedExpressionMode,
87    IdentityParameters, IdentityProperty, IdentityPropertyFormatKind, IdentityPropertyKind,
88    IdentityPropertyOrder, IndexColumn, IndexOption, IndexType, KeyOrIndexDisplay, Msck,
89    NullsDistinctOption, OperatorArgTypes, OperatorClassItem, OperatorFamilyDropItem,
90    OperatorFamilyItem, OperatorOption, OperatorPurpose, Owner, Partition, PartitionBoundValue,
91    ProcedureParam, ReferentialAction, RenameTableNameKind, ReplicaIdentity, SqliteTableOption,
92    SqliteTableOptions, TagsColumnOption, TextSearchObjectType, TriggerObjectKind, Truncate,
93    UserDefinedTypeCompositeAttributeDef, UserDefinedTypeInternalLength,
94    UserDefinedTypeRangeOption, UserDefinedTypeRepresentation, UserDefinedTypeSqlDefinitionOption,
95    UserDefinedTypeStorage, UserMappingUser, ViewColumnDef, WithData,
96};
97pub use self::dml::{
98    Delete, Insert, InsertOverriding, Merge, MergeAction, MergeClause, MergeClauseKind,
99    MergeInsertExpr, MergeInsertKind, MergeUpdateExpr, MergeUpdateKind, MultiTableInsertIntoClause,
100    MultiTableInsertType, MultiTableInsertValue, MultiTableInsertValues,
101    MultiTableInsertWhenClause, OutputClause, Update,
102};
103pub use self::operator::{BinaryOperator, UnaryOperator};
104pub use self::query::{
105    AfterMatchSkip, ConnectByKind, Cte, CteAsMaterialized, Distinct, EmptyMatchesMode,
106    ExceptSelectItem, ExcludeSelectItem, ExprWithAlias, ExprWithAliasAndOrderBy, Fetch, ForClause,
107    ForJson, ForXml, FormatClause, GroupByExpr, GroupByWithModifier, IdentWithAlias,
108    IlikeSelectItem, InputFormatClause, Interpolate, InterpolateExpr, Join, JoinConstraint,
109    JoinOperator, JsonTableColumn, JsonTableColumnErrorHandling, JsonTableNamedColumn,
110    JsonTableNestedColumn, LateralView, LimitClause, LockClause, LockType, MatchRecognizePattern,
111    MatchRecognizeSymbol, Measure, NamedWindowDefinition, NamedWindowExpr, NonBlock, Offset,
112    OffsetRows, OpenJsonTableColumn, OrderBy, OrderByExpr, OrderByKind, OrderByOptions,
113    OrderBySort, PipeOperator, PivotValueSource, ProjectionSelect, Query, RenameSelectItem,
114    RepetitionQuantifier, ReplaceSelectElement, ReplaceSelectItem, RowsPerMatch, Select,
115    SelectFlavor, SelectInto, SelectItem, SelectItemQualifiedWildcardKind, SelectModifiers,
116    SetExpr, SetOperator, SetQuantifier, Setting, SymbolDefinition, Table, TableAlias,
117    TableAliasColumnDef, TableFactor, TableFunctionArgs, TableIndexDirective,
118    TableIndexHintForClause, TableIndexHintType, TableIndexHints, TableIndexType, TableInheritance,
119    TableSample, TableSampleBucket, TableSampleKind, TableSampleMethod, TableSampleModifier,
120    TableSampleQuantity, TableSampleSeed, TableSampleSeedModifier, TableSampleUnit, TableVersion,
121    TableWithJoins, Top, TopQuantity, UpdateTableFromKind, ValueTableMode, Values,
122    WildcardAdditionalOptions, With, WithFill, XmlNamespaceDefinition, XmlPassingArgument,
123    XmlPassingClause, XmlTableColumn, XmlTableColumnOption,
124};
125
126pub use self::trigger::{
127    TriggerEvent, TriggerExecBody, TriggerExecBodyType, TriggerObject, TriggerPeriod,
128    TriggerReferencing, TriggerReferencingType,
129};
130
131pub use self::value::{
132    escape_double_quote_string, escape_quoted_string, DateTimeField, DollarQuotedString,
133    NormalizationForm, QuoteDelimitedString, TrimWhereField, Value, ValueWithSpan,
134};
135
136use crate::ast::helpers::key_value_options::KeyValueOptions;
137use crate::ast::helpers::stmt_data_loading::StageParamsObject;
138
139#[cfg(feature = "visitor")]
140pub use visitor::*;
141
142pub use self::data_type::GeometricTypeKind;
143
144mod data_type;
145mod dcl;
146mod ddl;
147mod dml;
148/// Helper modules for building and manipulating AST nodes.
149pub mod helpers;
150pub mod table_constraints;
151pub use table_constraints::{
152    CheckConstraint, ConstraintUsingIndex, ExcludeConstraint, ExcludeConstraintElement,
153    ExcludeConstraintOperator, ForeignKeyConstraint, FullTextOrSpatialConstraint, IndexConstraint,
154    PrimaryKeyConstraint, TableConstraint, UniqueConstraint,
155};
156mod operator;
157mod query;
158mod spans;
159pub use spans::Spanned;
160
161pub mod comments;
162mod trigger;
163mod value;
164
165#[cfg(feature = "visitor")]
166mod visitor;
167
168/// Helper used to format a slice using a separator string (e.g., `", "`).
169pub struct DisplaySeparated<'a, T>
170where
171    T: fmt::Display,
172{
173    slice: &'a [T],
174    sep: &'static str,
175}
176
177impl<T> fmt::Display for DisplaySeparated<'_, T>
178where
179    T: fmt::Display,
180{
181    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
182        let mut delim = "";
183        for t in self.slice {
184            f.write_str(delim)?;
185            delim = self.sep;
186            t.fmt(f)?;
187        }
188        Ok(())
189    }
190}
191
192pub(crate) fn display_separated<'a, T>(slice: &'a [T], sep: &'static str) -> DisplaySeparated<'a, T>
193where
194    T: fmt::Display,
195{
196    DisplaySeparated { slice, sep }
197}
198
199pub(crate) fn display_comma_separated<T>(slice: &[T]) -> DisplaySeparated<'_, T>
200where
201    T: fmt::Display,
202{
203    DisplaySeparated { slice, sep: ", " }
204}
205
206/// Writes the given statements to the formatter, each ending with
207/// a semicolon and space separated.
208fn format_statement_list(f: &mut fmt::Formatter, statements: &[Statement]) -> fmt::Result {
209    write!(f, "{}", display_separated(statements, "; "))?;
210    // We manually insert semicolon for the last statement,
211    // since display_separated doesn't handle that case.
212    write!(f, ";")
213}
214
215/// Writes ` BEGIN ATOMIC <statements> END`.
216fn format_begin_atomic(f: &mut fmt::Formatter, statements: &[Statement]) -> fmt::Result {
217    write!(f, " BEGIN ATOMIC")?;
218    if !statements.is_empty() {
219        write!(f, " ")?;
220        format_statement_list(f, statements)?;
221    }
222    write!(f, " END")
223}
224
225/// A item `T` enclosed in a pair of parentheses
226#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
227#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
228#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
229pub struct Parens<T> {
230    /// the opening parenthesis token, i.e. `(`
231    pub opening_token: AttachedToken,
232    /// content enclosed in parentheses
233    pub content: T,
234    /// the closing parenthesis token, i.e. `)`
235    pub closing_token: AttachedToken,
236}
237
238impl<T> Parens<T> {
239    /// Constructor wrapping `content` into `Parens` with an empty span;
240    /// useful for testing purposes.
241    pub fn with_empty_span(content: T) -> Self {
242        Self {
243            opening_token: AttachedToken::empty(),
244            content,
245            closing_token: AttachedToken::empty(),
246        }
247    }
248}
249
250impl<T> Deref for Parens<T> {
251    type Target = T;
252
253    fn deref(&self) -> &Self::Target {
254        &self.content
255    }
256}
257
258impl<T> DerefMut for Parens<T> {
259    fn deref_mut(&mut self) -> &mut Self::Target {
260        &mut self.content
261    }
262}
263
264/// An identifier, decomposed into its value or character data and the quote style.
265#[derive(Debug, Clone)]
266#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
267pub struct Ident {
268    /// The value of the identifier without quotes.
269    pub value: String,
270    /// The starting quote if any. Valid quote characters are the single quote,
271    /// double quote, backtick, and opening square bracket.
272    pub quote_style: Option<char>,
273    /// The span of the identifier in the original SQL string.
274    pub span: Span,
275}
276
277impl PartialEq for Ident {
278    fn eq(&self, other: &Self) -> bool {
279        let Ident {
280            value,
281            quote_style,
282            // exhaustiveness check; we ignore spans in comparisons
283            span: _,
284        } = self;
285
286        value == &other.value && quote_style == &other.quote_style
287    }
288}
289
290impl core::hash::Hash for Ident {
291    fn hash<H: hash::Hasher>(&self, state: &mut H) {
292        let Ident {
293            value,
294            quote_style,
295            // exhaustiveness check; we ignore spans in hashes
296            span: _,
297        } = self;
298
299        value.hash(state);
300        quote_style.hash(state);
301    }
302}
303
304impl Eq for Ident {}
305
306impl PartialOrd for Ident {
307    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
308        Some(self.cmp(other))
309    }
310}
311
312impl Ord for Ident {
313    fn cmp(&self, other: &Self) -> Ordering {
314        let Ident {
315            value,
316            quote_style,
317            // exhaustiveness check; we ignore spans in ordering
318            span: _,
319        } = self;
320
321        let Ident {
322            value: other_value,
323            quote_style: other_quote_style,
324            // exhaustiveness check; we ignore spans in ordering
325            span: _,
326        } = other;
327
328        // First compare by value, then by quote_style
329        value
330            .cmp(other_value)
331            .then_with(|| quote_style.cmp(other_quote_style))
332    }
333}
334
335impl Ident {
336    /// Create a new identifier with the given value and no quotes and an empty span.
337    pub fn new<S>(value: S) -> Self
338    where
339        S: Into<String>,
340    {
341        Ident {
342            value: value.into(),
343            quote_style: None,
344            span: Span::empty(),
345        }
346    }
347
348    /// Create a new quoted identifier with the given quote and value. This function
349    /// panics if the given quote is not a valid quote character.
350    pub fn with_quote<S>(quote: char, value: S) -> Self
351    where
352        S: Into<String>,
353    {
354        assert!(quote == '\'' || quote == '"' || quote == '`' || quote == '[');
355        Ident {
356            value: value.into(),
357            quote_style: Some(quote),
358            span: Span::empty(),
359        }
360    }
361
362    /// Create an `Ident` with the given `span` and `value` (unquoted).
363    pub fn with_span<S>(span: Span, value: S) -> Self
364    where
365        S: Into<String>,
366    {
367        Ident {
368            value: value.into(),
369            quote_style: None,
370            span,
371        }
372    }
373
374    /// Create a quoted `Ident` with the given `quote` and `span`.
375    pub fn with_quote_and_span<S>(quote: char, span: Span, value: S) -> Self
376    where
377        S: Into<String>,
378    {
379        assert!(quote == '\'' || quote == '"' || quote == '`' || quote == '[');
380        Ident {
381            value: value.into(),
382            quote_style: Some(quote),
383            span,
384        }
385    }
386}
387
388impl From<&str> for Ident {
389    fn from(value: &str) -> Self {
390        Ident {
391            value: value.to_string(),
392            quote_style: None,
393            span: Span::empty(),
394        }
395    }
396}
397
398pub(crate) fn fmt_ident(
399    f: &mut fmt::Formatter,
400    value: &str,
401    quote_style: Option<char>,
402) -> fmt::Result {
403    match quote_style {
404        Some('[') => write!(f, "[{value}]"),
405        Some(q) => {
406            let escaped = value::escape_quoted_string(value, q);
407            write!(f, "{q}{escaped}{q}")
408        }
409        None => f.write_str(value),
410    }
411}
412
413impl fmt::Display for Ident {
414    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
415        fmt_ident(f, &self.value, self.quote_style)
416    }
417}
418
419#[cfg(feature = "visitor")]
420impl Visit for Ident {
421    fn visit<V: Visitor>(&self, visitor: &mut V) -> ControlFlow<V::Break> {
422        visitor.pre_visit_ident(self)?;
423        visitor.post_visit_ident(self)
424    }
425}
426
427#[cfg(feature = "visitor")]
428impl VisitMut for Ident {
429    fn visit<V: VisitorMut>(&mut self, visitor: &mut V) -> ControlFlow<V::Break> {
430        visitor.pre_visit_ident(self)?;
431        visitor.post_visit_ident(self)
432    }
433}
434
435/// A name of a table, view, custom type, etc., possibly multi-part, i.e. db.schema.obj
436#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
437#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
438#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
439pub struct ObjectName(pub Vec<ObjectNamePart>);
440
441impl From<Vec<Ident>> for ObjectName {
442    fn from(idents: Vec<Ident>) -> Self {
443        ObjectName(idents.into_iter().map(ObjectNamePart::Identifier).collect())
444    }
445}
446
447impl From<Ident> for ObjectName {
448    fn from(ident: Ident) -> Self {
449        ObjectName(vec![ObjectNamePart::Identifier(ident)])
450    }
451}
452
453impl fmt::Display for ObjectName {
454    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
455        write!(f, "{}", display_separated(&self.0, "."))
456    }
457}
458
459/// A single part of an ObjectName
460#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
461#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
462#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
463pub enum ObjectNamePart {
464    /// A single identifier part, e.g. `schema` or `table`.
465    Identifier(Ident),
466    /// A function that returns an identifier (dialect-specific).
467    Function(ObjectNamePartFunction),
468}
469
470impl ObjectNamePart {
471    /// Return the identifier if this is an `Identifier` variant.
472    pub fn as_ident(&self) -> Option<&Ident> {
473        match self {
474            ObjectNamePart::Identifier(ident) => Some(ident),
475            ObjectNamePart::Function(_) => None,
476        }
477    }
478}
479
480impl fmt::Display for ObjectNamePart {
481    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
482        match self {
483            ObjectNamePart::Identifier(ident) => write!(f, "{ident}"),
484            ObjectNamePart::Function(func) => write!(f, "{func}"),
485        }
486    }
487}
488
489/// An object name part that consists of a function that dynamically
490/// constructs identifiers.
491///
492/// - [Snowflake](https://docs.snowflake.com/en/sql-reference/identifier-literal)
493#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
494#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
495#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
496pub struct ObjectNamePartFunction {
497    /// The function name that produces the object name part.
498    pub name: Ident,
499    /// Function arguments used to compute the identifier.
500    pub args: Vec<FunctionArg>,
501}
502
503impl fmt::Display for ObjectNamePartFunction {
504    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
505        write!(f, "{}(", self.name)?;
506        write!(f, "{})", display_comma_separated(&self.args))
507    }
508}
509
510/// Represents an Array Expression, either
511/// `ARRAY[..]`, or `[..]`
512#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
513#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
514#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
515pub struct Array {
516    /// The list of expressions between brackets
517    pub elem: Vec<Expr>,
518
519    /// `true` for  `ARRAY[..]`, `false` for `[..]`
520    pub named: bool,
521}
522
523impl fmt::Display for Array {
524    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
525        write!(
526            f,
527            "{}[{}]",
528            if self.named { "ARRAY" } else { "" },
529            display_comma_separated(&self.elem)
530        )
531    }
532}
533
534/// Represents an INTERVAL expression, roughly in the following format:
535/// `INTERVAL '<value>' [ <leading_field> [ (<leading_precision>) ] ]
536/// [ TO <last_field> [ (<fractional_seconds_precision>) ] ]`,
537/// e.g. `INTERVAL '123:45.67' MINUTE(3) TO SECOND(2)`.
538///
539/// The parser does not validate the `<value>`, nor does it ensure
540/// that the `<leading_field>` units >= the units in `<last_field>`,
541/// so the user will have to reject intervals like `HOUR TO YEAR`.
542#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
543#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
544#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
545pub struct Interval {
546    /// The interval value expression (commonly a string literal).
547    pub value: Box<Expr>,
548    /// Optional leading time unit (e.g., `HOUR`, `MINUTE`).
549    pub leading_field: Option<DateTimeField>,
550    /// Optional leading precision for the leading field.
551    pub leading_precision: Option<u64>,
552    /// Optional trailing time unit for a range (e.g., `SECOND`).
553    pub last_field: Option<DateTimeField>,
554    /// The fractional seconds precision, when specified.
555    ///
556    /// See SQL `SECOND(n)` or `SECOND(m, n)` forms.
557    pub fractional_seconds_precision: Option<u64>,
558}
559
560impl fmt::Display for Interval {
561    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
562        let value = self.value.as_ref();
563        match (
564            &self.leading_field,
565            self.leading_precision,
566            self.fractional_seconds_precision,
567        ) {
568            (
569                Some(DateTimeField::Second),
570                Some(leading_precision),
571                Some(fractional_seconds_precision),
572            ) => {
573                // When the leading field is SECOND, the parser guarantees that
574                // the last field is None.
575                assert!(self.last_field.is_none());
576                write!(
577                    f,
578                    "INTERVAL {value} SECOND ({leading_precision}, {fractional_seconds_precision})"
579                )
580            }
581            _ => {
582                write!(f, "INTERVAL {value}")?;
583                if let Some(leading_field) = &self.leading_field {
584                    write!(f, " {leading_field}")?;
585                }
586                if let Some(leading_precision) = self.leading_precision {
587                    write!(f, " ({leading_precision})")?;
588                }
589                if let Some(last_field) = &self.last_field {
590                    write!(f, " TO {last_field}")?;
591                }
592                if let Some(fractional_seconds_precision) = self.fractional_seconds_precision {
593                    write!(f, " ({fractional_seconds_precision})")?;
594                }
595                Ok(())
596            }
597        }
598    }
599}
600
601/// A field definition within a struct
602///
603/// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#struct_type
604#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
605#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
606#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
607pub struct StructField {
608    /// Optional name of the struct field.
609    pub field_name: Option<Ident>,
610    /// The field data type.
611    pub field_type: DataType,
612    /// Struct field options (e.g., `OPTIONS(...)` on BigQuery).
613    /// See [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#column_name_and_column_schema)
614    pub options: Option<Vec<SqlOption>>,
615}
616
617impl fmt::Display for StructField {
618    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
619        if let Some(name) = &self.field_name {
620            write!(f, "{name} {}", self.field_type)?;
621        } else {
622            write!(f, "{}", self.field_type)?;
623        }
624        if let Some(options) = &self.options {
625            write!(f, " OPTIONS({})", display_separated(options, ", "))
626        } else {
627            Ok(())
628        }
629    }
630}
631
632/// A field definition within a union
633///
634/// [DuckDB]: https://duckdb.org/docs/sql/data_types/union.html
635#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
636#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
637#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
638pub struct UnionField {
639    /// Name of the union field.
640    pub field_name: Ident,
641    /// Type of the union field.
642    pub field_type: DataType,
643}
644
645impl fmt::Display for UnionField {
646    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
647        write!(f, "{} {}", self.field_name, self.field_type)
648    }
649}
650
651/// A dictionary field within a dictionary.
652///
653/// [DuckDB]: https://duckdb.org/docs/sql/data_types/struct#creating-structs
654#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
655#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
656#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
657pub struct DictionaryField {
658    /// Dictionary key identifier.
659    pub key: Ident,
660    /// Value expression for the dictionary entry.
661    pub value: Box<Expr>,
662}
663
664impl fmt::Display for DictionaryField {
665    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
666        write!(f, "{}: {}", self.key, self.value)
667    }
668}
669
670/// Represents a Map expression.
671#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
672#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
673#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
674pub struct Map {
675    /// Entries of the map as key/value pairs.
676    pub entries: Vec<MapEntry>,
677}
678
679impl Display for Map {
680    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
681        write!(f, "MAP {{{}}}", display_comma_separated(&self.entries))
682    }
683}
684
685/// A map field within a map.
686///
687/// [DuckDB]: https://duckdb.org/docs/sql/data_types/map.html#creating-maps
688#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
689#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
690#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
691pub struct MapEntry {
692    /// Key expression of the map entry.
693    pub key: Box<Expr>,
694    /// Value expression of the map entry.
695    pub value: Box<Expr>,
696}
697
698impl fmt::Display for MapEntry {
699    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
700        write!(f, "{}: {}", self.key, self.value)
701    }
702}
703
704/// Options for `CAST` / `TRY_CAST`
705/// BigQuery: <https://cloud.google.com/bigquery/docs/reference/standard-sql/format-elements#formatting_syntax>
706#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
707#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
708#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
709pub enum CastFormat {
710    /// A simple cast format specified by a `Value`.
711    Value(ValueWithSpan),
712    /// A cast format with an explicit time zone: `(format, timezone)`.
713    ValueAtTimeZone(ValueWithSpan, ValueWithSpan),
714}
715
716/// An element of a JSON path.
717#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
718#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
719#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
720pub enum JsonPathElem {
721    /// Accesses an object field using dot notation, e.g. `obj:foo.bar.baz`.
722    ///
723    /// See <https://docs.snowflake.com/en/user-guide/querying-semistructured#dot-notation>.
724    Dot {
725        /// The object key text (without quotes).
726        key: String,
727        /// `true` when the key was quoted in the source.
728        quoted: bool,
729    },
730    /// Accesses an object field or array element using bracket notation,
731    /// e.g. `obj['foo']`.
732    ///
733    /// See <https://docs.snowflake.com/en/user-guide/querying-semistructured#bracket-notation>.
734    Bracket {
735        /// The expression used as the bracket key (string or numeric expression).
736        key: Expr,
737    },
738    /// Access an object field using colon bracket notation
739    /// e.g. `obj:['foo']`
740    ///
741    /// See <https://docs.databricks.com/en/sql/language-manual/functions/colonsign.html>
742    ColonBracket {
743        /// The expression used as the bracket key (string or numeric expression).
744        key: Expr,
745    },
746}
747
748/// A JSON path.
749///
750/// See <https://docs.snowflake.com/en/user-guide/querying-semistructured>.
751/// See <https://docs.databricks.com/en/sql/language-manual/sql-ref-json-path-expression.html>.
752#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
753#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
754#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
755pub struct JsonPath {
756    /// Sequence of path elements that form the JSON path.
757    pub path: Vec<JsonPathElem>,
758}
759
760impl fmt::Display for JsonPath {
761    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
762        for (i, elem) in self.path.iter().enumerate() {
763            match elem {
764                JsonPathElem::Dot { key, quoted } => {
765                    if i == 0 {
766                        write!(f, ":")?;
767                    } else {
768                        write!(f, ".")?;
769                    }
770
771                    if *quoted {
772                        write!(f, "\"{}\"", escape_double_quote_string(key))?;
773                    } else {
774                        write!(f, "{key}")?;
775                    }
776                }
777                JsonPathElem::Bracket { key } => {
778                    write!(f, "[{key}]")?;
779                }
780                JsonPathElem::ColonBracket { key } => {
781                    write!(f, ":[{key}]")?;
782                }
783            }
784        }
785        Ok(())
786    }
787}
788
789/// The syntax used for in a cast expression.
790#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
791#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
792#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
793pub enum CastKind {
794    /// The standard SQL cast syntax, e.g. `CAST(<expr> as <datatype>)`
795    Cast,
796    /// A cast that returns `NULL` on failure, e.g. `TRY_CAST(<expr> as <datatype>)`.
797    ///
798    /// See <https://docs.snowflake.com/en/sql-reference/functions/try_cast>.
799    /// See <https://learn.microsoft.com/en-us/sql/t-sql/functions/try-cast-transact-sql>.
800    TryCast,
801    /// A cast that returns `NULL` on failure, bigQuery-specific ,  e.g. `SAFE_CAST(<expr> as <datatype>)`.
802    ///
803    /// See <https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#safe_casting>.
804    SafeCast,
805    /// `<expr> :: <datatype>`
806    DoubleColon,
807}
808
809/// `MATCH` type for constraint references
810///
811/// See: <https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-PARMS-REFERENCES>
812#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
813#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
814#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
815pub enum ConstraintReferenceMatchKind {
816    /// `MATCH FULL`
817    Full,
818    /// `MATCH PARTIAL`
819    Partial,
820    /// `MATCH SIMPLE`
821    Simple,
822}
823
824impl fmt::Display for ConstraintReferenceMatchKind {
825    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
826        match self {
827            Self::Full => write!(f, "MATCH FULL"),
828            Self::Partial => write!(f, "MATCH PARTIAL"),
829            Self::Simple => write!(f, "MATCH SIMPLE"),
830        }
831    }
832}
833
834/// `EXTRACT` syntax variants.
835///
836/// In Snowflake dialect, the `EXTRACT` expression can support either the `from` syntax
837/// or the comma syntax.
838///
839/// See <https://docs.snowflake.com/en/sql-reference/functions/extract>
840#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
841#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
842#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
843pub enum ExtractSyntax {
844    /// `EXTRACT( <date_or_time_part> FROM <date_or_time_expr> )`
845    From,
846    /// `EXTRACT( <date_or_time_part> , <date_or_timestamp_expr> )`
847    Comma,
848}
849
850/// The syntax used in a CEIL or FLOOR expression.
851///
852/// The `CEIL/FLOOR(<datetime value expression> TO <time unit>)` is an Amazon Kinesis Data Analytics extension.
853/// See <https://docs.aws.amazon.com/kinesisanalytics/latest/sqlref/sql-reference-ceil.html> for
854/// details.
855///
856/// Other dialects either support `CEIL/FLOOR( <expr> [, <scale>])` format or just
857/// `CEIL/FLOOR(<expr>)`.
858#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
859#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
860#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
861pub enum CeilFloorKind {
862    /// `CEIL( <expr> TO <DateTimeField>)`
863    DateTimeField(DateTimeField),
864    /// `CEIL( <expr> [, <scale>])`
865    Scale(ValueWithSpan),
866}
867
868/// A WHEN clause in a CASE expression containing both
869/// the condition and its corresponding result
870#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
871#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
872#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
873pub struct CaseWhen {
874    /// The `WHEN` condition expression.
875    pub condition: Expr,
876    /// The expression returned when `condition` matches.
877    pub result: Expr,
878}
879
880impl fmt::Display for CaseWhen {
881    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
882        f.write_str("WHEN ")?;
883        self.condition.fmt(f)?;
884        f.write_str(" THEN")?;
885        SpaceOrNewline.fmt(f)?;
886        Indent(&self.result).fmt(f)?;
887        Ok(())
888    }
889}
890
891/// The right-hand side of an `IN` predicate, see [`Expr::In`].
892#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
893#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
894#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
895pub enum InTarget {
896    /// `(val1, val2, ...)`
897    List(Vec<Expr>),
898    /// `(SELECT ...)`
899    Subquery(Box<Query>),
900    /// `UNNEST(array_expression)`, see
901    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/operators#in_operators)
902    Unnest(Box<Expr>),
903    /// A table name or table-valued function, read as `(SELECT * FROM name)`, see
904    /// [SQLite](https://www.sqlite.org/lang_expr.html#in_op)
905    Table {
906        #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
907        /// Table or table-valued function name, visited as a relation.
908        name: ObjectName,
909        /// Table-valued function arguments, `None` for a plain table name.
910        args: Option<Vec<FunctionArg>>,
911    },
912}
913
914impl fmt::Display for InTarget {
915    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
916        match self {
917            InTarget::List(list) => write!(f, "({})", display_comma_separated(list)),
918            InTarget::Subquery(subquery) => write!(f, "({subquery})"),
919            InTarget::Unnest(array_expr) => write!(f, "UNNEST({array_expr})"),
920            InTarget::Table { name, args } => {
921                write!(f, "{name}")?;
922                if let Some(args) = args {
923                    write!(f, "({})", display_comma_separated(args))?;
924                }
925                Ok(())
926            }
927        }
928    }
929}
930
931/// An SQL expression of any type.
932///
933/// # Semantics / Type Checking
934///
935/// The parser does not distinguish between expressions of different types
936/// (e.g. boolean vs string). The caller is responsible for detecting and
937/// validating types as necessary (for example  `WHERE 1` vs `SELECT 1=1`)
938/// See the [README.md] for more details.
939///
940/// [README.md]: https://github.com/apache/datafusion-sqlparser-rs/blob/main/README.md#syntax-vs-semantics
941///
942/// # Equality and Hashing Does not Include Source Locations
943///
944/// The `Expr` type implements `PartialEq` and `Eq` based on the semantic value
945/// of the expression (not bitwise comparison). This means that `Expr` instances
946/// that are semantically equivalent but have different spans (locations in the
947/// source tree) will compare as equal.
948#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
949#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
950#[cfg_attr(
951    feature = "visitor",
952    derive(Visit, VisitMut),
953    visit(with = "visit_expr")
954)]
955pub enum Expr {
956    /// Identifier e.g. table name or column name
957    Identifier(Ident),
958    /// Multi-part identifier, e.g. `table_alias.column` or `schema.table.col`
959    CompoundIdentifier(Vec<Ident>),
960    /// Multi-part expression access.
961    ///
962    /// This structure represents an access chain in structured / nested types
963    /// such as maps, arrays, and lists:
964    /// - Array
965    ///     - A 1-dim array `a[1]` will be represented like:
966    ///       `CompoundFieldAccess(Ident('a'), vec![Subscript(1)]`
967    ///     - A 2-dim array `a[1][2]` will be represented like:
968    ///       `CompoundFieldAccess(Ident('a'), vec![Subscript(1), Subscript(2)]`
969    /// - Map or Struct (Bracket-style)
970    ///     - A map `a['field1']` will be represented like:
971    ///       `CompoundFieldAccess(Ident('a'), vec![Subscript('field')]`
972    ///     - A 2-dim map `a['field1']['field2']` will be represented like:
973    ///       `CompoundFieldAccess(Ident('a'), vec![Subscript('field1'), Subscript('field2')]`
974    /// - Struct (Dot-style) (only effect when the chain contains both subscript and expr)
975    ///     - A struct access `a[field1].field2` will be represented like:
976    ///       `CompoundFieldAccess(Ident('a'), vec![Subscript('field1'), Ident('field2')]`
977    /// - If a struct access likes `a.field1.field2`, it will be represented by CompoundIdentifier([a, field1, field2])
978    CompoundFieldAccess {
979        /// The base expression being accessed.
980        root: Box<Expr>,
981        /// Sequence of access operations (subscript or identifier accesses).
982        access_chain: Vec<AccessExpr>,
983    },
984    /// Access data nested in a value containing semi-structured data, such as
985    /// the `VARIANT` type on Snowflake. for example `src:customer[0].name`.
986    ///
987    /// See <https://docs.snowflake.com/en/user-guide/querying-semistructured>.
988    /// See <https://docs.databricks.com/en/sql/language-manual/functions/colonsign.html>.
989    JsonAccess {
990        /// The value being queried.
991        value: Box<Expr>,
992        /// The path to the data to extract.
993        path: JsonPath,
994    },
995    /// `IS FALSE` operator
996    IsFalse(Box<Expr>),
997    /// `IS NOT FALSE` operator
998    IsNotFalse(Box<Expr>),
999    /// `IS TRUE` operator
1000    IsTrue(Box<Expr>),
1001    /// `IS NOT TRUE` operator
1002    IsNotTrue(Box<Expr>),
1003    /// `IS NULL` operator
1004    IsNull(Box<Expr>),
1005    /// `IS NOT NULL` operator
1006    IsNotNull(Box<Expr>),
1007    /// `IS UNKNOWN` operator
1008    IsUnknown(Box<Expr>),
1009    /// `IS NOT UNKNOWN` operator
1010    IsNotUnknown(Box<Expr>),
1011    /// `IS DISTINCT FROM` operator
1012    IsDistinctFrom(Box<Expr>, Box<Expr>),
1013    /// `IS NOT DISTINCT FROM` operator
1014    IsNotDistinctFrom(Box<Expr>, Box<Expr>),
1015    /// `<expr> IS [NOT] JSON [VALUE|SCALAR|ARRAY|OBJECT] [WITH|WITHOUT UNIQUE [KEYS]]`
1016    IsJson {
1017        /// Expression being tested.
1018        expr: Box<Expr>,
1019        /// Optional JSON shape constraint.
1020        kind: Option<JsonPredicateType>,
1021        /// Optional duplicate-key handling constraint for JSON objects.
1022        unique_keys: Option<JsonKeyUniqueness>,
1023        /// `true` when `NOT` is present.
1024        negated: bool,
1025    },
1026    /// `<expr> IS [ NOT ] [ form ] NORMALIZED`
1027    IsNormalized {
1028        /// Expression being tested.
1029        expr: Box<Expr>,
1030        /// Optional normalization `form` (e.g., NFC, NFD).
1031        form: Option<NormalizationForm>,
1032        /// `true` when `NOT` is present.
1033        negated: bool,
1034    },
1035    /// `<expr> [ GLOBAL ] [ NOT ] IN <target>`
1036    In {
1037        /// Left-hand expression to test for membership.
1038        expr: Box<Expr>,
1039        /// What `expr` is tested against.
1040        target: InTarget,
1041        /// `true` when the `NOT` modifier is present.
1042        negated: bool,
1043        /// `true` when the ClickHouse `GLOBAL` modifier is present.
1044        global: bool,
1045    },
1046    /// `<expr> [ NOT ] BETWEEN <low> AND <high>`
1047    Between {
1048        /// Expression being compared.
1049        expr: Box<Expr>,
1050        /// `true` when the `NOT` modifier is present.
1051        negated: bool,
1052        /// Lower bound.
1053        low: Box<Expr>,
1054        /// Upper bound.
1055        high: Box<Expr>,
1056    },
1057    /// Binary operation e.g. `1 + 1` or `foo > bar`
1058    BinaryOp {
1059        /// Left operand.
1060        left: Box<Expr>,
1061        /// Operator between operands.
1062        op: BinaryOperator,
1063        /// Right operand.
1064        right: Box<Expr>,
1065    },
1066    /// `[NOT] LIKE <pattern> [ESCAPE <escape_character>]`
1067    Like {
1068        /// `true` when `NOT` is present.
1069        negated: bool,
1070        /// Snowflake supports the ANY keyword to match against a list of patterns
1071        /// <https://docs.snowflake.com/en/sql-reference/functions/like_any>
1072        any: bool,
1073        /// Expression to match.
1074        expr: Box<Expr>,
1075        /// Pattern expression.
1076        pattern: Box<Expr>,
1077        /// Optional escape character.
1078        escape_char: Option<Box<Expr>>,
1079    },
1080    /// `ILIKE` (case-insensitive `LIKE`)
1081    ILike {
1082        /// `true` when `NOT` is present.
1083        negated: bool,
1084        /// Snowflake supports the ANY keyword to match against a list of patterns
1085        /// <https://docs.snowflake.com/en/sql-reference/functions/like_any>
1086        any: bool,
1087        /// Expression to match.
1088        expr: Box<Expr>,
1089        /// Pattern expression.
1090        pattern: Box<Expr>,
1091        /// Optional escape character.
1092        escape_char: Option<Box<Expr>>,
1093    },
1094    /// `SIMILAR TO` regex
1095    SimilarTo {
1096        /// `true` when `NOT` is present.
1097        negated: bool,
1098        /// Expression to test.
1099        expr: Box<Expr>,
1100        /// Pattern expression.
1101        pattern: Box<Expr>,
1102        /// Optional escape character.
1103        escape_char: Option<Box<Expr>>,
1104    },
1105    /// MySQL: `RLIKE` regex or `REGEXP` regex
1106    RLike {
1107        /// `true` when `NOT` is present.
1108        negated: bool,
1109        /// Expression to test.
1110        expr: Box<Expr>,
1111        /// Pattern expression.
1112        pattern: Box<Expr>,
1113        /// true for REGEXP, false for RLIKE (no difference in semantics)
1114        regexp: bool,
1115    },
1116    /// `ANY` operation e.g. `foo > ANY(bar)`, comparison operator is one of `[=, >, <, =>, =<, !=]`
1117    /// <https://docs.snowflake.com/en/sql-reference/operators-subquery#all-any>
1118    AnyOp {
1119        /// Left operand.
1120        left: Box<Expr>,
1121        /// Comparison operator.
1122        compare_op: BinaryOperator,
1123        /// Right-hand subquery expression.
1124        right: Box<Expr>,
1125        /// ANY and SOME are synonymous: <https://docs.cloudera.com/cdw-runtime/cloud/using-hiveql/topics/hive_comparison_predicates.html>
1126        is_some: bool,
1127    },
1128    /// `ALL` operation e.g. `foo > ALL(bar)`, comparison operator is one of `[=, >, <, =>, =<, !=]`
1129    /// <https://docs.snowflake.com/en/sql-reference/operators-subquery#all-any>
1130    AllOp {
1131        /// Left operand.
1132        left: Box<Expr>,
1133        /// Comparison operator.
1134        compare_op: BinaryOperator,
1135        /// Right-hand subquery expression.
1136        right: Box<Expr>,
1137    },
1138
1139    /// Unary operation e.g. `NOT foo`
1140    UnaryOp {
1141        /// The unary operator (e.g., `NOT`, `-`).
1142        op: UnaryOperator,
1143        /// Operand expression.
1144        expr: Box<Expr>,
1145    },
1146    /// CONVERT a value to a different data type or character encoding. e.g. `CONVERT(foo USING utf8mb4)`
1147    Convert {
1148        /// CONVERT (false) or TRY_CONVERT (true)
1149        /// <https://learn.microsoft.com/en-us/sql/t-sql/functions/try-convert-transact-sql?view=sql-server-ver16>
1150        is_try: bool,
1151        /// The expression to convert.
1152        expr: Box<Expr>,
1153        /// The target data type, if provided.
1154        data_type: Option<DataType>,
1155        /// Optional target character encoding (e.g., `utf8mb4`).
1156        charset: Option<ObjectName>,
1157        /// `true` when target precedes the value (MSSQL syntax).
1158        target_before_value: bool,
1159        /// How to translate the expression.
1160        ///
1161        /// [MSSQL]: https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16#style
1162        styles: Vec<Expr>,
1163    },
1164    /// `CAST` an expression to a different data type e.g. `CAST(foo AS VARCHAR(123))`
1165    Cast {
1166        /// The cast kind (e.g., `CAST`, `TRY_CAST`).
1167        kind: CastKind,
1168        /// Expression being cast.
1169        expr: Box<Expr>,
1170        /// Target data type.
1171        data_type: DataType,
1172        /// Optional CAST(string_expression AS type FORMAT format_string_expression) as used by [BigQuery]
1173        ///
1174        /// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/format-elements#formatting_syntax
1175        format: Option<CastFormat>,
1176    },
1177    /// AT a timestamp to a different timezone e.g. `FROM_UNIXTIME(0) AT TIME ZONE 'UTC-06:00'`
1178    AtTimeZone {
1179        /// Timestamp expression to shift.
1180        timestamp: Box<Expr>,
1181        /// Time zone expression to apply.
1182        time_zone: Box<Expr>,
1183    },
1184    /// Extract a field from a timestamp e.g. `EXTRACT(MONTH FROM foo)`
1185    /// Or `EXTRACT(MONTH, foo)`
1186    ///
1187    /// Syntax:
1188    /// ```sql
1189    /// EXTRACT(DateTimeField FROM <expr>) | EXTRACT(DateTimeField, <expr>)
1190    /// ```
1191    Extract {
1192        /// Which datetime field is being extracted.
1193        field: DateTimeField,
1194        /// Syntax variant used (`From` or `Comma`).
1195        syntax: ExtractSyntax,
1196        /// Expression to extract from.
1197        expr: Box<Expr>,
1198    },
1199    /// ```sql
1200    /// CEIL(<expr> [TO DateTimeField])
1201    /// ```
1202    /// ```sql
1203    /// CEIL( <input_expr> [, <scale_expr> ] )
1204    /// ```
1205    Ceil {
1206        /// Expression to ceil.
1207        expr: Box<Expr>,
1208        /// The CEIL/FLOOR kind (datetime field or scale).
1209        field: CeilFloorKind,
1210    },
1211    /// ```sql
1212    /// FLOOR(<expr> [TO DateTimeField])
1213    /// ```
1214    /// ```sql
1215    /// FLOOR( <input_expr> [, <scale_expr> ] )
1216    ///
1217    Floor {
1218        /// Expression to floor.
1219        expr: Box<Expr>,
1220        /// The CEIL/FLOOR kind (datetime field or scale).
1221        field: CeilFloorKind,
1222    },
1223    /// ```sql
1224    /// POSITION(<expr> in <expr>)
1225    /// ```
1226    Position {
1227        /// Expression to search for.
1228        expr: Box<Expr>,
1229        /// Expression to search in.
1230        r#in: Box<Expr>,
1231    },
1232    /// ```sql
1233    /// SUBSTRING(<expr> [FROM <expr>] [FOR <expr>])
1234    /// ```
1235    /// or
1236    /// ```sql
1237    /// SUBSTRING(<expr>, <expr>, <expr>)
1238    /// ```
1239    Substring {
1240        /// Source expression.
1241        expr: Box<Expr>,
1242        /// Optional `FROM` expression.
1243        substring_from: Option<Box<Expr>>,
1244        /// Optional `FOR` expression.
1245        substring_for: Option<Box<Expr>>,
1246
1247        /// false if the expression is represented using the `SUBSTRING(expr [FROM start] [FOR len])` syntax
1248        /// true if the expression is represented using the `SUBSTRING(expr, start, len)` syntax
1249        /// This flag is used for formatting.
1250        special: bool,
1251
1252        /// true if the expression is represented using the `SUBSTR` shorthand
1253        /// This flag is used for formatting.
1254        shorthand: bool,
1255    },
1256    /// ```sql
1257    /// TRIM([BOTH | LEADING | TRAILING] [<expr> FROM] <expr>)
1258    /// TRIM(<expr>)
1259    /// TRIM(<expr>, [, characters]) -- PostgreSQL, DuckDB, Snowflake, BigQuery, Generic
1260    /// ```
1261    Trim {
1262        /// Which side to trim: `BOTH`, `LEADING`, or `TRAILING`.
1263        trim_where: Option<TrimWhereField>,
1264        /// Optional expression specifying what to trim from the value `expr`.
1265        trim_what: Option<Box<Expr>>,
1266        /// The expression to trim from.
1267        expr: Box<Expr>,
1268        /// Optional list of characters to trim (dialect-specific).
1269        trim_characters: Option<Vec<Expr>>,
1270    },
1271    /// ```sql
1272    /// OVERLAY(<expr> PLACING <expr> FROM <expr>[ FOR <expr> ]
1273    /// ```
1274    Overlay {
1275        /// The target expression being overlayed.
1276        expr: Box<Expr>,
1277        /// The expression to place into the target.
1278        overlay_what: Box<Expr>,
1279        /// The `FROM` position expression indicating where to start overlay.
1280        overlay_from: Box<Expr>,
1281        /// Optional `FOR` length expression limiting the overlay span.
1282        overlay_for: Option<Box<Expr>>,
1283    },
1284    /// `expr COLLATE collation`
1285    Collate {
1286        /// The expression being collated.
1287        expr: Box<Expr>,
1288        /// The collation name to apply to the expression.
1289        collation: ObjectName,
1290    },
1291    /// Nested expression e.g. `(foo > bar)` or `(1)`
1292    Nested(Box<Expr>),
1293    /// A literal value, such as string, number, date or NULL
1294    Value(ValueWithSpan),
1295    /// Prefixed expression, e.g. introducer strings, projection prefix
1296    /// <https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html>
1297    /// <https://docs.snowflake.com/en/sql-reference/constructs/connect-by>
1298    Prefixed {
1299        /// The prefix identifier (introducer or projection prefix).
1300        prefix: Ident,
1301        /// The value expression being prefixed.
1302        /// Hint: you can unwrap the string value using `value.into_string()`.
1303        value: Box<Expr>,
1304    },
1305    /// A constant of form `<data_type> 'value'`.
1306    /// This can represent ANSI SQL `DATE`, `TIME`, and `TIMESTAMP` literals (such as `DATE '2020-01-01'`),
1307    /// as well as constants of other types (a non-standard PostgreSQL extension).
1308    TypedString(TypedString),
1309    /// Scalar function call e.g. `LEFT(foo, 5)`
1310    Function(Function),
1311    /// `CASE [<operand>] WHEN <condition> THEN <result> ... [ELSE <result>] END`
1312    ///
1313    /// Note we only recognize a complete single expression as `<condition>`,
1314    /// not `< 0` nor `1, 2, 3` as allowed in a `<simple when clause>` per
1315    /// <https://jakewheat.github.io/sql-overview/sql-2011-foundation-grammar.html#simple-when-clause>
1316    Case {
1317        /// The attached `CASE` token (keeps original spacing/comments).
1318        case_token: AttachedToken,
1319        /// The attached `END` token (keeps original spacing/comments).
1320        end_token: AttachedToken,
1321        /// Optional operand expression after `CASE` (for simple CASE).
1322        operand: Option<Box<Expr>>,
1323        /// The `WHEN ... THEN` conditions and results.
1324        conditions: Vec<CaseWhen>,
1325        /// Optional `ELSE` result expression.
1326        else_result: Option<Box<Expr>>,
1327    },
1328    /// An exists expression `[ NOT ] EXISTS(SELECT ...)`, used in expressions like
1329    /// `WHERE [ NOT ] EXISTS (SELECT ...)`.
1330    Exists {
1331        /// The subquery checked by `EXISTS`.
1332        subquery: Box<Query>,
1333        /// Whether the `EXISTS` is negated (`NOT EXISTS`).
1334        negated: bool,
1335    },
1336    /// A parenthesized subquery `(SELECT ...)`, used in expression like
1337    /// `SELECT (subquery) AS x` or `WHERE (subquery) = x`
1338    Subquery(Box<Query>),
1339    /// The `GROUPING SETS` expr.
1340    GroupingSets(Vec<Vec<Expr>>),
1341    /// The `CUBE` expr.
1342    Cube(Vec<Vec<Expr>>),
1343    /// The `ROLLUP` expr.
1344    Rollup(Vec<Vec<Expr>>),
1345    /// ROW / TUPLE a single value, such as `SELECT (1, 2)`
1346    Tuple(Vec<Expr>),
1347    /// `Struct` literal expression
1348    /// Syntax:
1349    /// ```sql
1350    /// STRUCT<[field_name] field_type, ...>( expr1 [, ... ])
1351    ///
1352    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#struct_type)
1353    /// [Databricks](https://docs.databricks.com/en/sql/language-manual/functions/struct.html)
1354    /// ```
1355    Struct {
1356        /// Struct values.
1357        values: Vec<Expr>,
1358        /// Struct field definitions.
1359        fields: Vec<StructField>,
1360    },
1361    /// A named expression: `1 AS A`. Used in `BigQuery` typeless structs [1]
1362    /// and in aliased function arguments, e.g. `XMLFOREST(a AS x)` in
1363    /// PostgreSQL [2].
1364    ///
1365    /// [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types#struct_type
1366    /// [2]: https://www.postgresql.org/docs/current/functions-xml.html#FUNCTIONS-PRODUCING-XML-XMLFOREST
1367    Named {
1368        /// The expression being named.
1369        expr: Box<Expr>,
1370        /// The assigned identifier name for the expression.
1371        name: Ident,
1372    },
1373    /// `DuckDB` specific `Struct` literal expression [1]
1374    ///
1375    /// Syntax:
1376    /// ```sql
1377    /// syntax: {'field_name': expr1[, ... ]}
1378    /// ```
1379    /// [1]: https://duckdb.org/docs/sql/data_types/struct#creating-structs
1380    Dictionary(Vec<DictionaryField>),
1381    /// `DuckDB` specific `Map` literal expression [1]
1382    ///
1383    /// Syntax:
1384    /// ```sql
1385    /// syntax: Map {key1: value1[, ... ]}
1386    /// ```
1387    /// [1]: https://duckdb.org/docs/sql/data_types/map#creating-maps
1388    Map(Map),
1389    /// An array expression e.g. `ARRAY[1, 2]`
1390    Array(Array),
1391    /// An interval expression e.g. `INTERVAL '1' YEAR`
1392    Interval(Interval),
1393    /// `MySQL` specific text search function [(1)].
1394    ///
1395    /// Syntax:
1396    /// ```sql
1397    /// MATCH (<col>, <col>, ...) AGAINST (<expr> [<search modifier>])
1398    ///
1399    /// <col> = CompoundIdentifier
1400    /// <expr> = String literal
1401    /// ```
1402    /// [(1)]: https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html#function_match
1403    MatchAgainst {
1404        /// `(<col>, <col>, ...)`.
1405        columns: Vec<ObjectName>,
1406        /// `<expr>`.
1407        match_value: ValueWithSpan,
1408        /// `<search modifier>`
1409        opt_search_modifier: Option<SearchModifier>,
1410    },
1411    /// An unqualified `*` wildcard token (e.g. `*`).
1412    Wildcard(AttachedToken),
1413    /// Qualified wildcard, e.g. `alias.*` or `schema.table.*`.
1414    /// (Same caveats apply to `QualifiedWildcard` as to `Wildcard`.)
1415    QualifiedWildcard(ObjectName, AttachedToken),
1416    /// Some dialects support an older syntax for outer joins where columns are
1417    /// marked with the `(+)` operator in the WHERE clause, for example:
1418    ///
1419    /// ```sql
1420    /// SELECT t1.c1, t2.c2 FROM t1, t2 WHERE t1.c1 = t2.c2 (+)
1421    /// ```
1422    ///
1423    /// which is equivalent to
1424    ///
1425    /// ```sql
1426    /// SELECT t1.c1, t2.c2 FROM t1 LEFT OUTER JOIN t2 ON t1.c1 = t2.c2
1427    /// ```
1428    ///
1429    /// See <https://docs.snowflake.com/en/sql-reference/constructs/where#joins-in-the-where-clause>.
1430    OuterJoin(Box<Expr>),
1431    /// A reference to the prior level in a CONNECT BY clause.
1432    Prior(Box<Expr>),
1433    /// A lambda function.
1434    ///
1435    /// Syntax:
1436    /// ```plaintext
1437    /// param -> expr | (param1, ...) -> expr
1438    /// ```
1439    ///
1440    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/functions#higher-order-functions---operator-and-lambdaparams-expr-function)
1441    /// [Databricks](https://docs.databricks.com/en/sql/language-manual/sql-ref-lambda-functions.html)
1442    /// [DuckDB](https://duckdb.org/docs/stable/sql/functions/lambda)
1443    Lambda(LambdaFunction),
1444    /// Checks membership of a value in a JSON array
1445    MemberOf(MemberOf),
1446}
1447
1448impl Expr {
1449    /// Creates a new [`Expr::Value`]
1450    pub fn value(value: impl Into<ValueWithSpan>) -> Self {
1451        Expr::Value(value.into())
1452    }
1453}
1454
1455/// The contents inside the `[` and `]` in a subscript expression.
1456#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1457#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1458#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1459pub enum Subscript {
1460    /// Accesses the element of the array at the given index.
1461    Index {
1462        /// The index expression used to access the array element.
1463        index: Expr,
1464    },
1465
1466    /// Accesses a slice of an array on PostgreSQL, e.g.
1467    ///
1468    /// ```plaintext
1469    /// => select (array[1,2,3,4,5,6])[2:5];
1470    /// -----------
1471    /// {2,3,4,5}
1472    /// ```
1473    ///
1474    /// The lower and/or upper bound can be omitted to slice from the start or
1475    /// end of the array respectively.
1476    ///
1477    /// See <https://www.postgresql.org/docs/current/arrays.html#ARRAYS-ACCESSING>.
1478    ///
1479    /// Also supports an optional "stride" as the last element (this is not
1480    /// supported by postgres), e.g.
1481    ///
1482    /// ```plaintext
1483    /// => select (array[1,2,3,4,5,6])[1:6:2];
1484    /// -----------
1485    /// {1,3,5}
1486    /// ```
1487    Slice {
1488        /// Optional lower bound for the slice (inclusive).
1489        lower_bound: Option<Expr>,
1490        /// Optional upper bound for the slice (inclusive).
1491        upper_bound: Option<Expr>,
1492        /// Optional stride for the slice (step size).
1493        stride: Option<Expr>,
1494    },
1495}
1496
1497impl fmt::Display for Subscript {
1498    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1499        match self {
1500            Subscript::Index { index } => write!(f, "{index}"),
1501            Subscript::Slice {
1502                lower_bound,
1503                upper_bound,
1504                stride,
1505            } => {
1506                if let Some(lower) = lower_bound {
1507                    write!(f, "{lower}")?;
1508                }
1509                write!(f, ":")?;
1510                if let Some(upper) = upper_bound {
1511                    write!(f, "{upper}")?;
1512                }
1513                if let Some(stride) = stride {
1514                    write!(f, ":")?;
1515                    write!(f, "{stride}")?;
1516                }
1517                Ok(())
1518            }
1519        }
1520    }
1521}
1522
1523/// An element of a [`Expr::CompoundFieldAccess`].
1524/// It can be an expression or a subscript.
1525#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1526#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1527#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1528pub enum AccessExpr {
1529    /// Accesses a field using dot notation, e.g. `foo.bar.baz`.
1530    Dot(Expr),
1531    /// Accesses a field or array element using bracket notation, e.g. `foo['bar']`.
1532    Subscript(Subscript),
1533}
1534
1535const fn is_number_expr(expr: &Expr) -> bool {
1536    matches!(expr, Expr::Value(v) if matches!(v.value, Value::Number(_, _)))
1537}
1538
1539impl fmt::Display for AccessExpr {
1540    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1541        match self {
1542            AccessExpr::Dot(expr) if is_number_expr(expr) => write!(f, " . {expr}"),
1543            AccessExpr::Dot(expr) => write!(f, ".{expr}"),
1544            AccessExpr::Subscript(subscript) => write!(f, "[{subscript}]"),
1545        }
1546    }
1547}
1548
1549/// A lambda function.
1550#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1551#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1552#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1553pub struct LambdaFunction {
1554    /// The parameters to the lambda function.
1555    pub params: OneOrManyWithParens<LambdaFunctionParameter>,
1556    /// The body of the lambda function.
1557    pub body: Box<Expr>,
1558    /// The syntax style used to write the lambda function.
1559    pub syntax: LambdaSyntax,
1560}
1561
1562impl fmt::Display for LambdaFunction {
1563    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1564        match self.syntax {
1565            LambdaSyntax::Arrow => write!(f, "{} -> {}", self.params, self.body),
1566            LambdaSyntax::LambdaKeyword => {
1567                // For lambda keyword syntax, display params without parentheses
1568                // e.g., `lambda x, y : expr` not `lambda (x, y) : expr`
1569                write!(f, "lambda ")?;
1570                match &self.params {
1571                    OneOrManyWithParens::One(p) => write!(f, "{p}")?,
1572                    OneOrManyWithParens::Many(ps) => write!(f, "{}", display_comma_separated(ps))?,
1573                };
1574                write!(f, " : {}", self.body)
1575            }
1576        }
1577    }
1578}
1579
1580/// A parameter to a lambda function, optionally with a data type.
1581#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1582#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1583#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1584pub struct LambdaFunctionParameter {
1585    /// The name of the parameter
1586    pub name: Ident,
1587    /// The optional data type of the parameter
1588    /// [Snowflake Syntax](https://docs.snowflake.com/en/sql-reference/functions/filter#arguments)
1589    pub data_type: Option<DataType>,
1590}
1591
1592impl fmt::Display for LambdaFunctionParameter {
1593    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1594        match &self.data_type {
1595            Some(dt) => write!(f, "{} {}", self.name, dt),
1596            None => write!(f, "{}", self.name),
1597        }
1598    }
1599}
1600
1601/// The syntax style for a lambda function.
1602#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Copy)]
1603#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1604#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1605pub enum LambdaSyntax {
1606    /// Arrow syntax: `param -> expr` or `(param1, param2) -> expr`
1607    ///
1608    /// <https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-lambda-functions>
1609    ///
1610    /// Supported, but deprecated in DuckDB:
1611    /// <https://duckdb.org/docs/stable/sql/functions/lambda>
1612    Arrow,
1613    /// Lambda keyword syntax: `lambda param : expr` or `lambda param1, param2 : expr`
1614    ///
1615    /// Recommended in DuckDB:
1616    /// <https://duckdb.org/docs/stable/sql/functions/lambda>
1617    LambdaKeyword,
1618}
1619
1620/// Encapsulates the common pattern in SQL where either one unparenthesized item
1621/// such as an identifier or expression is permitted, or multiple of the same
1622/// item in a parenthesized list. For accessing items regardless of the form,
1623/// `OneOrManyWithParens` implements `Deref<Target = [T]>` and `IntoIterator`,
1624/// so you can call slice methods on it and iterate over items
1625/// # Examples
1626/// Accessing as a slice:
1627/// ```
1628/// # use sqlparser::ast::OneOrManyWithParens;
1629/// let one = OneOrManyWithParens::One("a");
1630///
1631/// assert_eq!(one[0], "a");
1632/// assert_eq!(one.len(), 1);
1633/// ```
1634/// Iterating:
1635/// ```
1636/// # use sqlparser::ast::OneOrManyWithParens;
1637/// let one = OneOrManyWithParens::One("a");
1638/// let many = OneOrManyWithParens::Many(vec!["a", "b"]);
1639///
1640/// assert_eq!(one.into_iter().chain(many).collect::<Vec<_>>(), vec!["a", "a", "b"] );
1641/// ```
1642#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1643#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1644#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1645pub enum OneOrManyWithParens<T> {
1646    /// A single `T`, unparenthesized.
1647    One(T),
1648    /// One or more `T`s, parenthesized.
1649    Many(Vec<T>),
1650}
1651
1652impl<T> Deref for OneOrManyWithParens<T> {
1653    type Target = [T];
1654
1655    fn deref(&self) -> &[T] {
1656        match self {
1657            OneOrManyWithParens::One(one) => core::slice::from_ref(one),
1658            OneOrManyWithParens::Many(many) => many,
1659        }
1660    }
1661}
1662
1663impl<T> AsRef<[T]> for OneOrManyWithParens<T> {
1664    fn as_ref(&self) -> &[T] {
1665        self
1666    }
1667}
1668
1669impl<'a, T> IntoIterator for &'a OneOrManyWithParens<T> {
1670    type Item = &'a T;
1671    type IntoIter = core::slice::Iter<'a, T>;
1672
1673    fn into_iter(self) -> Self::IntoIter {
1674        self.iter()
1675    }
1676}
1677
1678/// Owned iterator implementation of `OneOrManyWithParens`
1679#[derive(Debug, Clone)]
1680pub struct OneOrManyWithParensIntoIter<T> {
1681    inner: OneOrManyWithParensIntoIterInner<T>,
1682}
1683
1684#[derive(Debug, Clone)]
1685enum OneOrManyWithParensIntoIterInner<T> {
1686    One(core::iter::Once<T>),
1687    Many(<Vec<T> as IntoIterator>::IntoIter),
1688}
1689
1690impl<T> core::iter::FusedIterator for OneOrManyWithParensIntoIter<T>
1691where
1692    core::iter::Once<T>: core::iter::FusedIterator,
1693    <Vec<T> as IntoIterator>::IntoIter: core::iter::FusedIterator,
1694{
1695}
1696
1697impl<T> core::iter::ExactSizeIterator for OneOrManyWithParensIntoIter<T>
1698where
1699    core::iter::Once<T>: core::iter::ExactSizeIterator,
1700    <Vec<T> as IntoIterator>::IntoIter: core::iter::ExactSizeIterator,
1701{
1702}
1703
1704impl<T> core::iter::Iterator for OneOrManyWithParensIntoIter<T> {
1705    type Item = T;
1706
1707    fn next(&mut self) -> Option<Self::Item> {
1708        match &mut self.inner {
1709            OneOrManyWithParensIntoIterInner::One(one) => one.next(),
1710            OneOrManyWithParensIntoIterInner::Many(many) => many.next(),
1711        }
1712    }
1713
1714    fn size_hint(&self) -> (usize, Option<usize>) {
1715        match &self.inner {
1716            OneOrManyWithParensIntoIterInner::One(one) => one.size_hint(),
1717            OneOrManyWithParensIntoIterInner::Many(many) => many.size_hint(),
1718        }
1719    }
1720
1721    fn count(self) -> usize
1722    where
1723        Self: Sized,
1724    {
1725        match self.inner {
1726            OneOrManyWithParensIntoIterInner::One(one) => one.count(),
1727            OneOrManyWithParensIntoIterInner::Many(many) => many.count(),
1728        }
1729    }
1730
1731    fn fold<B, F>(mut self, init: B, f: F) -> B
1732    where
1733        Self: Sized,
1734        F: FnMut(B, Self::Item) -> B,
1735    {
1736        match &mut self.inner {
1737            OneOrManyWithParensIntoIterInner::One(one) => one.fold(init, f),
1738            OneOrManyWithParensIntoIterInner::Many(many) => many.fold(init, f),
1739        }
1740    }
1741}
1742
1743impl<T> core::iter::DoubleEndedIterator for OneOrManyWithParensIntoIter<T> {
1744    fn next_back(&mut self) -> Option<Self::Item> {
1745        match &mut self.inner {
1746            OneOrManyWithParensIntoIterInner::One(one) => one.next_back(),
1747            OneOrManyWithParensIntoIterInner::Many(many) => many.next_back(),
1748        }
1749    }
1750}
1751
1752impl<T> IntoIterator for OneOrManyWithParens<T> {
1753    type Item = T;
1754
1755    type IntoIter = OneOrManyWithParensIntoIter<T>;
1756
1757    fn into_iter(self) -> Self::IntoIter {
1758        let inner = match self {
1759            OneOrManyWithParens::One(one) => {
1760                OneOrManyWithParensIntoIterInner::One(core::iter::once(one))
1761            }
1762            OneOrManyWithParens::Many(many) => {
1763                OneOrManyWithParensIntoIterInner::Many(many.into_iter())
1764            }
1765        };
1766
1767        OneOrManyWithParensIntoIter { inner }
1768    }
1769}
1770
1771impl<T> fmt::Display for OneOrManyWithParens<T>
1772where
1773    T: fmt::Display,
1774{
1775    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1776        match self {
1777            OneOrManyWithParens::One(value) => write!(f, "{value}"),
1778            OneOrManyWithParens::Many(values) => {
1779                write!(f, "({})", display_comma_separated(values))
1780            }
1781        }
1782    }
1783}
1784
1785impl fmt::Display for CastFormat {
1786    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1787        match self {
1788            CastFormat::Value(v) => write!(f, "{v}"),
1789            CastFormat::ValueAtTimeZone(v, tz) => write!(f, "{v} AT TIME ZONE {tz}"),
1790        }
1791    }
1792}
1793
1794impl fmt::Display for Expr {
1795    #[cfg_attr(feature = "recursive-protection", recursive::recursive)]
1796    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1797        match self {
1798            Expr::Identifier(s) => write!(f, "{s}"),
1799            Expr::Wildcard(_) => f.write_str("*"),
1800            Expr::QualifiedWildcard(prefix, _) => write!(f, "{prefix}.*"),
1801            Expr::CompoundIdentifier(s) => write!(f, "{}", display_separated(s, ".")),
1802            Expr::CompoundFieldAccess { root, access_chain } => {
1803                write!(f, "{root}")?;
1804                let mut prev_is_number = is_number_expr(root);
1805                for field in access_chain {
1806                    match field {
1807                        AccessExpr::Dot(expr) if prev_is_number => write!(f, " . {expr}")?,
1808                        _ => write!(f, "{field}")?,
1809                    }
1810                    prev_is_number = matches!(field, AccessExpr::Dot(expr) if is_number_expr(expr));
1811                }
1812                Ok(())
1813            }
1814            Expr::IsTrue(ast) => write!(f, "{ast} IS TRUE"),
1815            Expr::IsNotTrue(ast) => write!(f, "{ast} IS NOT TRUE"),
1816            Expr::IsFalse(ast) => write!(f, "{ast} IS FALSE"),
1817            Expr::IsNotFalse(ast) => write!(f, "{ast} IS NOT FALSE"),
1818            Expr::IsNull(ast) => write!(f, "{ast} IS NULL"),
1819            Expr::IsNotNull(ast) => write!(f, "{ast} IS NOT NULL"),
1820            Expr::IsUnknown(ast) => write!(f, "{ast} IS UNKNOWN"),
1821            Expr::IsNotUnknown(ast) => write!(f, "{ast} IS NOT UNKNOWN"),
1822            Expr::IsJson {
1823                expr,
1824                kind,
1825                unique_keys,
1826                negated,
1827            } => {
1828                write!(f, "{expr} IS ")?;
1829                if *negated {
1830                    write!(f, "NOT ")?;
1831                }
1832                write!(f, "JSON")?;
1833                if let Some(kind) = kind {
1834                    write!(f, " {kind}")?;
1835                }
1836                if let Some(unique_keys) = unique_keys {
1837                    write!(f, " {unique_keys}")?;
1838                }
1839                Ok(())
1840            }
1841            Expr::In {
1842                expr,
1843                target,
1844                negated,
1845                global,
1846            } => write!(
1847                f,
1848                "{} {}{}IN {}",
1849                expr,
1850                if *global { "GLOBAL " } else { "" },
1851                if *negated { "NOT " } else { "" },
1852                target
1853            ),
1854            Expr::Between {
1855                expr,
1856                negated,
1857                low,
1858                high,
1859            } => write!(
1860                f,
1861                "{} {}BETWEEN {} AND {}",
1862                expr,
1863                if *negated { "NOT " } else { "" },
1864                low,
1865                high
1866            ),
1867            Expr::BinaryOp { left, op, right } => write!(f, "{left} {op} {right}"),
1868            Expr::Like {
1869                negated,
1870                expr,
1871                pattern,
1872                escape_char,
1873                any,
1874            } => match escape_char {
1875                Some(ch) => write!(
1876                    f,
1877                    "{} {}LIKE {}{} ESCAPE {}",
1878                    expr,
1879                    if *negated { "NOT " } else { "" },
1880                    if *any { "ANY " } else { "" },
1881                    pattern,
1882                    ch
1883                ),
1884                _ => write!(
1885                    f,
1886                    "{} {}LIKE {}{}",
1887                    expr,
1888                    if *negated { "NOT " } else { "" },
1889                    if *any { "ANY " } else { "" },
1890                    pattern
1891                ),
1892            },
1893            Expr::ILike {
1894                negated,
1895                expr,
1896                pattern,
1897                escape_char,
1898                any,
1899            } => match escape_char {
1900                Some(ch) => write!(
1901                    f,
1902                    "{} {}ILIKE {}{} ESCAPE {}",
1903                    expr,
1904                    if *negated { "NOT " } else { "" },
1905                    if *any { "ANY" } else { "" },
1906                    pattern,
1907                    ch
1908                ),
1909                _ => write!(
1910                    f,
1911                    "{} {}ILIKE {}{}",
1912                    expr,
1913                    if *negated { "NOT " } else { "" },
1914                    if *any { "ANY " } else { "" },
1915                    pattern
1916                ),
1917            },
1918            Expr::RLike {
1919                negated,
1920                expr,
1921                pattern,
1922                regexp,
1923            } => write!(
1924                f,
1925                "{} {}{} {}",
1926                expr,
1927                if *negated { "NOT " } else { "" },
1928                if *regexp { "REGEXP" } else { "RLIKE" },
1929                pattern
1930            ),
1931            Expr::IsNormalized {
1932                expr,
1933                form,
1934                negated,
1935            } => {
1936                let not_ = if *negated { "NOT " } else { "" };
1937                if let Some(form) = form {
1938                    write!(f, "{} IS {}{} NORMALIZED", expr, not_, form)
1939                } else {
1940                    write!(f, "{expr} IS {not_}NORMALIZED")
1941                }
1942            }
1943            Expr::SimilarTo {
1944                negated,
1945                expr,
1946                pattern,
1947                escape_char,
1948            } => match escape_char {
1949                Some(ch) => write!(
1950                    f,
1951                    "{} {}SIMILAR TO {} ESCAPE {}",
1952                    expr,
1953                    if *negated { "NOT " } else { "" },
1954                    pattern,
1955                    ch
1956                ),
1957                _ => write!(
1958                    f,
1959                    "{} {}SIMILAR TO {}",
1960                    expr,
1961                    if *negated { "NOT " } else { "" },
1962                    pattern
1963                ),
1964            },
1965            Expr::AnyOp {
1966                left,
1967                compare_op,
1968                right,
1969                is_some,
1970            } => {
1971                let add_parens = !matches!(right.as_ref(), Expr::Subquery(_));
1972                write!(
1973                    f,
1974                    "{left} {compare_op} {}{}{right}{}",
1975                    if *is_some { "SOME" } else { "ANY" },
1976                    if add_parens { "(" } else { "" },
1977                    if add_parens { ")" } else { "" },
1978                )
1979            }
1980            Expr::AllOp {
1981                left,
1982                compare_op,
1983                right,
1984            } => {
1985                let add_parens = !matches!(right.as_ref(), Expr::Subquery(_));
1986                write!(
1987                    f,
1988                    "{left} {compare_op} ALL{}{right}{}",
1989                    if add_parens { "(" } else { "" },
1990                    if add_parens { ")" } else { "" },
1991                )
1992            }
1993            Expr::UnaryOp { op, expr } => match op {
1994                UnaryOperator::PGPostfixFactorial => {
1995                    if matches!(
1996                        expr.as_ref(),
1997                        Expr::UnaryOp {
1998                            op: UnaryOperator::PGPostfixFactorial,
1999                            ..
2000                        }
2001                    ) {
2002                        write!(f, "{expr} {op}")
2003                    } else {
2004                        write!(f, "{expr}{op}")
2005                    }
2006                }
2007                UnaryOperator::Not
2008                | UnaryOperator::BitwiseNot
2009                | UnaryOperator::Hash
2010                | UnaryOperator::AtDashAt
2011                | UnaryOperator::DoubleAt
2012                | UnaryOperator::PGAbs
2013                | UnaryOperator::QuestionDash
2014                | UnaryOperator::QuestionPipe
2015                | UnaryOperator::PGSquareRoot
2016                | UnaryOperator::PGCubeRoot => write!(f, "{op} {expr}"),
2017                UnaryOperator::Minus | UnaryOperator::BangNot => {
2018                    // Written before the check, so an enclosing
2019                    // `starts_with_operator_char` stops at this operator.
2020                    write!(f, "{op}")?;
2021                    if starts_with_operator_char(expr) {
2022                        f.write_str(" ")?;
2023                    }
2024                    write!(f, "{expr}")
2025                }
2026                UnaryOperator::Plus | UnaryOperator::PGPrefixFactorial => write!(f, "{op}{expr}"),
2027            },
2028            Expr::Convert {
2029                is_try,
2030                expr,
2031                target_before_value,
2032                data_type,
2033                charset,
2034                styles,
2035            } => {
2036                write!(f, "{}CONVERT(", if *is_try { "TRY_" } else { "" })?;
2037                if let Some(data_type) = data_type {
2038                    if let Some(charset) = charset {
2039                        write!(f, "{expr}, {data_type} CHARACTER SET {charset}")
2040                    } else if *target_before_value {
2041                        write!(f, "{data_type}, {expr}")
2042                    } else {
2043                        write!(f, "{expr}, {data_type}")
2044                    }
2045                } else if let Some(charset) = charset {
2046                    write!(f, "{expr} USING {charset}")
2047                } else {
2048                    write!(f, "{expr}") // This should never happen
2049                }?;
2050                if !styles.is_empty() {
2051                    write!(f, ", {}", display_comma_separated(styles))?;
2052                }
2053                write!(f, ")")
2054            }
2055            Expr::Cast {
2056                kind,
2057                expr,
2058                data_type,
2059                format,
2060            } => match kind {
2061                CastKind::Cast => {
2062                    if matches!(data_type, DataType::Unspecified) {
2063                        write!(f, "CAST({expr} AS")?;
2064                    } else {
2065                        write!(f, "CAST({expr} AS {data_type}")?;
2066                    }
2067                    if let Some(format) = format {
2068                        write!(f, " FORMAT {format}")?;
2069                    }
2070                    write!(f, ")")
2071                }
2072                CastKind::TryCast => {
2073                    if let Some(format) = format {
2074                        write!(f, "TRY_CAST({expr} AS {data_type} FORMAT {format})")
2075                    } else {
2076                        write!(f, "TRY_CAST({expr} AS {data_type})")
2077                    }
2078                }
2079                CastKind::SafeCast => {
2080                    if let Some(format) = format {
2081                        write!(f, "SAFE_CAST({expr} AS {data_type} FORMAT {format})")
2082                    } else {
2083                        write!(f, "SAFE_CAST({expr} AS {data_type})")
2084                    }
2085                }
2086                CastKind::DoubleColon => {
2087                    write!(f, "{expr}::{data_type}")
2088                }
2089            },
2090            Expr::Extract {
2091                field,
2092                syntax,
2093                expr,
2094            } => match syntax {
2095                ExtractSyntax::From => write!(f, "EXTRACT({field} FROM {expr})"),
2096                ExtractSyntax::Comma => write!(f, "EXTRACT({field}, {expr})"),
2097            },
2098            Expr::Ceil { expr, field } => match field {
2099                CeilFloorKind::DateTimeField(DateTimeField::NoDateTime) => {
2100                    write!(f, "CEIL({expr})")
2101                }
2102                CeilFloorKind::DateTimeField(dt_field) => write!(f, "CEIL({expr} TO {dt_field})"),
2103                CeilFloorKind::Scale(s) => write!(f, "CEIL({expr}, {s})"),
2104            },
2105            Expr::Floor { expr, field } => match field {
2106                CeilFloorKind::DateTimeField(DateTimeField::NoDateTime) => {
2107                    write!(f, "FLOOR({expr})")
2108                }
2109                CeilFloorKind::DateTimeField(dt_field) => write!(f, "FLOOR({expr} TO {dt_field})"),
2110                CeilFloorKind::Scale(s) => write!(f, "FLOOR({expr}, {s})"),
2111            },
2112            Expr::Position { expr, r#in } => write!(f, "POSITION({expr} IN {in})"),
2113            Expr::Collate { expr, collation } => write!(f, "{expr} COLLATE {collation}"),
2114            Expr::Nested(ast) => write!(f, "({ast})"),
2115            Expr::Value(v) => write!(f, "{v}"),
2116            Expr::Prefixed { prefix, value } => write!(f, "{prefix} {value}"),
2117            Expr::TypedString(ts) => ts.fmt(f),
2118            Expr::Function(fun) => fun.fmt(f),
2119            Expr::Case {
2120                case_token: _,
2121                end_token: _,
2122                operand,
2123                conditions,
2124                else_result,
2125            } => {
2126                f.write_str("CASE")?;
2127                if let Some(operand) = operand {
2128                    f.write_str(" ")?;
2129                    operand.fmt(f)?;
2130                }
2131                for when in conditions {
2132                    SpaceOrNewline.fmt(f)?;
2133                    Indent(when).fmt(f)?;
2134                }
2135                if let Some(else_result) = else_result {
2136                    SpaceOrNewline.fmt(f)?;
2137                    Indent("ELSE").fmt(f)?;
2138                    SpaceOrNewline.fmt(f)?;
2139                    Indent(Indent(else_result)).fmt(f)?;
2140                }
2141                SpaceOrNewline.fmt(f)?;
2142                f.write_str("END")
2143            }
2144            Expr::Exists { subquery, negated } => write!(
2145                f,
2146                "{}EXISTS ({})",
2147                if *negated { "NOT " } else { "" },
2148                subquery
2149            ),
2150            Expr::Subquery(s) => write!(f, "({s})"),
2151            Expr::GroupingSets(sets) => {
2152                write!(f, "GROUPING SETS (")?;
2153                let mut sep = "";
2154                for set in sets {
2155                    write!(f, "{sep}")?;
2156                    sep = ", ";
2157                    write!(f, "({})", display_comma_separated(set))?;
2158                }
2159                write!(f, ")")
2160            }
2161            Expr::Cube(sets) => {
2162                write!(f, "CUBE (")?;
2163                let mut sep = "";
2164                for set in sets {
2165                    write!(f, "{sep}")?;
2166                    sep = ", ";
2167                    if set.len() == 1 {
2168                        write!(f, "{}", set[0])?;
2169                    } else {
2170                        write!(f, "({})", display_comma_separated(set))?;
2171                    }
2172                }
2173                write!(f, ")")
2174            }
2175            Expr::Rollup(sets) => {
2176                write!(f, "ROLLUP (")?;
2177                let mut sep = "";
2178                for set in sets {
2179                    write!(f, "{sep}")?;
2180                    sep = ", ";
2181                    if set.len() == 1 {
2182                        write!(f, "{}", set[0])?;
2183                    } else {
2184                        write!(f, "({})", display_comma_separated(set))?;
2185                    }
2186                }
2187                write!(f, ")")
2188            }
2189            Expr::Substring {
2190                expr,
2191                substring_from,
2192                substring_for,
2193                special,
2194                shorthand,
2195            } => {
2196                f.write_str("SUBSTR")?;
2197                if !*shorthand {
2198                    f.write_str("ING")?;
2199                }
2200                write!(f, "({expr}")?;
2201                if let Some(from_part) = substring_from {
2202                    if *special {
2203                        write!(f, ", {from_part}")?;
2204                    } else {
2205                        write!(f, " FROM {from_part}")?;
2206                    }
2207                }
2208                if let Some(for_part) = substring_for {
2209                    if *special {
2210                        write!(f, ", {for_part}")?;
2211                    } else {
2212                        write!(f, " FOR {for_part}")?;
2213                    }
2214                }
2215
2216                write!(f, ")")
2217            }
2218            Expr::Overlay {
2219                expr,
2220                overlay_what,
2221                overlay_from,
2222                overlay_for,
2223            } => {
2224                write!(
2225                    f,
2226                    "OVERLAY({expr} PLACING {overlay_what} FROM {overlay_from}"
2227                )?;
2228                if let Some(for_part) = overlay_for {
2229                    write!(f, " FOR {for_part}")?;
2230                }
2231
2232                write!(f, ")")
2233            }
2234            Expr::IsDistinctFrom(a, b) => write!(f, "{a} IS DISTINCT FROM {b}"),
2235            Expr::IsNotDistinctFrom(a, b) => write!(f, "{a} IS NOT DISTINCT FROM {b}"),
2236            Expr::Trim {
2237                expr,
2238                trim_where,
2239                trim_what,
2240                trim_characters,
2241            } => {
2242                write!(f, "TRIM(")?;
2243                if let Some(ident) = trim_where {
2244                    write!(f, "{ident} ")?;
2245                }
2246                if let Some(trim_char) = trim_what {
2247                    write!(f, "{trim_char} FROM {expr}")?;
2248                } else {
2249                    write!(f, "{expr}")?;
2250                }
2251                if let Some(characters) = trim_characters {
2252                    write!(f, ", {}", display_comma_separated(characters))?;
2253                }
2254
2255                write!(f, ")")
2256            }
2257            Expr::Tuple(exprs) => {
2258                write!(f, "({})", display_comma_separated(exprs))
2259            }
2260            Expr::Struct { values, fields } => {
2261                if !fields.is_empty() {
2262                    write!(
2263                        f,
2264                        "STRUCT<{}>({})",
2265                        display_comma_separated(fields),
2266                        display_comma_separated(values)
2267                    )
2268                } else {
2269                    write!(f, "STRUCT({})", display_comma_separated(values))
2270                }
2271            }
2272            Expr::Named { expr, name } => {
2273                write!(f, "{expr} AS {name}")
2274            }
2275            Expr::Dictionary(fields) => {
2276                write!(f, "{{{}}}", display_comma_separated(fields))
2277            }
2278            Expr::Map(map) => {
2279                write!(f, "{map}")
2280            }
2281            Expr::Array(set) => {
2282                write!(f, "{set}")
2283            }
2284            Expr::JsonAccess { value, path } => {
2285                write!(f, "{value}{path}")
2286            }
2287            Expr::AtTimeZone {
2288                timestamp,
2289                time_zone,
2290            } => {
2291                write!(f, "{timestamp} AT TIME ZONE {time_zone}")
2292            }
2293            Expr::Interval(interval) => {
2294                write!(f, "{interval}")
2295            }
2296            Expr::MatchAgainst {
2297                columns,
2298                match_value: match_expr,
2299                opt_search_modifier,
2300            } => {
2301                write!(f, "MATCH ({}) AGAINST ", display_comma_separated(columns),)?;
2302
2303                if let Some(search_modifier) = opt_search_modifier {
2304                    write!(f, "({match_expr} {search_modifier})")?;
2305                } else {
2306                    write!(f, "({match_expr})")?;
2307                }
2308
2309                Ok(())
2310            }
2311            Expr::OuterJoin(expr) => {
2312                write!(f, "{expr} (+)")
2313            }
2314            Expr::Prior(expr) => write!(f, "PRIOR {expr}"),
2315            Expr::Lambda(lambda) => write!(f, "{lambda}"),
2316            Expr::MemberOf(member_of) => write!(f, "{member_of}"),
2317        }
2318    }
2319}
2320
2321/// The type of a window used in `OVER` clauses.
2322///
2323/// A window can be either an inline specification (`WindowSpec`) or a
2324/// reference to a previously defined named window.
2325///
2326/// - `WindowSpec(WindowSpec)`: An inline window specification, e.g.
2327///   `OVER (PARTITION BY ... ORDER BY ...)`.
2328/// - `NamedWindow(Ident)`: A reference to a named window declared elsewhere.
2329#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2330#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2331#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2332pub enum WindowType {
2333    /// An inline window specification.
2334    WindowSpec(WindowSpec),
2335    /// A reference to a previously defined named window.
2336    NamedWindow(Ident),
2337}
2338
2339impl Display for WindowType {
2340    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2341        match self {
2342            WindowType::WindowSpec(spec) => {
2343                f.write_str("(")?;
2344                NewLine.fmt(f)?;
2345                Indent(spec).fmt(f)?;
2346                NewLine.fmt(f)?;
2347                f.write_str(")")
2348            }
2349            WindowType::NamedWindow(name) => name.fmt(f),
2350        }
2351    }
2352}
2353
2354/// A window specification (i.e. `OVER ([window_name] PARTITION BY .. ORDER BY .. etc.)`)
2355#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2356#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2357#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2358pub struct WindowSpec {
2359    /// Optional window name.
2360    ///
2361    /// You can find it at least in [MySQL][1], [BigQuery][2], [PostgreSQL][3]
2362    ///
2363    /// [1]: https://dev.mysql.com/doc/refman/8.0/en/window-functions-named-windows.html
2364    /// [2]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
2365    /// [3]: https://www.postgresql.org/docs/current/sql-expressions.html#SYNTAX-WINDOW-FUNCTIONS
2366    pub window_name: Option<Ident>,
2367    /// `OVER (PARTITION BY ...)`
2368    pub partition_by: Vec<Expr>,
2369    /// `OVER (ORDER BY ...)`
2370    pub order_by: Vec<OrderByExpr>,
2371    /// `OVER (window frame)`
2372    pub window_frame: Option<WindowFrame>,
2373}
2374
2375impl fmt::Display for WindowSpec {
2376    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2377        let mut is_first = true;
2378        if let Some(window_name) = &self.window_name {
2379            if !is_first {
2380                SpaceOrNewline.fmt(f)?;
2381            }
2382            is_first = false;
2383            write!(f, "{window_name}")?;
2384        }
2385        if !self.partition_by.is_empty() {
2386            if !is_first {
2387                SpaceOrNewline.fmt(f)?;
2388            }
2389            is_first = false;
2390            write!(
2391                f,
2392                "PARTITION BY {}",
2393                display_comma_separated(&self.partition_by)
2394            )?;
2395        }
2396        if !self.order_by.is_empty() {
2397            if !is_first {
2398                SpaceOrNewline.fmt(f)?;
2399            }
2400            is_first = false;
2401            write!(f, "ORDER BY {}", display_comma_separated(&self.order_by))?;
2402        }
2403        if let Some(window_frame) = &self.window_frame {
2404            if !is_first {
2405                SpaceOrNewline.fmt(f)?;
2406            }
2407            if let Some(end_bound) = &window_frame.end_bound {
2408                write!(
2409                    f,
2410                    "{} BETWEEN {} AND {}",
2411                    window_frame.units, window_frame.start_bound, end_bound
2412                )?;
2413            } else {
2414                write!(f, "{} {}", window_frame.units, window_frame.start_bound)?;
2415            }
2416        }
2417        Ok(())
2418    }
2419}
2420
2421/// Specifies the data processed by a window function, e.g.
2422/// `RANGE UNBOUNDED PRECEDING` or `ROWS BETWEEN 5 PRECEDING AND CURRENT ROW`.
2423///
2424/// Note: The parser does not validate the specified bounds; the caller should
2425/// reject invalid bounds like `ROWS UNBOUNDED FOLLOWING` before execution.
2426#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2427#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2428#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2429pub struct WindowFrame {
2430    /// Units for the frame (e.g. `ROWS`, `RANGE`, `GROUPS`).
2431    pub units: WindowFrameUnits,
2432    /// The start bound of the window frame.
2433    pub start_bound: WindowFrameBound,
2434    /// The right bound of the `BETWEEN .. AND` clause. The end bound of `None`
2435    /// indicates the shorthand form (e.g. `ROWS 1 PRECEDING`), which must
2436    /// behave the same as `end_bound = WindowFrameBound::CurrentRow`.
2437    pub end_bound: Option<WindowFrameBound>,
2438    // TBD: EXCLUDE
2439}
2440
2441impl Default for WindowFrame {
2442    /// Returns default value for window frame
2443    ///
2444    /// See [this page](https://www.sqlite.org/windowfunctions.html#frame_specifications) for more details.
2445    fn default() -> Self {
2446        Self {
2447            units: WindowFrameUnits::Range,
2448            start_bound: WindowFrameBound::Preceding(None),
2449            end_bound: None,
2450        }
2451    }
2452}
2453
2454#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2455#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2456#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2457/// Units used to describe the window frame scope.
2458pub enum WindowFrameUnits {
2459    /// `ROWS` unit.
2460    Rows,
2461    /// `RANGE` unit.
2462    Range,
2463    /// `GROUPS` unit.
2464    Groups,
2465}
2466
2467impl fmt::Display for WindowFrameUnits {
2468    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2469        f.write_str(match self {
2470            WindowFrameUnits::Rows => "ROWS",
2471            WindowFrameUnits::Range => "RANGE",
2472            WindowFrameUnits::Groups => "GROUPS",
2473        })
2474    }
2475}
2476
2477/// Specifies Ignore / Respect NULL within window functions.
2478/// For example
2479/// `FIRST_VALUE(column2) IGNORE NULLS OVER (PARTITION BY column1)`
2480#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2481#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2482#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2483/// How NULL values are treated in certain window functions.
2484pub enum NullTreatment {
2485    /// Ignore NULL values (e.g. `IGNORE NULLS`).
2486    IgnoreNulls,
2487    /// Respect NULL values (e.g. `RESPECT NULLS`).
2488    RespectNulls,
2489}
2490
2491impl fmt::Display for NullTreatment {
2492    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2493        f.write_str(match self {
2494            NullTreatment::IgnoreNulls => "IGNORE NULLS",
2495            NullTreatment::RespectNulls => "RESPECT NULLS",
2496        })
2497    }
2498}
2499
2500/// Specifies [WindowFrame]'s `start_bound` and `end_bound`
2501#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2502#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2503#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2504pub enum WindowFrameBound {
2505    /// `CURRENT ROW`
2506    CurrentRow,
2507    /// `<N> PRECEDING` or `UNBOUNDED PRECEDING`
2508    Preceding(Option<Box<Expr>>),
2509    /// `<N> FOLLOWING` or `UNBOUNDED FOLLOWING`.
2510    Following(Option<Box<Expr>>),
2511}
2512
2513impl fmt::Display for WindowFrameBound {
2514    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2515        match self {
2516            WindowFrameBound::CurrentRow => f.write_str("CURRENT ROW"),
2517            WindowFrameBound::Preceding(None) => f.write_str("UNBOUNDED PRECEDING"),
2518            WindowFrameBound::Following(None) => f.write_str("UNBOUNDED FOLLOWING"),
2519            WindowFrameBound::Preceding(Some(n)) => write!(f, "{n} PRECEDING"),
2520            WindowFrameBound::Following(Some(n)) => write!(f, "{n} FOLLOWING"),
2521        }
2522    }
2523}
2524
2525#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2526#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2527#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2528/// Indicates partition operation type for partition management statements.
2529pub enum AddDropSync {
2530    /// Add partitions.
2531    ADD,
2532    /// Drop partitions.
2533    DROP,
2534    /// Sync partitions.
2535    SYNC,
2536}
2537
2538impl fmt::Display for AddDropSync {
2539    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2540        match self {
2541            AddDropSync::SYNC => f.write_str("SYNC PARTITIONS"),
2542            AddDropSync::DROP => f.write_str("DROP PARTITIONS"),
2543            AddDropSync::ADD => f.write_str("ADD PARTITIONS"),
2544        }
2545    }
2546}
2547
2548#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2549#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2550#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2551/// Object kinds supported by `SHOW CREATE` statements.
2552pub enum ShowCreateObject {
2553    /// An event object for `SHOW CREATE EVENT`.
2554    Event,
2555    /// A function object for `SHOW CREATE FUNCTION`.
2556    Function,
2557    /// A procedure object for `SHOW CREATE PROCEDURE`.
2558    Procedure,
2559    /// A table object for `SHOW CREATE TABLE`.
2560    Table,
2561    /// A trigger object for `SHOW CREATE TRIGGER`.
2562    Trigger,
2563    /// A view object for `SHOW CREATE VIEW`.
2564    View,
2565}
2566
2567impl fmt::Display for ShowCreateObject {
2568    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2569        match self {
2570            ShowCreateObject::Event => f.write_str("EVENT"),
2571            ShowCreateObject::Function => f.write_str("FUNCTION"),
2572            ShowCreateObject::Procedure => f.write_str("PROCEDURE"),
2573            ShowCreateObject::Table => f.write_str("TABLE"),
2574            ShowCreateObject::Trigger => f.write_str("TRIGGER"),
2575            ShowCreateObject::View => f.write_str("VIEW"),
2576        }
2577    }
2578}
2579
2580#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2581#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2582#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2583/// Objects that can be targeted by a `COMMENT` statement.
2584pub enum CommentObject {
2585    /// A collation.
2586    Collation,
2587    /// A table column.
2588    Column,
2589    /// A database.
2590    Database,
2591    /// A domain.
2592    Domain,
2593    /// An extension.
2594    Extension,
2595    /// A foreign table.
2596    ForeignTable,
2597    /// A function.
2598    Function,
2599    /// An index.
2600    Index,
2601    /// A materialized view.
2602    MaterializedView,
2603    /// A procedure.
2604    Procedure,
2605    /// A role.
2606    Role,
2607    /// A schema.
2608    Schema,
2609    /// A sequence.
2610    Sequence,
2611    /// A table.
2612    Table,
2613    /// A type.
2614    Type,
2615    /// A user.
2616    User,
2617    /// A view.
2618    View,
2619}
2620
2621impl fmt::Display for CommentObject {
2622    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2623        match self {
2624            CommentObject::Collation => f.write_str("COLLATION"),
2625            CommentObject::Column => f.write_str("COLUMN"),
2626            CommentObject::Database => f.write_str("DATABASE"),
2627            CommentObject::Domain => f.write_str("DOMAIN"),
2628            CommentObject::Extension => f.write_str("EXTENSION"),
2629            CommentObject::ForeignTable => f.write_str("FOREIGN TABLE"),
2630            CommentObject::Function => f.write_str("FUNCTION"),
2631            CommentObject::Index => f.write_str("INDEX"),
2632            CommentObject::MaterializedView => f.write_str("MATERIALIZED VIEW"),
2633            CommentObject::Procedure => f.write_str("PROCEDURE"),
2634            CommentObject::Role => f.write_str("ROLE"),
2635            CommentObject::Schema => f.write_str("SCHEMA"),
2636            CommentObject::Sequence => f.write_str("SEQUENCE"),
2637            CommentObject::Table => f.write_str("TABLE"),
2638            CommentObject::Type => f.write_str("TYPE"),
2639            CommentObject::User => f.write_str("USER"),
2640            CommentObject::View => f.write_str("VIEW"),
2641        }
2642    }
2643}
2644
2645#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2646#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2647#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2648/// Password specification variants used in user-related statements.
2649pub enum Password {
2650    /// A concrete password expression.
2651    Password(Expr),
2652    /// Represents a `NULL` password.
2653    NullPassword,
2654}
2655
2656/// A `CASE` statement.
2657///
2658/// Examples:
2659/// ```sql
2660/// CASE
2661///     WHEN EXISTS(SELECT 1)
2662///         THEN SELECT 1 FROM T;
2663///     WHEN EXISTS(SELECT 2)
2664///         THEN SELECT 1 FROM U;
2665///     ELSE
2666///         SELECT 1 FROM V;
2667/// END CASE;
2668/// ```
2669///
2670/// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/procedural-language#case_search_expression)
2671/// [Snowflake](https://docs.snowflake.com/en/sql-reference/snowflake-scripting/case)
2672#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2673#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2674#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2675pub struct CaseStatement {
2676    /// The `CASE` token that starts the statement.
2677    pub case_token: AttachedToken,
2678    /// Optional expression to match against in `CASE ... WHEN`.
2679    pub match_expr: Option<Expr>,
2680    /// The `WHEN ... THEN` blocks of the `CASE` statement.
2681    pub when_blocks: Vec<ConditionalStatementBlock>,
2682    /// Optional `ELSE` block for the `CASE` statement.
2683    pub else_block: Option<ConditionalStatementBlock>,
2684    /// The last token of the statement (`END` or `CASE`).
2685    pub end_case_token: AttachedToken,
2686}
2687
2688impl fmt::Display for CaseStatement {
2689    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2690        let CaseStatement {
2691            case_token: _,
2692            match_expr,
2693            when_blocks,
2694            else_block,
2695            end_case_token: AttachedToken(end),
2696        } = self;
2697
2698        write!(f, "CASE")?;
2699
2700        if let Some(expr) = match_expr {
2701            write!(f, " {expr}")?;
2702        }
2703
2704        if !when_blocks.is_empty() {
2705            write!(f, " {}", display_separated(when_blocks, " "))?;
2706        }
2707
2708        if let Some(else_block) = else_block {
2709            write!(f, " {else_block}")?;
2710        }
2711
2712        write!(f, " END")?;
2713
2714        if let Token::Word(w) = &end.token {
2715            if w.keyword == Keyword::CASE {
2716                write!(f, " CASE")?;
2717            }
2718        }
2719
2720        Ok(())
2721    }
2722}
2723
2724/// An `IF` statement.
2725///
2726/// Example (BigQuery or Snowflake):
2727/// ```sql
2728/// IF TRUE THEN
2729///     SELECT 1;
2730///     SELECT 2;
2731/// ELSEIF TRUE THEN
2732///     SELECT 3;
2733/// ELSE
2734///     SELECT 4;
2735/// END IF
2736/// ```
2737/// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/procedural-language#if)
2738/// [Snowflake](https://docs.snowflake.com/en/sql-reference/snowflake-scripting/if)
2739///
2740/// Example (MSSQL):
2741/// ```sql
2742/// IF 1=1 SELECT 1 ELSE SELECT 2
2743/// ```
2744/// [MSSQL](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/if-else-transact-sql?view=sql-server-ver16)
2745#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2746#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2747#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2748pub struct IfStatement {
2749    /// The initial `IF` block containing the condition and statements.
2750    pub if_block: ConditionalStatementBlock,
2751    /// Additional `ELSEIF` blocks.
2752    pub elseif_blocks: Vec<ConditionalStatementBlock>,
2753    /// Optional `ELSE` block.
2754    pub else_block: Option<ConditionalStatementBlock>,
2755    /// Optional trailing `END` token for the `IF` statement.
2756    pub end_token: Option<AttachedToken>,
2757}
2758
2759impl fmt::Display for IfStatement {
2760    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2761        let IfStatement {
2762            if_block,
2763            elseif_blocks,
2764            else_block,
2765            end_token,
2766        } = self;
2767
2768        write!(f, "{if_block}")?;
2769
2770        for elseif_block in elseif_blocks {
2771            write!(f, " {elseif_block}")?;
2772        }
2773
2774        if let Some(else_block) = else_block {
2775            write!(f, " {else_block}")?;
2776        }
2777
2778        if let Some(AttachedToken(end_token)) = end_token {
2779            write!(f, " END {end_token}")?;
2780        }
2781
2782        Ok(())
2783    }
2784}
2785
2786/// A `WHILE` statement.
2787///
2788/// Example:
2789/// ```sql
2790/// WHILE @@FETCH_STATUS = 0
2791/// BEGIN
2792///    FETCH NEXT FROM c1 INTO @var1, @var2;
2793/// END
2794/// ```
2795///
2796/// [MsSql](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/while-transact-sql)
2797#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2798#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2799#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2800pub struct WhileStatement {
2801    /// Block executed while the condition holds.
2802    pub while_block: ConditionalStatementBlock,
2803}
2804
2805impl fmt::Display for WhileStatement {
2806    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2807        let WhileStatement { while_block } = self;
2808        write!(f, "{while_block}")?;
2809        Ok(())
2810    }
2811}
2812
2813/// A block within a [Statement::Case] or [Statement::If] or [Statement::While]-like statement
2814///
2815/// Example 1:
2816/// ```sql
2817/// WHEN EXISTS(SELECT 1) THEN SELECT 1;
2818/// ```
2819///
2820/// Example 2:
2821/// ```sql
2822/// IF TRUE THEN SELECT 1; SELECT 2;
2823/// ```
2824///
2825/// Example 3:
2826/// ```sql
2827/// ELSE SELECT 1; SELECT 2;
2828/// ```
2829///
2830/// Example 4:
2831/// ```sql
2832/// WHILE @@FETCH_STATUS = 0
2833/// BEGIN
2834///    FETCH NEXT FROM c1 INTO @var1, @var2;
2835/// END
2836/// ```
2837#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2838#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2839#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2840pub struct ConditionalStatementBlock {
2841    /// Token representing the start of the block (e.g., WHEN/IF/WHILE).
2842    pub start_token: AttachedToken,
2843    /// Optional condition expression for the block.
2844    pub condition: Option<Expr>,
2845    /// Optional token for the `THEN` keyword.
2846    pub then_token: Option<AttachedToken>,
2847    /// The statements contained in this conditional block.
2848    pub conditional_statements: ConditionalStatements,
2849}
2850
2851impl ConditionalStatementBlock {
2852    /// Get the statements in this conditional block.
2853    pub fn statements(&self) -> &Vec<Statement> {
2854        self.conditional_statements.statements()
2855    }
2856}
2857
2858impl fmt::Display for ConditionalStatementBlock {
2859    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2860        let ConditionalStatementBlock {
2861            start_token: AttachedToken(start_token),
2862            condition,
2863            then_token,
2864            conditional_statements,
2865        } = self;
2866
2867        write!(f, "{start_token}")?;
2868
2869        if let Some(condition) = condition {
2870            write!(f, " {condition}")?;
2871        }
2872
2873        if then_token.is_some() {
2874            write!(f, " THEN")?;
2875        }
2876
2877        if !conditional_statements.statements().is_empty() {
2878            write!(f, " {conditional_statements}")?;
2879        }
2880
2881        Ok(())
2882    }
2883}
2884
2885/// A list of statements in a [ConditionalStatementBlock].
2886#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2887#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2888#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2889/// Statements used inside conditional blocks (`IF`, `WHEN`, `WHILE`).
2890pub enum ConditionalStatements {
2891    /// Simple sequence of statements (no `BEGIN`/`END`).
2892    Sequence {
2893        /// The statements in the sequence.
2894        statements: Vec<Statement>,
2895    },
2896    /// Block enclosed by `BEGIN` and `END`.
2897    BeginEnd(BeginEndStatements),
2898}
2899
2900impl ConditionalStatements {
2901    /// Get the statements in this conditional statements block.
2902    pub fn statements(&self) -> &Vec<Statement> {
2903        match self {
2904            ConditionalStatements::Sequence { statements } => statements,
2905            ConditionalStatements::BeginEnd(bes) => &bes.statements,
2906        }
2907    }
2908}
2909
2910impl fmt::Display for ConditionalStatements {
2911    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2912        match self {
2913            ConditionalStatements::Sequence { statements } => {
2914                if !statements.is_empty() {
2915                    format_statement_list(f, statements)?;
2916                }
2917                Ok(())
2918            }
2919            ConditionalStatements::BeginEnd(bes) => write!(f, "{bes}"),
2920        }
2921    }
2922}
2923
2924/// Represents a list of statements enclosed within `BEGIN` and `END` keywords.
2925/// Example:
2926/// ```sql
2927/// BEGIN
2928///     SELECT 1;
2929///     SELECT 2;
2930/// END
2931/// ```
2932#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2933#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2934#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2935pub struct BeginEndStatements {
2936    /// Token representing the `BEGIN` keyword (may include span info).
2937    pub begin_token: AttachedToken,
2938    /// Statements contained within the block.
2939    pub statements: Vec<Statement>,
2940    /// Token representing the `END` keyword (may include span info).
2941    pub end_token: AttachedToken,
2942}
2943
2944impl fmt::Display for BeginEndStatements {
2945    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2946        let BeginEndStatements {
2947            begin_token: AttachedToken(begin_token),
2948            statements,
2949            end_token: AttachedToken(end_token),
2950        } = self;
2951
2952        if begin_token.token != Token::EOF {
2953            write!(f, "{begin_token} ")?;
2954        }
2955        if !statements.is_empty() {
2956            format_statement_list(f, statements)?;
2957        }
2958        if end_token.token != Token::EOF {
2959            write!(f, " {end_token}")?;
2960        }
2961        Ok(())
2962    }
2963}
2964
2965/// A `RAISE` statement.
2966///
2967/// Examples:
2968/// ```sql
2969/// RAISE USING MESSAGE = 'error';
2970///
2971/// RAISE myerror;
2972/// ```
2973///
2974/// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/procedural-language#raise)
2975/// [Snowflake](https://docs.snowflake.com/en/sql-reference/snowflake-scripting/raise)
2976#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2977#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2978#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2979pub struct RaiseStatement {
2980    /// Optional value provided to the RAISE statement.
2981    pub value: Option<RaiseStatementValue>,
2982}
2983
2984impl fmt::Display for RaiseStatement {
2985    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2986        let RaiseStatement { value } = self;
2987
2988        write!(f, "RAISE")?;
2989        if let Some(value) = value {
2990            write!(f, " {value}")?;
2991        }
2992
2993        Ok(())
2994    }
2995}
2996
2997/// Represents the error value of a [RaiseStatement].
2998#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2999#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3000#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3001pub enum RaiseStatementValue {
3002    /// `RAISE USING MESSAGE = 'error'`
3003    UsingMessage(Expr),
3004    /// `RAISE myerror`
3005    Expr(Expr),
3006}
3007
3008impl fmt::Display for RaiseStatementValue {
3009    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3010        match self {
3011            RaiseStatementValue::Expr(expr) => write!(f, "{expr}"),
3012            RaiseStatementValue::UsingMessage(expr) => write!(f, "USING MESSAGE = {expr}"),
3013        }
3014    }
3015}
3016
3017/// A MSSQL `THROW` statement.
3018///
3019/// ```sql
3020/// THROW [ error_number, message, state ]
3021/// ```
3022///
3023/// [MSSQL](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/throw-transact-sql)
3024#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3025#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3026#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3027pub struct ThrowStatement {
3028    /// Error number expression.
3029    pub error_number: Option<Box<Expr>>,
3030    /// Error message expression.
3031    pub message: Option<Box<Expr>>,
3032    /// State expression.
3033    pub state: Option<Box<Expr>>,
3034}
3035
3036impl fmt::Display for ThrowStatement {
3037    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3038        let ThrowStatement {
3039            error_number,
3040            message,
3041            state,
3042        } = self;
3043
3044        write!(f, "THROW")?;
3045        if let (Some(error_number), Some(message), Some(state)) = (error_number, message, state) {
3046            write!(f, " {error_number}, {message}, {state}")?;
3047        }
3048        Ok(())
3049    }
3050}
3051
3052/// Represents an expression assignment within a variable `DECLARE` statement.
3053///
3054/// Examples:
3055/// ```sql
3056/// DECLARE variable_name := 42
3057/// DECLARE variable_name DEFAULT 42
3058/// ```
3059#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3060#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3061#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3062pub enum DeclareAssignment {
3063    /// Plain expression specified.
3064    Expr(Box<Expr>),
3065
3066    /// Expression assigned via the `DEFAULT` keyword
3067    Default(Box<Expr>),
3068
3069    /// Expression assigned via the `:=` syntax
3070    ///
3071    /// Example:
3072    /// ```sql
3073    /// DECLARE variable_name := 42;
3074    /// ```
3075    DuckAssignment(Box<Expr>),
3076
3077    /// Expression via the `FOR` keyword
3078    ///
3079    /// Example:
3080    /// ```sql
3081    /// DECLARE c1 CURSOR FOR res
3082    /// ```
3083    For(Box<Expr>),
3084
3085    /// Expression via the `=` syntax.
3086    ///
3087    /// Example:
3088    /// ```sql
3089    /// DECLARE @variable AS INT = 100
3090    /// ```
3091    MsSqlAssignment(Box<Expr>),
3092}
3093
3094impl fmt::Display for DeclareAssignment {
3095    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3096        match self {
3097            DeclareAssignment::Expr(expr) => {
3098                write!(f, "{expr}")
3099            }
3100            DeclareAssignment::Default(expr) => {
3101                write!(f, "DEFAULT {expr}")
3102            }
3103            DeclareAssignment::DuckAssignment(expr) => {
3104                write!(f, ":= {expr}")
3105            }
3106            DeclareAssignment::MsSqlAssignment(expr) => {
3107                write!(f, "= {expr}")
3108            }
3109            DeclareAssignment::For(expr) => {
3110                write!(f, "FOR {expr}")
3111            }
3112        }
3113    }
3114}
3115
3116/// Represents the type of a `DECLARE` statement.
3117#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3118#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3119#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3120pub enum DeclareType {
3121    /// Cursor variable type. e.g. [Snowflake] [PostgreSQL] [MsSql]
3122    ///
3123    /// [Snowflake]: https://docs.snowflake.com/en/developer-guide/snowflake-scripting/cursors#declaring-a-cursor
3124    /// [PostgreSQL]: https://www.postgresql.org/docs/current/plpgsql-cursors.html
3125    /// [MsSql]: https://learn.microsoft.com/en-us/sql/t-sql/language-elements/declare-cursor-transact-sql
3126    Cursor,
3127
3128    /// Result set variable type. [Snowflake]
3129    ///
3130    /// Syntax:
3131    /// ```text
3132    /// <resultset_name> RESULTSET [ { DEFAULT | := } ( <query> ) ] ;
3133    /// ```
3134    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/snowflake-scripting/declare#resultset-declaration-syntax
3135    ResultSet,
3136
3137    /// Exception declaration syntax. [Snowflake]
3138    ///
3139    /// Syntax:
3140    /// ```text
3141    /// <exception_name> EXCEPTION [ ( <exception_number> , '<exception_message>' ) ] ;
3142    /// ```
3143    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/snowflake-scripting/declare#exception-declaration-syntax
3144    Exception,
3145}
3146
3147impl fmt::Display for DeclareType {
3148    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3149        match self {
3150            DeclareType::Cursor => {
3151                write!(f, "CURSOR")
3152            }
3153            DeclareType::ResultSet => {
3154                write!(f, "RESULTSET")
3155            }
3156            DeclareType::Exception => {
3157                write!(f, "EXCEPTION")
3158            }
3159        }
3160    }
3161}
3162
3163/// Separator written between the declarations collected by one `DECLARE` keyword.
3164#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Default)]
3165#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3166#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3167pub enum DeclareSeparator {
3168    /// Each declaration ends with `;`, as in a Snowflake Scripting `DECLARE` section.
3169    ///
3170    /// [Snowflake](https://docs.snowflake.com/en/sql-reference/snowflake-scripting/declare)
3171    #[default]
3172    Semicolon,
3173    /// One comma-separated list, as in `DECLARE @a INT, @b INT`.
3174    ///
3175    /// [MsSql](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/declare-local-variable-transact-sql)
3176    Comma,
3177}
3178
3179/// A `DECLARE` statement.
3180/// [PostgreSQL] [Snowflake] [BigQuery]
3181///
3182/// Examples:
3183/// ```sql
3184/// DECLARE variable_name := 42
3185/// DECLARE liahona CURSOR FOR SELECT * FROM films;
3186/// ```
3187///
3188/// [PostgreSQL]: https://www.postgresql.org/docs/current/sql-declare.html
3189/// [Snowflake]: https://docs.snowflake.com/en/sql-reference/snowflake-scripting/declare
3190/// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/procedural-language#declare
3191#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3192#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3193#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3194pub struct Declare {
3195    /// The name(s) being declared.
3196    /// Example: `DECLARE a, b, c DEFAULT 42;
3197    pub names: Vec<Ident>,
3198    /// Data-type assigned to the declared variable.
3199    /// Example: `DECLARE x INT64 DEFAULT 42;
3200    pub data_type: Option<DataType>,
3201    /// Expression being assigned to the declared variable.
3202    pub assignment: Option<DeclareAssignment>,
3203    /// Represents the type of the declared variable.
3204    pub declare_type: Option<DeclareType>,
3205    /// Causes the cursor to return data in binary rather than in text format.
3206    pub binary: Option<bool>,
3207    /// None = Not specified
3208    /// Some(true) = INSENSITIVE
3209    /// Some(false) = ASENSITIVE
3210    pub sensitive: Option<bool>,
3211    /// None = Not specified
3212    /// Some(true) = SCROLL
3213    /// Some(false) = NO SCROLL
3214    pub scroll: Option<bool>,
3215    /// None = Not specified
3216    /// Some(true) = WITH HOLD, specifies that the cursor can continue to be used after the transaction that created it successfully commits
3217    /// Some(false) = WITHOUT HOLD, specifies that the cursor cannot be used outside of the transaction that created it
3218    pub hold: Option<bool>,
3219    /// `FOR <query>` clause in a CURSOR declaration.
3220    pub for_query: Option<Box<Query>>,
3221}
3222
3223impl fmt::Display for Declare {
3224    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3225        let Declare {
3226            names,
3227            data_type,
3228            assignment,
3229            declare_type,
3230            binary,
3231            sensitive,
3232            scroll,
3233            hold,
3234            for_query,
3235        } = self;
3236        write!(f, "{}", display_comma_separated(names))?;
3237
3238        if let Some(true) = binary {
3239            write!(f, " BINARY")?;
3240        }
3241
3242        if let Some(sensitive) = sensitive {
3243            if *sensitive {
3244                write!(f, " INSENSITIVE")?;
3245            } else {
3246                write!(f, " ASENSITIVE")?;
3247            }
3248        }
3249
3250        if let Some(scroll) = scroll {
3251            if *scroll {
3252                write!(f, " SCROLL")?;
3253            } else {
3254                write!(f, " NO SCROLL")?;
3255            }
3256        }
3257
3258        if let Some(declare_type) = declare_type {
3259            write!(f, " {declare_type}")?;
3260        }
3261
3262        if let Some(hold) = hold {
3263            if *hold {
3264                write!(f, " WITH HOLD")?;
3265            } else {
3266                write!(f, " WITHOUT HOLD")?;
3267            }
3268        }
3269
3270        if let Some(query) = for_query {
3271            write!(f, " FOR {query}")?;
3272        }
3273
3274        if let Some(data_type) = data_type {
3275            write!(f, " {data_type}")?;
3276        }
3277
3278        if let Some(expr) = assignment {
3279            write!(f, " {expr}")?;
3280        }
3281        Ok(())
3282    }
3283}
3284
3285/// Sql options of a `CREATE TABLE` statement.
3286#[derive(Debug, Default, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3287#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3288#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3289/// Options allowed within a `CREATE TABLE` statement.
3290pub enum CreateTableOptions {
3291    /// No options specified.
3292    #[default]
3293    None,
3294    /// Options specified using the `WITH` keyword, e.g. `WITH (k = v)`.
3295    With(Vec<SqlOption>),
3296    /// Options specified using the `OPTIONS(...)` clause.
3297    Options(Vec<SqlOption>),
3298    /// Plain space-separated options.
3299    Plain(Vec<SqlOption>),
3300    /// Table properties (e.g., TBLPROPERTIES / storage properties).
3301    TableProperties(Vec<SqlOption>),
3302}
3303
3304impl fmt::Display for CreateTableOptions {
3305    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3306        match self {
3307            CreateTableOptions::With(with_options) => {
3308                write!(f, "WITH ({})", display_comma_separated(with_options))
3309            }
3310            CreateTableOptions::Options(options) => {
3311                write!(f, "OPTIONS({})", display_comma_separated(options))
3312            }
3313            CreateTableOptions::TableProperties(options) => {
3314                write!(f, "TBLPROPERTIES ({})", display_comma_separated(options))
3315            }
3316            CreateTableOptions::Plain(options) => {
3317                write!(f, "{}", display_separated(options, " "))
3318            }
3319            CreateTableOptions::None => Ok(()),
3320        }
3321    }
3322}
3323
3324/// A `FROM` clause within a `DELETE` statement.
3325///
3326/// Syntax
3327/// ```sql
3328/// [FROM] table
3329/// ```
3330#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3331#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3332#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3333pub enum FromTable {
3334    /// An explicit `FROM` keyword was specified.
3335    WithFromKeyword(Vec<TableWithJoins>),
3336    /// BigQuery: `FROM` keyword was omitted.
3337    /// <https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#delete_statement>
3338    WithoutKeyword(Vec<TableWithJoins>),
3339}
3340impl Display for FromTable {
3341    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3342        match self {
3343            FromTable::WithFromKeyword(tables) => {
3344                write!(f, "FROM {}", display_comma_separated(tables))
3345            }
3346            FromTable::WithoutKeyword(tables) => {
3347                write!(f, "{}", display_comma_separated(tables))
3348            }
3349        }
3350    }
3351}
3352
3353#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3354#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3355#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3356/// Variants for the `SET` family of statements.
3357pub enum Set {
3358    /// SQL Standard-style
3359    /// SET a = 1;
3360    /// `SET var = value` (standard SQL-style assignment).
3361    SingleAssignment {
3362        /// Optional scope modifier (`SESSION` / `LOCAL`).
3363        scope: Option<ContextModifier>,
3364        /// Whether this is a Hive-style `HIVEVAR:` assignment.
3365        hivevar: bool,
3366        /// Variable name to assign.
3367        variable: ObjectName,
3368        /// Values assigned to the variable.
3369        values: Vec<Expr>,
3370    },
3371    /// Snowflake-style
3372    /// SET (a, b, ..) = (1, 2, ..);
3373    /// `SET (a, b) = (1, 2)` (tuple assignment syntax).
3374    ParenthesizedAssignments {
3375        /// Variables being assigned in tuple form.
3376        variables: Vec<ObjectName>,
3377        /// Corresponding values for the variables.
3378        values: Vec<Expr>,
3379    },
3380    /// MySQL-style
3381    /// SET a = 1, b = 2, ..;
3382    /// `SET a = 1, b = 2` (MySQL-style comma-separated assignments).
3383    MultipleAssignments {
3384        /// List of `SET` assignments (MySQL-style comma-separated).
3385        assignments: Vec<SetAssignment>,
3386    },
3387    /// Session authorization for Postgres/Redshift
3388    ///
3389    /// ```sql
3390    /// SET SESSION AUTHORIZATION { user_name | DEFAULT }
3391    /// ```
3392    ///
3393    /// See <https://www.postgresql.org/docs/current/sql-set-session-authorization.html>
3394    /// See <https://docs.aws.amazon.com/redshift/latest/dg/r_SET_SESSION_AUTHORIZATION.html>
3395    SetSessionAuthorization(SetSessionAuthorizationParam),
3396    /// MS-SQL session
3397    ///
3398    /// See <https://learn.microsoft.com/en-us/sql/t-sql/statements/set-statements-transact-sql>
3399    SetSessionParam(SetSessionParamKind),
3400    /// ```sql
3401    /// SET [ SESSION | LOCAL ] ROLE role_name
3402    /// ```
3403    ///
3404    /// Sets session state. Examples: [ANSI][1], [Postgresql][2], [MySQL][3], and [Oracle][4]
3405    ///
3406    /// [1]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#set-role-statement
3407    /// [2]: https://www.postgresql.org/docs/14/sql-set-role.html
3408    /// [3]: https://dev.mysql.com/doc/refman/8.0/en/set-role.html
3409    /// [4]: https://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_10004.htm
3410    SetRole {
3411        /// Non-ANSI optional identifier to inform if the role is defined inside the current session (`SESSION`) or transaction (`LOCAL`).
3412        context_modifier: Option<ContextModifier>,
3413        /// Role name. If NONE is specified, then the current role name is removed.
3414        role_name: Option<Ident>,
3415    },
3416    /// ```sql
3417    /// SET TIME ZONE <value>
3418    /// ```
3419    ///
3420    /// Note: this is a PostgreSQL-specific statements
3421    /// `SET TIME ZONE <value>` is an alias for `SET timezone TO <value>` in PostgreSQL
3422    /// However, we allow it for all dialects.
3423    /// `SET TIME ZONE` statement. `local` indicates the `LOCAL` keyword.
3424    /// `SET TIME ZONE <value>` statement.
3425    SetTimeZone {
3426        /// Whether the `LOCAL` keyword was specified.
3427        local: bool,
3428        /// Time zone expression value.
3429        value: Expr,
3430    },
3431    /// ```sql
3432    /// SET NAMES 'charset_name' [COLLATE 'collation_name']
3433    /// ```
3434    SetNames {
3435        /// Character set name to set.
3436        charset_name: Ident,
3437        /// Optional collation name.
3438        collation_name: Option<String>,
3439    },
3440    /// ```sql
3441    /// SET NAMES DEFAULT
3442    /// ```
3443    ///
3444    /// Note: this is a MySQL-specific statement.
3445    SetNamesDefault {},
3446    /// ```sql
3447    /// SET TRANSACTION ...
3448    /// ```
3449    SetTransaction {
3450        /// Transaction modes (e.g., ISOLATION LEVEL, READ ONLY).
3451        modes: Vec<TransactionMode>,
3452        /// Optional snapshot value for transaction snapshot control.
3453        snapshot: Option<ValueWithSpan>,
3454        /// `true` when the `SESSION` keyword was used.
3455        session: bool,
3456    },
3457}
3458
3459impl Display for Set {
3460    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3461        match self {
3462            Self::ParenthesizedAssignments { variables, values } => write!(
3463                f,
3464                "SET ({}) = ({})",
3465                display_comma_separated(variables),
3466                display_comma_separated(values)
3467            ),
3468            Self::MultipleAssignments { assignments } => {
3469                write!(f, "SET {}", display_comma_separated(assignments))
3470            }
3471            Self::SetRole {
3472                context_modifier,
3473                role_name,
3474            } => {
3475                let role_name = role_name.clone().unwrap_or_else(|| Ident::new("NONE"));
3476                write!(
3477                    f,
3478                    "SET {modifier}ROLE {role_name}",
3479                    modifier = context_modifier.map(|m| format!("{m}")).unwrap_or_default()
3480                )
3481            }
3482            Self::SetSessionAuthorization(kind) => write!(f, "SET SESSION AUTHORIZATION {kind}"),
3483            Self::SetSessionParam(kind) => write!(f, "SET {kind}"),
3484            Self::SetTransaction {
3485                modes,
3486                snapshot,
3487                session,
3488            } => {
3489                if *session {
3490                    write!(f, "SET SESSION CHARACTERISTICS AS TRANSACTION")?;
3491                } else {
3492                    write!(f, "SET TRANSACTION")?;
3493                }
3494                if !modes.is_empty() {
3495                    write!(f, " {}", display_comma_separated(modes))?;
3496                }
3497                if let Some(snapshot_id) = snapshot {
3498                    write!(f, " SNAPSHOT {snapshot_id}")?;
3499                }
3500                Ok(())
3501            }
3502            Self::SetTimeZone { local, value } => {
3503                f.write_str("SET ")?;
3504                if *local {
3505                    f.write_str("LOCAL ")?;
3506                }
3507                write!(f, "TIME ZONE {value}")
3508            }
3509            Self::SetNames {
3510                charset_name,
3511                collation_name,
3512            } => {
3513                write!(f, "SET NAMES {charset_name}")?;
3514
3515                if let Some(collation) = collation_name {
3516                    f.write_str(" COLLATE ")?;
3517                    f.write_str(collation)?;
3518                };
3519
3520                Ok(())
3521            }
3522            Self::SetNamesDefault {} => {
3523                f.write_str("SET NAMES DEFAULT")?;
3524
3525                Ok(())
3526            }
3527            Set::SingleAssignment {
3528                scope,
3529                hivevar,
3530                variable,
3531                values,
3532            } => {
3533                write!(
3534                    f,
3535                    "SET {}{}{} = {}",
3536                    scope.map(|s| format!("{s}")).unwrap_or_default(),
3537                    if *hivevar { "HIVEVAR:" } else { "" },
3538                    variable,
3539                    display_comma_separated(values)
3540                )
3541            }
3542        }
3543    }
3544}
3545
3546/// A representation of a `WHEN` arm with all the identifiers catched and the statements to execute
3547/// for the arm.
3548///
3549/// Snowflake: <https://docs.snowflake.com/en/sql-reference/snowflake-scripting/exception>
3550/// BigQuery: <https://cloud.google.com/bigquery/docs/reference/standard-sql/procedural-language#beginexceptionend>
3551#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3552#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3553#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3554pub struct ExceptionWhen {
3555    /// Identifiers that trigger this branch (error conditions).
3556    pub idents: Vec<Ident>,
3557    /// Statements to execute when the condition matches.
3558    pub statements: Vec<Statement>,
3559}
3560
3561impl Display for ExceptionWhen {
3562    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3563        write!(
3564            f,
3565            "WHEN {idents} THEN",
3566            idents = display_separated(&self.idents, " OR ")
3567        )?;
3568
3569        if !self.statements.is_empty() {
3570            write!(f, " ")?;
3571            format_statement_list(f, &self.statements)?;
3572        }
3573
3574        Ok(())
3575    }
3576}
3577
3578/// ANALYZE statement
3579///
3580/// Supported syntax varies by dialect:
3581/// - Hive: `ANALYZE TABLE t [PARTITION (...)] COMPUTE STATISTICS [NOSCAN] [FOR COLUMNS [col1, ...]] [CACHE METADATA]`
3582/// - PostgreSQL: `ANALYZE [VERBOSE] [t [(col1, ...)]]` See <https://www.postgresql.org/docs/current/sql-analyze.html>
3583/// - General: `ANALYZE [TABLE] t`
3584#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3585#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3586#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3587pub struct Analyze {
3588    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3589    /// Name of the table to analyze. `None` for bare `ANALYZE`.
3590    pub table_name: Option<ObjectName>,
3591    /// Optional partition expressions to restrict the analysis.
3592    pub partitions: Option<Vec<Expr>>,
3593    /// `true` when analyzing specific columns (Hive `FOR COLUMNS` syntax).
3594    pub for_columns: bool,
3595    /// Columns to analyze.
3596    pub columns: Vec<Ident>,
3597    /// Whether to cache metadata before analyzing.
3598    pub cache_metadata: bool,
3599    /// Whether to skip scanning the table.
3600    pub noscan: bool,
3601    /// Whether to compute statistics during analysis.
3602    pub compute_statistics: bool,
3603    /// Whether the `TABLE` keyword was present.
3604    pub has_table_keyword: bool,
3605}
3606
3607impl fmt::Display for Analyze {
3608    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3609        write!(f, "ANALYZE")?;
3610        if let Some(ref table_name) = self.table_name {
3611            if self.has_table_keyword {
3612                write!(f, " TABLE")?;
3613            }
3614            write!(f, " {table_name}")?;
3615        }
3616        if !self.for_columns && !self.columns.is_empty() {
3617            write!(f, " ({})", display_comma_separated(&self.columns))?;
3618        }
3619        if let Some(ref parts) = self.partitions {
3620            if !parts.is_empty() {
3621                write!(f, " PARTITION ({})", display_comma_separated(parts))?;
3622            }
3623        }
3624        if self.compute_statistics {
3625            write!(f, " COMPUTE STATISTICS")?;
3626        }
3627        if self.noscan {
3628            write!(f, " NOSCAN")?;
3629        }
3630        if self.cache_metadata {
3631            write!(f, " CACHE METADATA")?;
3632        }
3633        if self.for_columns {
3634            write!(f, " FOR COLUMNS")?;
3635            if !self.columns.is_empty() {
3636                write!(f, " {}", display_comma_separated(&self.columns))?;
3637            }
3638        }
3639        Ok(())
3640    }
3641}
3642
3643/// A top-level statement (SELECT, INSERT, CREATE, etc.)
3644#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3645#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3646#[cfg_attr(
3647    feature = "visitor",
3648    derive(Visit, VisitMut),
3649    visit(with = "visit_statement")
3650)]
3651pub enum Statement {
3652    /// ```sql
3653    /// ANALYZE
3654    /// ```
3655    /// Analyze (Hive)
3656    Analyze(Analyze),
3657    /// `SET` statements (session, transaction, timezone, etc.).
3658    Set(Set),
3659    /// ```sql
3660    /// TRUNCATE
3661    /// ```
3662    /// Truncate (Hive)
3663    Truncate(Truncate),
3664    /// ```sql
3665    /// MSCK
3666    /// ```
3667    /// Msck (Hive)
3668    Msck(Msck),
3669    /// ```sql
3670    /// SELECT
3671    /// ```
3672    Query(Box<Query>),
3673    /// ```sql
3674    /// INSERT
3675    /// ```
3676    Insert(Insert),
3677    /// ```sql
3678    /// INSTALL
3679    /// ```
3680    Install {
3681        /// Only for DuckDB
3682        extension_name: Ident,
3683    },
3684    /// ```sql
3685    /// LOAD
3686    /// ```
3687    Load {
3688        /// Only for DuckDB
3689        extension_name: Ident,
3690    },
3691    // TODO: Support ROW FORMAT
3692    /// LOAD DATA from a directory or query source.
3693    Directory {
3694        /// Whether to overwrite existing files.
3695        overwrite: bool,
3696        /// Whether the directory is local to the server.
3697        local: bool,
3698        /// Path to the directory or files.
3699        path: String,
3700        /// Optional file format for the data.
3701        file_format: Option<FileFormat>,
3702        /// Source query providing data to load.
3703        source: Box<Query>,
3704    },
3705    /// A `CASE` statement.
3706    Case(CaseStatement),
3707    /// An `IF` statement.
3708    If(IfStatement),
3709    /// A `WHILE` statement.
3710    While(WhileStatement),
3711    /// A `RAISE` statement.
3712    Raise(RaiseStatement),
3713    /// ```sql
3714    /// CALL <function>
3715    /// ```
3716    Call(Function),
3717    /// ```sql
3718    /// COPY [TO | FROM] ...
3719    /// ```
3720    Copy {
3721        /// The source of 'COPY TO', or the target of 'COPY FROM'
3722        source: CopySource,
3723        /// If true, is a 'COPY TO' statement. If false is a 'COPY FROM'
3724        to: bool,
3725        /// The target of 'COPY TO', or the source of 'COPY FROM'
3726        target: CopyTarget,
3727        /// WITH options (from PostgreSQL version 9.0)
3728        options: Vec<CopyOption>,
3729        /// WITH options (before PostgreSQL version 9.0)
3730        legacy_options: Vec<CopyLegacyOption>,
3731        /// The inline payload of `COPY ... FROM STDIN`, captured verbatim
3732        /// from the source text. `None` when the statement carries no
3733        /// inline data.
3734        payload: Option<CopyPayload>,
3735    },
3736    /// ```sql
3737    /// COPY INTO <table> | <location>
3738    /// ```
3739    /// See:
3740    /// <https://docs.snowflake.com/en/sql-reference/sql/copy-into-table>
3741    /// <https://docs.snowflake.com/en/sql-reference/sql/copy-into-location>
3742    ///
3743    /// Copy Into syntax available for Snowflake is different than the one implemented in
3744    /// Postgres. Although they share common prefix, it is reasonable to implement them
3745    /// in different enums. This can be refactored later once custom dialects
3746    /// are allowed to have custom Statements.
3747    CopyIntoSnowflake {
3748        /// Kind of COPY INTO operation (table or location).
3749        kind: CopyIntoSnowflakeKind,
3750        /// Target object for the COPY INTO operation.
3751        into: ObjectName,
3752        /// Optional list of target columns.
3753        into_columns: Option<Vec<Ident>>,
3754        /// Optional source object name (staged data).
3755        from_obj: Option<ObjectName>,
3756        /// Optional alias for the source object.
3757        from_obj_alias: Option<Ident>,
3758        /// Stage-specific parameters (e.g., credentials, path).
3759        stage_params: StageParamsObject,
3760        /// Optional list of transformations applied when loading.
3761        from_transformations: Option<Vec<StageLoadSelectItemKind>>,
3762        /// Optional source query instead of a staged object.
3763        from_query: Option<Box<Query>>,
3764        /// Optional list of specific file names to load.
3765        files: Option<Vec<String>>,
3766        /// Optional filename matching pattern.
3767        pattern: Option<String>,
3768        /// File format options.
3769        file_format: KeyValueOptions,
3770        /// Additional copy options.
3771        copy_options: KeyValueOptions,
3772        /// Optional validation mode string.
3773        validation_mode: Option<String>,
3774        /// Optional partition expression for loading.
3775        partition: Option<Box<Expr>>,
3776    },
3777    /// ```sql
3778    /// OPEN cursor_name
3779    /// ```
3780    /// Opens a cursor.
3781    Open(OpenStatement),
3782    /// ```sql
3783    /// CLOSE
3784    /// ```
3785    /// Closes the portal underlying an open cursor.
3786    Close {
3787        /// Cursor name
3788        cursor: CloseCursor,
3789    },
3790    /// ```sql
3791    /// UPDATE
3792    /// ```
3793    Update(Update),
3794    /// ```sql
3795    /// DELETE
3796    /// ```
3797    Delete(Delete),
3798    /// ```sql
3799    /// CREATE VIEW
3800    /// ```
3801    CreateView(CreateView),
3802    /// ```sql
3803    /// CREATE TABLE
3804    /// ```
3805    CreateTable(CreateTable),
3806    /// ```sql
3807    /// CREATE VIRTUAL TABLE .. USING <module_name> (<module_args>)`
3808    /// ```
3809    /// Sqlite specific statement
3810    CreateVirtualTable {
3811        #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3812        /// Name of the virtual table module instance.
3813        name: ObjectName,
3814        /// `true` when `IF NOT EXISTS` was specified.
3815        if_not_exists: bool,
3816        /// Module name used by the virtual table.
3817        module_name: Ident,
3818        /// Arguments passed to the module.
3819        module_args: Vec<Ident>,
3820    },
3821    /// ```sql
3822    /// `CREATE INDEX`
3823    /// ```
3824    CreateIndex(CreateIndex),
3825    /// ```sql
3826    /// CREATE ROLE
3827    /// ```
3828    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createrole.html)
3829    CreateRole(CreateRole),
3830    /// ```sql
3831    /// CREATE SECRET
3832    /// ```
3833    /// See [DuckDB](https://duckdb.org/docs/sql/statements/create_secret.html)
3834    CreateSecret {
3835        /// `true` when `OR REPLACE` was specified.
3836        or_replace: bool,
3837        /// Optional `TEMPORARY` flag.
3838        temporary: Option<bool>,
3839        /// `true` when `IF NOT EXISTS` was present.
3840        if_not_exists: bool,
3841        /// Optional secret name.
3842        name: Option<Ident>,
3843        /// Optional storage specifier identifier.
3844        storage_specifier: Option<Ident>,
3845        /// The secret type identifier.
3846        secret_type: Ident,
3847        /// Additional secret options.
3848        options: Vec<SecretOption>,
3849    },
3850    /// A `CREATE SERVER` statement.
3851    CreateServer(CreateServerStatement),
3852    /// ```sql
3853    /// CREATE FOREIGN TABLE
3854    /// ```
3855    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createforeigntable.html)
3856    CreateForeignTable(CreateForeignTable),
3857    /// ```sql
3858    /// CREATE FOREIGN DATA WRAPPER
3859    /// ```
3860    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createforeigndatawrapper.html)
3861    CreateForeignDataWrapper(CreateForeignDataWrapper),
3862    /// ```sql
3863    /// CREATE USER MAPPING
3864    /// ```
3865    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createusermapping.html)
3866    CreateUserMapping(CreateUserMapping),
3867    /// ```sql
3868    /// CREATE POLICY
3869    /// ```
3870    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createpolicy.html)
3871    CreatePolicy(CreatePolicy),
3872    /// ```sql
3873    /// CREATE RULE
3874    /// ```
3875    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createrule.html)
3876    CreateRule(CreateRule),
3877    /// ```sql
3878    /// CREATE CONNECTOR
3879    /// ```
3880    /// See [Hive](https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=27362034#LanguageManualDDL-CreateDataConnectorCreateConnector)
3881    CreateConnector(CreateConnector),
3882    /// ```sql
3883    /// CREATE OPERATOR
3884    /// ```
3885    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createoperator.html)
3886    CreateOperator(CreateOperator),
3887    /// ```sql
3888    /// CREATE OPERATOR FAMILY
3889    /// ```
3890    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createopfamily.html)
3891    CreateOperatorFamily(CreateOperatorFamily),
3892    /// ```sql
3893    /// CREATE OPERATOR CLASS
3894    /// ```
3895    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createopclass.html)
3896    CreateOperatorClass(CreateOperatorClass),
3897    /// A `CREATE TEXT SEARCH` statement.
3898    ///
3899    /// See [PostgreSQL](https://www.postgresql.org/docs/current/textsearch-intro.html)
3900    CreateTextSearch(CreateTextSearch),
3901    /// ```sql
3902    /// CREATE AGGREGATE
3903    /// ```
3904    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createaggregate.html)
3905    CreateAggregate(CreateAggregate),
3906    /// ```sql
3907    /// ALTER TABLE
3908    /// ```
3909    AlterTable(AlterTable),
3910    /// ```sql
3911    /// ALTER SCHEMA
3912    /// ```
3913    /// See [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#alter_schema_collate_statement)
3914    AlterSchema(AlterSchema),
3915    /// ```sql
3916    /// ALTER INDEX
3917    /// ```
3918    AlterIndex {
3919        /// Name of the index to alter.
3920        name: ObjectName,
3921        /// The operation to perform on the index.
3922        operation: AlterIndexOperation,
3923    },
3924    /// ```sql
3925    /// ALTER [ MATERIALIZED ] VIEW
3926    /// ```
3927    AlterView(AlterView),
3928    /// ```sql
3929    /// ALTER FUNCTION
3930    /// ALTER AGGREGATE
3931    /// ```
3932    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-alterfunction.html)
3933    /// and [PostgreSQL](https://www.postgresql.org/docs/current/sql-alteraggregate.html)
3934    AlterFunction(AlterFunction),
3935    /// ```sql
3936    /// ALTER TYPE
3937    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-altertype.html)
3938    /// ```
3939    AlterType(AlterType),
3940    /// ```sql
3941    /// ALTER COLLATION
3942    /// ```
3943    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-altercollation.html)
3944    AlterCollation(AlterCollation),
3945    /// ```sql
3946    /// ALTER OPERATOR
3947    /// ```
3948    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-alteroperator.html)
3949    AlterOperator(AlterOperator),
3950    /// ```sql
3951    /// ALTER OPERATOR FAMILY
3952    /// ```
3953    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-alteropfamily.html)
3954    AlterOperatorFamily(AlterOperatorFamily),
3955    /// ```sql
3956    /// ALTER OPERATOR CLASS
3957    /// ```
3958    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-alteropclass.html)
3959    AlterOperatorClass(AlterOperatorClass),
3960    /// An `ALTER TEXT SEARCH` statement.
3961    ///
3962    /// See [PostgreSQL](https://www.postgresql.org/docs/current/textsearch-configuration.html)
3963    AlterTextSearch(AlterTextSearch),
3964    /// ```sql
3965    /// ALTER ROLE
3966    /// ```
3967    AlterRole {
3968        /// Role name being altered.
3969        name: Ident,
3970        /// Operation to perform on the role.
3971        operation: AlterRoleOperation,
3972    },
3973    /// ```sql
3974    /// ALTER POLICY <NAME> ON <TABLE NAME> [<OPERATION>]
3975    /// ```
3976    /// (Postgresql-specific)
3977    AlterPolicy(AlterPolicy),
3978    /// ```sql
3979    /// ALTER TRIGGER <NAME> ON <TABLE NAME> <OPERATION>
3980    /// ```
3981    /// (Postgresql-specific)
3982    AlterTrigger(AlterTrigger),
3983    /// ```sql
3984    /// ALTER CONNECTOR connector_name SET DCPROPERTIES(property_name=property_value, ...);
3985    /// or
3986    /// ALTER CONNECTOR connector_name SET URL new_url;
3987    /// or
3988    /// ALTER CONNECTOR connector_name SET OWNER [USER|ROLE] user_or_role;
3989    /// ```
3990    /// (Hive-specific)
3991    AlterConnector {
3992        /// Name of the connector to alter.
3993        name: Ident,
3994        /// Optional connector properties to set.
3995        properties: Option<Vec<SqlOption>>,
3996        /// Optional new URL for the connector.
3997        url: Option<String>,
3998        /// Optional new owner specification.
3999        owner: Option<ddl::AlterConnectorOwner>,
4000    },
4001    /// ```sql
4002    /// ALTER SESSION SET sessionParam
4003    /// ALTER SESSION UNSET <param_name> [ , <param_name> , ... ]
4004    /// ```
4005    /// See <https://docs.snowflake.com/en/sql-reference/sql/alter-session>
4006    AlterSession {
4007        /// true is to set for the session parameters, false is to unset
4008        set: bool,
4009        /// The session parameters to set or unset
4010        session_params: KeyValueOptions,
4011    },
4012    /// ```sql
4013    /// ATTACH DATABASE 'path/to/file' AS alias
4014    /// ```
4015    /// (SQLite-specific)
4016    AttachDatabase {
4017        /// The name to bind to the newly attached database
4018        schema_name: Ident,
4019        /// An expression that indicates the path to the database file
4020        database_file_name: Expr,
4021        /// true if the syntax is 'ATTACH DATABASE', false if it's just 'ATTACH'
4022        database: bool,
4023    },
4024    /// (DuckDB-specific)
4025    /// ```sql
4026    /// ATTACH 'sqlite_file.db' AS sqlite_db (READ_ONLY, TYPE SQLITE);
4027    /// ```
4028    /// See <https://duckdb.org/docs/sql/statements/attach.html>
4029    AttachDuckDBDatabase {
4030        /// `true` when `IF NOT EXISTS` was present.
4031        if_not_exists: bool,
4032        /// `true` if the syntax used `ATTACH DATABASE` rather than `ATTACH`.
4033        database: bool,
4034        /// The path identifier to the database file being attached.
4035        database_path: Ident,
4036        /// Optional alias assigned to the attached database.
4037        database_alias: Option<Ident>,
4038        /// Dialect-specific attach options (e.g., `READ_ONLY`).
4039        attach_options: Vec<AttachDuckDBDatabaseOption>,
4040    },
4041    /// (DuckDB-specific)
4042    /// ```sql
4043    /// DETACH db_alias;
4044    /// ```
4045    /// See <https://duckdb.org/docs/sql/statements/attach.html>
4046    DetachDuckDBDatabase {
4047        /// `true` when `IF EXISTS` was present.
4048        if_exists: bool,
4049        /// `true` if the syntax used `DETACH DATABASE` rather than `DETACH`.
4050        database: bool,
4051        /// Alias of the database to detach.
4052        database_alias: Ident,
4053    },
4054    /// ```sql
4055    /// DROP [TABLE, VIEW, ...]
4056    /// ```
4057    Drop {
4058        /// The type of the object to drop: TABLE, VIEW, etc.
4059        object_type: ObjectType,
4060        /// An optional `IF EXISTS` clause. (Non-standard.)
4061        if_exists: bool,
4062        /// One or more objects to drop. (ANSI SQL requires exactly one.)
4063        names: Vec<ObjectName>,
4064        /// Whether `CASCADE` was specified. This will be `false` when
4065        /// `RESTRICT` or no drop behavior at all was specified.
4066        cascade: bool,
4067        /// Whether `RESTRICT` was specified. This will be `false` when
4068        /// `CASCADE` or no drop behavior at all was specified.
4069        restrict: bool,
4070        /// Hive allows you specify whether the table's stored data will be
4071        /// deleted along with the dropped table
4072        purge: bool,
4073        /// MySQL-specific "TEMPORARY" keyword
4074        temporary: bool,
4075        /// MySQL-specific drop index syntax, which requires table specification
4076        /// See <https://dev.mysql.com/doc/refman/8.4/en/drop-index.html>
4077        table: Option<ObjectName>,
4078    },
4079    /// ```sql
4080    /// DROP FUNCTION
4081    /// ```
4082    DropFunction(DropFunction),
4083    /// ```sql
4084    /// DROP DOMAIN
4085    /// ```
4086    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-dropdomain.html)
4087    ///
4088    /// DROP DOMAIN [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ]
4089    ///
4090    DropDomain(DropDomain),
4091    /// ```sql
4092    /// DROP PROCEDURE
4093    /// ```
4094    DropProcedure {
4095        /// `true` when `IF EXISTS` was present.
4096        if_exists: bool,
4097        /// One or more functions/procedures to drop.
4098        proc_desc: Vec<FunctionDesc>,
4099        /// Optional drop behavior (`CASCADE` or `RESTRICT`).
4100        drop_behavior: Option<DropBehavior>,
4101    },
4102    /// ```sql
4103    /// DROP SECRET
4104    /// ```
4105    DropSecret {
4106        /// `true` when `IF EXISTS` was present.
4107        if_exists: bool,
4108        /// Optional `TEMPORARY` marker.
4109        temporary: Option<bool>,
4110        /// Name of the secret to drop.
4111        name: Ident,
4112        /// Optional storage specifier identifier.
4113        storage_specifier: Option<Ident>,
4114    },
4115    ///```sql
4116    /// DROP POLICY
4117    /// ```
4118    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-droppolicy.html)
4119    DropPolicy(DropPolicy),
4120    /// ```sql
4121    /// DROP RULE
4122    /// ```
4123    /// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-droprule.html)
4124    DropRule(DropRule),
4125    /// ```sql
4126    /// DROP CONNECTOR
4127    /// ```
4128    /// See [Hive](https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=27362034#LanguageManualDDL-DropConnector)
4129    DropConnector {
4130        /// `true` when `IF EXISTS` was present.
4131        if_exists: bool,
4132        /// Name of the connector to drop.
4133        name: Ident,
4134    },
4135    /// ```sql
4136    /// DECLARE
4137    /// ```
4138    /// Declare Cursor Variables
4139    ///
4140    /// Note: this is a PostgreSQL-specific statement,
4141    /// but may also compatible with other SQL.
4142    Declare {
4143        /// Cursor declaration statements collected by `DECLARE`.
4144        stmts: Vec<Declare>,
4145        /// Separator between `stmts` in the rendered SQL.
4146        separator: DeclareSeparator,
4147    },
4148    /// ```sql
4149    /// CREATE EXTENSION [ IF NOT EXISTS ] extension_name
4150    ///     [ WITH ] [ SCHEMA schema_name ]
4151    ///              [ VERSION version ]
4152    ///              [ CASCADE ]
4153    /// ```
4154    ///
4155    /// Note: this is a PostgreSQL-specific statement,
4156    CreateExtension(CreateExtension),
4157    /// ```sql
4158    /// CREATE COLLATION
4159    /// ```
4160    /// Note: this is a PostgreSQL-specific statement.
4161    /// <https://www.postgresql.org/docs/current/sql-createcollation.html>
4162    CreateCollation(CreateCollation),
4163    /// ```sql
4164    /// DROP EXTENSION [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ]
4165    /// ```
4166    /// Note: this is a PostgreSQL-specific statement.
4167    /// <https://www.postgresql.org/docs/current/sql-dropextension.html>
4168    DropExtension(DropExtension),
4169    /// ```sql
4170    /// DROP OPERATOR [ IF EXISTS ] name ( { left_type | NONE } , right_type ) [, ...] [ CASCADE | RESTRICT ]
4171    /// ```
4172    /// Note: this is a PostgreSQL-specific statement.
4173    /// <https://www.postgresql.org/docs/current/sql-dropoperator.html>
4174    DropOperator(DropOperator),
4175    /// ```sql
4176    /// DROP OPERATOR FAMILY [ IF EXISTS ] name USING index_method [ CASCADE | RESTRICT ]
4177    /// ```
4178    /// Note: this is a PostgreSQL-specific statement.
4179    /// <https://www.postgresql.org/docs/current/sql-dropopfamily.html>
4180    DropOperatorFamily(DropOperatorFamily),
4181    /// ```sql
4182    /// DROP OPERATOR CLASS [ IF EXISTS ] name USING index_method [ CASCADE | RESTRICT ]
4183    /// ```
4184    /// Note: this is a PostgreSQL-specific statement.
4185    /// <https://www.postgresql.org/docs/current/sql-dropopclass.html>
4186    DropOperatorClass(DropOperatorClass),
4187    /// ```sql
4188    /// FETCH
4189    /// ```
4190    /// Retrieve rows from a query using a cursor
4191    ///
4192    /// Note: this is a PostgreSQL-specific statement,
4193    /// but may also compatible with other SQL.
4194    Fetch {
4195        /// Cursor name
4196        name: Ident,
4197        /// The fetch direction (e.g., `FORWARD`, `BACKWARD`).
4198        direction: FetchDirection,
4199        /// The fetch position (e.g., `ALL`, `NEXT`, `ABSOLUTE`).
4200        position: FetchPosition,
4201        /// Optional target table to fetch rows into.
4202        into: Option<ObjectName>,
4203    },
4204    /// ```sql
4205    /// FLUSH [NO_WRITE_TO_BINLOG | LOCAL] flush_option [, flush_option] ... | tables_option
4206    /// ```
4207    ///
4208    /// Note: this is a Mysql-specific statement,
4209    /// but may also compatible with other SQL.
4210    Flush {
4211        /// The specific flush option or object to flush.
4212        object_type: FlushType,
4213        /// Optional flush location (dialect-specific).
4214        location: Option<FlushLocation>,
4215        /// Optional channel name used for flush operations.
4216        channel: Option<String>,
4217        /// Whether a read lock was requested.
4218        read_lock: bool,
4219        /// Whether this is an export flush operation.
4220        export: bool,
4221        /// Optional list of tables involved in the flush.
4222        tables: Vec<ObjectName>,
4223    },
4224    /// ```sql
4225    /// DISCARD [ ALL | PLANS | SEQUENCES | TEMPORARY | TEMP ]
4226    /// ```
4227    ///
4228    /// Note: this is a PostgreSQL-specific statement,
4229    /// but may also compatible with other SQL.
4230    Discard {
4231        /// The kind of object(s) to discard (ALL, PLANS, etc.).
4232        object_type: DiscardObject,
4233    },
4234    /// `SHOW FUNCTIONS`
4235    ///
4236    /// Note: this is a Presto-specific statement.
4237    ShowFunctions {
4238        /// Optional filter for which functions to display.
4239        filter: Option<ShowStatementFilter>,
4240    },
4241    /// ```sql
4242    /// SHOW <variable>
4243    /// ```
4244    ///
4245    /// Note: this is a PostgreSQL-specific statement.
4246    ShowVariable {
4247        /// Variable name as one or more identifiers.
4248        variable: Vec<Ident>,
4249    },
4250    /// ```sql
4251    /// SHOW [GLOBAL | SESSION] STATUS [LIKE 'pattern' | WHERE expr]
4252    /// ```
4253    ///
4254    /// Note: this is a MySQL-specific statement.
4255    ShowStatus {
4256        /// Optional filter for which status entries to display.
4257        filter: Option<ShowStatementFilter>,
4258        /// `true` when `GLOBAL` scope was requested.
4259        global: bool,
4260        /// `true` when `SESSION` scope was requested.
4261        session: bool,
4262    },
4263    /// ```sql
4264    /// SHOW VARIABLES
4265    /// ```
4266    ///
4267    /// Note: this is a MySQL-specific statement.
4268    ShowVariables {
4269        /// Optional filter for which variables to display.
4270        filter: Option<ShowStatementFilter>,
4271        /// `true` when `GLOBAL` scope was requested.
4272        global: bool,
4273        /// `true` when `SESSION` scope was requested.
4274        session: bool,
4275    },
4276    /// ```sql
4277    /// SHOW CREATE TABLE
4278    /// ```
4279    ///
4280    /// Note: this is a MySQL-specific statement.
4281    ShowCreate {
4282        /// The kind of object being shown (TABLE, VIEW, etc.).
4283        obj_type: ShowCreateObject,
4284        /// The name of the object to show create statement for.
4285        obj_name: ObjectName,
4286    },
4287    /// ```sql
4288    /// SHOW COLUMNS
4289    /// ```
4290    ShowColumns {
4291        /// `true` when extended column information was requested.
4292        extended: bool,
4293        /// `true` when full column details were requested.
4294        full: bool,
4295        /// Additional options for `SHOW COLUMNS`.
4296        show_options: ShowStatementOptions,
4297    },
4298    /// ```sql
4299    /// SHOW CATALOGS
4300    /// ```
4301    ShowCatalogs {
4302        /// `true` when terse output format was requested.
4303        terse: bool,
4304        /// `true` when history information was requested.
4305        history: bool,
4306        /// Additional options for `SHOW CATALOGS`.
4307        show_options: ShowStatementOptions,
4308    },
4309    /// ```sql
4310    /// SHOW DATABASES
4311    /// ```
4312    ShowDatabases {
4313        /// `true` when terse output format was requested.
4314        terse: bool,
4315        /// `true` when history information was requested.
4316        history: bool,
4317        /// Additional options for `SHOW DATABASES`.
4318        show_options: ShowStatementOptions,
4319    },
4320    /// ```sql
4321    /// SHOW [FULL] PROCESSLIST
4322    /// ```
4323    ///
4324    /// Note: this is a MySQL-specific statement.
4325    ShowProcessList {
4326        /// `true` when full process information was requested.
4327        full: bool,
4328    },
4329    /// ```sql
4330    /// SHOW SCHEMAS
4331    /// ```
4332    ShowSchemas {
4333        /// `true` when terse (compact) output was requested.
4334        terse: bool,
4335        /// `true` when history information was requested.
4336        history: bool,
4337        /// Additional options for `SHOW SCHEMAS`.
4338        show_options: ShowStatementOptions,
4339    },
4340    // ```sql
4341    // SHOW {CHARACTER SET | CHARSET}
4342    // ```
4343    // [MySQL]:
4344    // <https://dev.mysql.com/doc/refman/8.4/en/show.html#:~:text=SHOW%20%7BCHARACTER%20SET%20%7C%20CHARSET%7D%20%5Blike_or_where%5D>
4345    /// Show the available character sets (alias `CHARSET`).
4346    ShowCharset(ShowCharset),
4347    /// ```sql
4348    /// SHOW OBJECTS LIKE 'line%' IN mydb.public
4349    /// ```
4350    /// Snowflake-specific statement
4351    /// <https://docs.snowflake.com/en/sql-reference/sql/show-objects>
4352    ShowObjects(ShowObjects),
4353    /// ```sql
4354    /// SHOW TABLES
4355    /// ```
4356    ShowTables {
4357        /// `true` when terse output format was requested (compact listing).
4358        terse: bool,
4359        /// `true` when history rows are requested.
4360        history: bool,
4361        /// `true` when extended information should be shown.
4362        extended: bool,
4363        /// `true` when a full listing was requested.
4364        full: bool,
4365        /// `true` when external tables should be included.
4366        external: bool,
4367        /// Additional options for `SHOW` statements.
4368        show_options: ShowStatementOptions,
4369    },
4370    /// ```sql
4371    /// SHOW VIEWS
4372    /// ```
4373    ShowViews {
4374        /// `true` when terse output format was requested.
4375        terse: bool,
4376        /// `true` when materialized views should be included.
4377        materialized: bool,
4378        /// Additional options for `SHOW` statements.
4379        show_options: ShowStatementOptions,
4380    },
4381    /// ```sql
4382    /// SHOW COLLATION
4383    /// ```
4384    ///
4385    /// Note: this is a MySQL-specific statement.
4386    ShowCollation {
4387        /// Optional filter for which collations to display.
4388        filter: Option<ShowStatementFilter>,
4389    },
4390    /// ```sql
4391    /// `USE ...`
4392    /// ```
4393    Use(Use),
4394    /// ```sql
4395    /// START  [ TRANSACTION | WORK ] | START TRANSACTION } ...
4396    /// ```
4397    /// If `begin` is false.
4398    ///
4399    /// ```sql
4400    /// `BEGIN  [ TRANSACTION | WORK ] | START TRANSACTION } ...`
4401    /// ```
4402    /// If `begin` is true
4403    StartTransaction {
4404        /// Transaction modes such as `ISOLATION LEVEL` or `READ WRITE`.
4405        modes: Vec<TransactionMode>,
4406        /// `true` when this was parsed as `BEGIN` instead of `START`.
4407        begin: bool,
4408        /// Optional specific keyword used: `TRANSACTION` or `WORK`.
4409        transaction: Option<BeginTransactionKind>,
4410        /// Optional transaction modifier (e.g., `AND NO CHAIN`).
4411        modifier: Option<TransactionModifier>,
4412        /// List of statements belonging to the `BEGIN` block.
4413        /// Example:
4414        /// ```sql
4415        /// BEGIN
4416        ///     SELECT 1;
4417        ///     SELECT 2;
4418        /// END;
4419        /// ```
4420        statements: Vec<Statement>,
4421        /// Exception handling with exception clauses.
4422        /// Example:
4423        /// ```sql
4424        /// EXCEPTION
4425        ///     WHEN EXCEPTION_1 THEN
4426        ///         SELECT 2;
4427        ///     WHEN EXCEPTION_2 OR EXCEPTION_3 THEN
4428        ///         SELECT 3;
4429        ///     WHEN OTHER THEN
4430        ///         SELECT 4;
4431        /// ```
4432        /// <https://cloud.google.com/bigquery/docs/reference/standard-sql/procedural-language#beginexceptionend>
4433        /// <https://docs.snowflake.com/en/sql-reference/snowflake-scripting/exception>
4434        exception: Option<Vec<ExceptionWhen>>,
4435        /// TRUE if the statement has an `END` keyword.
4436        has_end_keyword: bool,
4437    },
4438    /// ```sql
4439    /// COMMENT ON ...
4440    /// ```
4441    ///
4442    /// Note: this is a PostgreSQL-specific statement.
4443    Comment {
4444        /// Type of object being commented (table, column, etc.).
4445        object_type: CommentObject,
4446        /// Name of the object the comment applies to.
4447        object_name: ObjectName,
4448        /// Optional comment text (None to remove comment).
4449        comment: Option<String>,
4450        /// An optional `IF EXISTS` clause. (Non-standard.)
4451        /// See <https://docs.snowflake.com/en/sql-reference/sql/comment>
4452        if_exists: bool,
4453    },
4454    /// ```sql
4455    /// COMMIT [ TRANSACTION | WORK ] [ AND [ NO ] CHAIN ]
4456    /// ```
4457    /// If `end` is false
4458    ///
4459    /// ```sql
4460    /// END [ TRY | CATCH ]
4461    /// ```
4462    /// If `end` is true
4463    Commit {
4464        /// `true` when `AND [ NO ] CHAIN` was present.
4465        chain: bool,
4466        /// `true` when this `COMMIT` was parsed as an `END` block terminator.
4467        end: bool,
4468        /// Optional transaction modifier for commit semantics.
4469        modifier: Option<TransactionModifier>,
4470    },
4471    /// ```sql
4472    /// ROLLBACK [ TRANSACTION | WORK ] [ AND [ NO ] CHAIN ] [ TO [ SAVEPOINT ] savepoint_name ]
4473    /// ```
4474    Rollback {
4475        /// `true` when `AND [ NO ] CHAIN` was present.
4476        chain: bool,
4477        /// Optional savepoint name to roll back to.
4478        savepoint: Option<Ident>,
4479    },
4480    /// ```sql
4481    /// CREATE SCHEMA
4482    /// ```
4483    CreateSchema {
4484        /// `<schema name> | AUTHORIZATION <schema authorization identifier>  | <schema name>  AUTHORIZATION <schema authorization identifier>`
4485        schema_name: SchemaName,
4486        /// `true` when `OR REPLACE` was present.
4487        or_replace: bool,
4488        /// `true` when `IF NOT EXISTS` was present.
4489        if_not_exists: bool,
4490        /// Schema properties.
4491        ///
4492        /// ```sql
4493        /// CREATE SCHEMA myschema WITH (key1='value1');
4494        /// ```
4495        ///
4496        /// [Trino](https://trino.io/docs/current/sql/create-schema.html)
4497        with: Option<Vec<SqlOption>>,
4498        /// Schema options.
4499        ///
4500        /// ```sql
4501        /// CREATE SCHEMA myschema OPTIONS(key1='value1');
4502        /// ```
4503        ///
4504        /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_schema_statement)
4505        options: Option<Vec<SqlOption>>,
4506        /// Default collation specification for the schema.
4507        ///
4508        /// ```sql
4509        /// CREATE SCHEMA myschema DEFAULT COLLATE 'und:ci';
4510        /// ```
4511        ///
4512        /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_schema_statement)
4513        default_collate_spec: Option<Expr>,
4514        /// Clones a schema
4515        ///
4516        /// ```sql
4517        /// CREATE SCHEMA myschema CLONE otherschema
4518        /// ```
4519        ///
4520        /// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/create-clone#databases-schemas)
4521        clone: Option<ObjectName>,
4522    },
4523    /// ```sql
4524    /// CREATE DATABASE
4525    /// ```
4526    /// See:
4527    /// <https://docs.snowflake.com/en/sql-reference/sql/create-database>
4528    CreateDatabase {
4529        /// Database name.
4530        db_name: ObjectName,
4531        /// `IF NOT EXISTS` flag.
4532        if_not_exists: bool,
4533        /// Optional location URI.
4534        location: Option<String>,
4535        /// Optional managed location.
4536        managed_location: Option<String>,
4537        /// `OR REPLACE` flag.
4538        or_replace: bool,
4539        /// `TRANSIENT` flag.
4540        transient: bool,
4541        /// Optional clone source.
4542        clone: Option<ObjectName>,
4543        /// Optional data retention time in days.
4544        data_retention_time_in_days: Option<u64>,
4545        /// Optional maximum data extension time in days.
4546        max_data_extension_time_in_days: Option<u64>,
4547        /// Optional external volume identifier.
4548        external_volume: Option<String>,
4549        /// Optional catalog name.
4550        catalog: Option<String>,
4551        /// Whether to replace invalid characters.
4552        replace_invalid_characters: Option<bool>,
4553        /// Default DDL collation string.
4554        default_ddl_collation: Option<String>,
4555        /// Storage serialization policy.
4556        storage_serialization_policy: Option<StorageSerializationPolicy>,
4557        /// Optional comment.
4558        comment: Option<String>,
4559        /// Optional default character set (MySQL).
4560        default_charset: Option<String>,
4561        /// Optional default collation (MySQL).
4562        default_collation: Option<String>,
4563        /// Optional catalog sync identifier.
4564        catalog_sync: Option<String>,
4565        /// Catalog sync namespace mode.
4566        catalog_sync_namespace_mode: Option<CatalogSyncNamespaceMode>,
4567        /// Optional flatten delimiter for namespace sync.
4568        catalog_sync_namespace_flatten_delimiter: Option<String>,
4569        /// Optional tags for the database.
4570        with_tags: Option<Vec<Tag>>,
4571        /// Optional contact entries for the database.
4572        with_contacts: Option<Vec<ContactEntry>>,
4573    },
4574    /// ```sql
4575    /// CREATE FUNCTION
4576    /// ```
4577    ///
4578    /// Supported variants:
4579    /// 1. [Hive](https://cwiki.apache.org/confluence/display/hive/languagemanual+ddl#LanguageManualDDL-Create/Drop/ReloadFunction)
4580    /// 2. [PostgreSQL](https://www.postgresql.org/docs/15/sql-createfunction.html)
4581    /// 3. [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_function_statement)
4582    /// 4. [MsSql](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql)
4583    CreateFunction(CreateFunction),
4584    /// CREATE TRIGGER statement. See struct [CreateTrigger] for details.
4585    CreateTrigger(CreateTrigger),
4586    /// DROP TRIGGER statement. See struct [DropTrigger] for details.
4587    DropTrigger(DropTrigger),
4588    /// ```sql
4589    /// CREATE PROCEDURE
4590    /// ```
4591    CreateProcedure {
4592        /// `OR ALTER` flag.
4593        or_alter: bool,
4594        /// Procedure name.
4595        name: ObjectName,
4596        /// Parenthesized parameter list, `None` when absent.
4597        params: Option<Vec<ProcedureParam>>,
4598        /// Optional language identifier.
4599        language: Option<Ident>,
4600        /// Procedure body.
4601        body: CreateProcedureBody,
4602    },
4603    /// ```sql
4604    /// CREATE MACRO
4605    /// ```
4606    ///
4607    /// Supported variants:
4608    /// 1. [DuckDB](https://duckdb.org/docs/sql/statements/create_macro)
4609    CreateMacro {
4610        /// `OR REPLACE` flag.
4611        or_replace: bool,
4612        /// Whether macro is temporary.
4613        temporary: bool,
4614        /// Macro name.
4615        name: ObjectName,
4616        /// Optional macro arguments.
4617        args: Option<Vec<MacroArg>>,
4618        /// Macro definition body.
4619        definition: MacroDefinition,
4620    },
4621    /// ```sql
4622    /// CREATE STAGE
4623    /// ```
4624    /// See <https://docs.snowflake.com/en/sql-reference/sql/create-stage>
4625    CreateStage {
4626        /// `OR REPLACE` flag for stage.
4627        or_replace: bool,
4628        /// Whether stage is temporary.
4629        temporary: bool,
4630        /// `IF NOT EXISTS` flag.
4631        if_not_exists: bool,
4632        /// Stage name.
4633        name: ObjectName,
4634        /// Stage parameters.
4635        stage_params: StageParamsObject,
4636        /// Directory table parameters.
4637        directory_table_params: KeyValueOptions,
4638        /// File format options.
4639        file_format: KeyValueOptions,
4640        /// Copy options for stage.
4641        copy_options: KeyValueOptions,
4642        /// Optional comment.
4643        comment: Option<String>,
4644    },
4645    /// ```sql
4646    /// CREATE [ OR REPLACE ] [ { TEMP | TEMPORARY | VOLATILE } ] FILE FORMAT [ IF NOT EXISTS ] <name>
4647    ///   [ TYPE = { CSV | JSON | AVRO | ORC | PARQUET | XML } [ formatTypeOptions ] ]
4648    ///   [ COMMENT = '<string_literal>' ]
4649    /// ```
4650    /// See <https://docs.snowflake.com/en/sql-reference/sql/create-file-format>
4651    CreateFileFormat {
4652        /// `OR REPLACE` flag.
4653        or_replace: bool,
4654        /// Whether file format is temporary.
4655        temporary: bool,
4656        /// Whether file format is volatile.
4657        volatile: bool,
4658        /// `IF NOT EXISTS` flag.
4659        if_not_exists: bool,
4660        /// File format name.
4661        name: ObjectName,
4662        /// Format type options (e.g. `TYPE`, `FIELD_DELIMITER`, `COMPRESSION`, ...).
4663        options: KeyValueOptions,
4664        /// Optional comment.
4665        comment: Option<String>,
4666    },
4667    /// ```sql
4668    /// CREATE [ OR REPLACE ] WAREHOUSE [ IF NOT EXISTS ] <name>
4669    ///   [ [ WITH ] <property> = <value> [ ... ] ]
4670    /// ```
4671    /// Snowflake-specific statement to create a virtual warehouse.
4672    ///
4673    /// See <https://docs.snowflake.com/en/sql-reference/sql/create-warehouse>
4674    CreateWarehouse(CreateWarehouse),
4675    /// ```sql
4676    /// ASSERT <condition> [AS <message>]
4677    /// ```
4678    Assert {
4679        /// Assertion condition expression.
4680        condition: Expr,
4681        /// Optional message expression.
4682        message: Option<Expr>,
4683    },
4684    /// ```sql
4685    /// GRANT privileges ON objects TO grantees
4686    /// ```
4687    Grant(Grant),
4688    /// ```sql
4689    /// GRANT roles TO grantees
4690    /// ```
4691    GrantRole(GrantRole),
4692    /// ```sql
4693    /// DENY privileges ON object TO grantees
4694    /// ```
4695    Deny(DenyStatement),
4696    /// ```sql
4697    /// REVOKE privileges ON objects FROM grantees
4698    /// ```
4699    Revoke(Revoke),
4700    /// ```sql
4701    /// REVOKE roles FROM grantees
4702    /// ```
4703    RevokeRole(RevokeRole),
4704    /// ```sql
4705    /// ALTER DEFAULT PRIVILEGES
4706    /// ```
4707    AlterDefaultPrivileges(AlterDefaultPrivileges),
4708    /// ```sql
4709    /// DEALLOCATE [ PREPARE ] { name | ALL }
4710    /// ```
4711    ///
4712    /// Note: this is a PostgreSQL-specific statement.
4713    Deallocate {
4714        /// Name to deallocate (or `ALL`).
4715        name: Ident,
4716        /// Whether `PREPARE` keyword was present.
4717        prepare: bool,
4718    },
4719    /// ```sql
4720    /// An `EXECUTE` statement
4721    /// ```
4722    ///
4723    /// Postgres: <https://www.postgresql.org/docs/current/sql-execute.html>
4724    /// MSSQL: <https://learn.microsoft.com/en-us/sql/relational-databases/stored-procedures/execute-a-stored-procedure>
4725    /// BigQuery: <https://cloud.google.com/bigquery/docs/reference/standard-sql/procedural-language#execute_immediate>
4726    /// Snowflake: <https://docs.snowflake.com/en/sql-reference/sql/execute-immediate>
4727    Execute {
4728        /// Optional function/procedure name.
4729        name: Option<ObjectName>,
4730        /// Parameter expressions passed to execute.
4731        parameters: Vec<Expr>,
4732        /// Whether parentheses were present around `parameters`.
4733        has_parentheses: bool,
4734        /// Is this an `EXECUTE IMMEDIATE`.
4735        immediate: bool,
4736        /// Identifiers to capture results into.
4737        into: Vec<Ident>,
4738        /// `USING` expressions with optional aliases.
4739        using: Vec<ExprWithAlias>,
4740        /// Whether the last parameter is the return value of the procedure
4741        /// MSSQL: <https://learn.microsoft.com/en-us/sql/t-sql/language-elements/execute-transact-sql?view=sql-server-ver17#output>
4742        output: bool,
4743        /// Whether to invoke the procedure with the default parameter values
4744        /// MSSQL: <https://learn.microsoft.com/en-us/sql/t-sql/language-elements/execute-transact-sql?view=sql-server-ver17#default>
4745        default: bool,
4746    },
4747    /// ```sql
4748    /// PREPARE name [ ( data_type [, ...] ) ] AS statement
4749    /// ```
4750    ///
4751    /// Note: this is a PostgreSQL-specific statement.
4752    Prepare {
4753        /// Name of the prepared statement.
4754        name: Ident,
4755        /// Optional data types for parameters.
4756        data_types: Vec<DataType>,
4757        /// Statement being prepared.
4758        statement: Box<Statement>,
4759    },
4760    /// ```sql
4761    /// KILL [CONNECTION | QUERY | MUTATION]
4762    /// ```
4763    ///
4764    /// See <https://clickhouse.com/docs/en/sql-reference/statements/kill/>
4765    /// See <https://dev.mysql.com/doc/refman/8.0/en/kill.html>
4766    Kill {
4767        /// Optional kill modifier (CONNECTION, QUERY, MUTATION).
4768        modifier: Option<KillType>,
4769        // processlist_id
4770        /// The id of the process to kill.
4771        id: u64,
4772    },
4773    /// ```sql
4774    /// [EXPLAIN | DESC | DESCRIBE] TABLE
4775    /// ```
4776    /// Note: this is a MySQL-specific statement. See <https://dev.mysql.com/doc/refman/8.0/en/explain.html>
4777    ExplainTable {
4778        /// `EXPLAIN | DESC | DESCRIBE`
4779        describe_alias: DescribeAlias,
4780        /// Hive style `FORMATTED | EXTENDED`
4781        hive_format: Option<HiveDescribeFormat>,
4782        /// Snowflake and ClickHouse support `DESC|DESCRIBE TABLE <table_name>` syntax
4783        ///
4784        /// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/desc-table.html)
4785        /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/describe-table)
4786        has_table_keyword: bool,
4787        /// Table name
4788        #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4789        table_name: ObjectName,
4790    },
4791    /// ```sql
4792    /// [EXPLAIN | DESC | DESCRIBE]  <statement>
4793    /// ```
4794    Explain {
4795        /// `EXPLAIN | DESC | DESCRIBE`
4796        describe_alias: DescribeAlias,
4797        /// Carry out the command and show actual run times and other statistics.
4798        analyze: bool,
4799        /// Display additional information regarding the plan.
4800        verbose: bool,
4801        /// `EXPLAIN QUERY PLAN`
4802        /// Display the query plan without running the query.
4803        ///
4804        /// [SQLite](https://sqlite.org/lang_explain.html)
4805        query_plan: bool,
4806        /// `EXPLAIN ESTIMATE`
4807        /// [Clickhouse](https://clickhouse.com/docs/en/sql-reference/statements/explain#explain-estimate)
4808        estimate: bool,
4809        /// A SQL query that specifies what to explain
4810        statement: Box<Statement>,
4811        /// Optional output format of explain
4812        format: Option<AnalyzeFormatKind>,
4813        /// Postgres style utility options, `(analyze, verbose true)`
4814        options: Option<Vec<UtilityOption>>,
4815    },
4816    /// ```sql
4817    /// SAVEPOINT
4818    /// ```
4819    /// Define a new savepoint within the current transaction
4820    Savepoint {
4821        /// Name of the savepoint being defined.
4822        name: Ident,
4823    },
4824    /// ```sql
4825    /// RELEASE [ SAVEPOINT ] savepoint_name
4826    /// ```
4827    ReleaseSavepoint {
4828        /// Name of the savepoint to release.
4829        name: Ident,
4830    },
4831    /// A `MERGE` statement.
4832    ///
4833    /// ```sql
4834    /// MERGE INTO <target_table> USING <source> ON <join_expr> { matchedClause | notMatchedClause } [ ... ]
4835    /// ```
4836    /// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/merge)
4837    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#merge_statement)
4838    /// [MSSQL](https://learn.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql?view=sql-server-ver16)
4839    Merge(Merge),
4840    /// ```sql
4841    /// CACHE [ FLAG ] TABLE <table_name> [ OPTIONS('K1' = 'V1', 'K2' = V2) ] [ AS ] [ <query> ]
4842    /// ```
4843    ///
4844    /// See [Spark SQL docs] for more details.
4845    ///
4846    /// [Spark SQL docs]: https://docs.databricks.com/spark/latest/spark-sql/language-manual/sql-ref-syntax-aux-cache-cache-table.html
4847    Cache {
4848        /// Table flag
4849        table_flag: Option<ObjectName>,
4850        /// Table name
4851        #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4852        table_name: ObjectName,
4853        /// `true` if `AS` keyword was present before the query.
4854        has_as: bool,
4855        /// Table confs
4856        options: Vec<SqlOption>,
4857        /// Cache table as a Query
4858        query: Option<Box<Query>>,
4859    },
4860    /// ```sql
4861    /// UNCACHE TABLE [ IF EXISTS ]  <table_name>
4862    /// ```
4863    UNCache {
4864        /// Table name
4865        #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4866        table_name: ObjectName,
4867        /// `true` when `IF EXISTS` was present.
4868        if_exists: bool,
4869    },
4870    /// ```sql
4871    /// CREATE [ { TEMPORARY | TEMP } ] SEQUENCE [ IF NOT EXISTS ] <sequence_name>
4872    /// ```
4873    /// Define a new sequence:
4874    CreateSequence {
4875        /// Whether the sequence is temporary.
4876        temporary: bool,
4877        /// `IF NOT EXISTS` flag.
4878        if_not_exists: bool,
4879        /// Sequence name.
4880        name: ObjectName,
4881        /// Sequence options, in the order they were written.
4882        sequence_options: Vec<SequenceOptions>,
4883    },
4884    /// A `CREATE DOMAIN` statement.
4885    CreateDomain(CreateDomain),
4886    /// ```sql
4887    /// CREATE TYPE <name>
4888    /// ```
4889    CreateType {
4890        /// Type name to create.
4891        name: ObjectName,
4892        /// Optional type representation details.
4893        representation: Option<UserDefinedTypeRepresentation>,
4894    },
4895    /// ```sql
4896    /// PRAGMA <schema-name>.<pragma-name> = <pragma-value>
4897    /// ```
4898    Pragma {
4899        /// Pragma name (possibly qualified).
4900        name: ObjectName,
4901        /// Optional pragma value.
4902        value: Option<ValueWithSpan>,
4903        /// Whether the pragma used `=`.
4904        is_eq: bool,
4905    },
4906    /// ```sql
4907    /// LOCK [ TABLE ] [ ONLY ] name [ * ] [, ...] [ IN lockmode MODE ] [ NOWAIT ]
4908    /// ```
4909    ///
4910    /// See <https://www.postgresql.org/docs/current/sql-lock.html>
4911    Lock(Lock),
4912    /// ```sql
4913    /// LOCK TABLES <table_name> [READ [LOCAL] | [LOW_PRIORITY] WRITE]
4914    /// ```
4915    /// Note: this is a MySQL-specific statement. See <https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html>
4916    LockTables {
4917        /// List of tables to lock with modes.
4918        tables: Vec<LockTable>,
4919    },
4920    /// ```sql
4921    /// UNLOCK TABLES
4922    /// ```
4923    /// Note: this is a MySQL-specific statement. See <https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html>
4924    UnlockTables,
4925    /// Unloads the result of a query to file
4926    ///
4927    /// [Athena](https://docs.aws.amazon.com/athena/latest/ug/unload.html):
4928    /// ```sql
4929    /// UNLOAD(statement) TO <destination> [ WITH options ]
4930    /// ```
4931    ///
4932    /// [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_UNLOAD.html):
4933    /// ```sql
4934    /// UNLOAD('statement') TO <destination> [ OPTIONS ]
4935    /// ```
4936    Unload {
4937        /// Optional query AST to unload.
4938        query: Option<Box<Query>>,
4939        /// Optional original query text.
4940        query_text: Option<String>,
4941        /// Destination identifier.
4942        to: Ident,
4943        /// Optional IAM role/auth information.
4944        auth: Option<IamRoleKind>,
4945        /// Additional `WITH` options.
4946        with: Vec<SqlOption>,
4947        /// Legacy copy-style options.
4948        options: Vec<CopyLegacyOption>,
4949    },
4950    /// ClickHouse:
4951    /// ```sql
4952    /// OPTIMIZE TABLE [db.]name [ON CLUSTER cluster] [PARTITION partition | PARTITION ID 'partition_id'] [FINAL] [DEDUPLICATE [BY expression]]
4953    /// ```
4954    /// See ClickHouse <https://clickhouse.com/docs/en/sql-reference/statements/optimize>
4955    ///
4956    /// Databricks:
4957    /// ```sql
4958    /// OPTIMIZE table_name [WHERE predicate] [ZORDER BY (col_name1 [, ...])]
4959    /// ```
4960    /// See Databricks <https://docs.databricks.com/en/sql/language-manual/delta-optimize.html>
4961    OptimizeTable {
4962        /// Table name to optimize.
4963        name: ObjectName,
4964        /// Whether the `TABLE` keyword was present (ClickHouse uses `OPTIMIZE TABLE`, Databricks uses `OPTIMIZE`).
4965        has_table_keyword: bool,
4966        /// Optional cluster identifier.
4967        /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/optimize)
4968        on_cluster: Option<Ident>,
4969        /// Optional partition spec.
4970        /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/optimize)
4971        partition: Option<Partition>,
4972        /// Whether `FINAL` was specified.
4973        /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/optimize)
4974        include_final: bool,
4975        /// Optional deduplication settings.
4976        /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/optimize)
4977        deduplicate: Option<Deduplicate>,
4978        /// Optional WHERE predicate.
4979        /// [Databricks](https://docs.databricks.com/en/sql/language-manual/delta-optimize.html)
4980        predicate: Option<Expr>,
4981        /// Optional ZORDER BY columns.
4982        /// [Databricks](https://docs.databricks.com/en/sql/language-manual/delta-optimize.html)
4983        zorder: Option<Vec<Expr>>,
4984    },
4985    /// ```sql
4986    /// LISTEN
4987    /// ```
4988    /// listen for a notification channel
4989    ///
4990    /// See Postgres <https://www.postgresql.org/docs/current/sql-listen.html>
4991    LISTEN {
4992        /// Notification channel identifier.
4993        channel: Ident,
4994    },
4995    /// ```sql
4996    /// UNLISTEN
4997    /// ```
4998    /// stop listening for a notification
4999    ///
5000    /// See Postgres <https://www.postgresql.org/docs/current/sql-unlisten.html>
5001    UNLISTEN {
5002        /// Notification channel identifier.
5003        channel: Ident,
5004    },
5005    /// ```sql
5006    /// NOTIFY channel [ , payload ]
5007    /// ```
5008    /// send a notification event together with an optional "payload" string to channel
5009    ///
5010    /// See Postgres <https://www.postgresql.org/docs/current/sql-notify.html>
5011    NOTIFY {
5012        /// Notification channel identifier.
5013        channel: Ident,
5014        /// Optional payload string.
5015        payload: Option<String>,
5016    },
5017    /// ```sql
5018    /// LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename
5019    /// [PARTITION (partcol1=val1, partcol2=val2 ...)]
5020    /// [INPUTFORMAT 'inputformat' SERDE 'serde']
5021    /// ```
5022    /// Loading files into tables
5023    ///
5024    /// See Hive <https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=27362036#LanguageManualDML-Loadingfilesintotables>
5025    LoadData {
5026        /// Whether `LOCAL` is present.
5027        local: bool,
5028        /// Input path for files to load.
5029        inpath: String,
5030        /// Whether `OVERWRITE` was specified.
5031        overwrite: bool,
5032        /// Target table name to load into.
5033        table_name: ObjectName,
5034        /// Optional partition specification.
5035        partitioned: Option<Vec<Expr>>,
5036        /// Optional table format information.
5037        table_format: Option<HiveLoadDataFormat>,
5038    },
5039    /// ```sql
5040    /// Rename TABLE tbl_name TO new_tbl_name[, tbl_name2 TO new_tbl_name2] ...
5041    /// ```
5042    /// Renames one or more tables
5043    ///
5044    /// See Mysql <https://dev.mysql.com/doc/refman/9.1/en/rename-table.html>
5045    RenameTable(Vec<RenameTable>),
5046    /// Snowflake `LIST`
5047    /// See: <https://docs.snowflake.com/en/sql-reference/sql/list>
5048    List(FileStagingCommand),
5049    /// Snowflake `PUT`
5050    /// ```sql
5051    /// PUT 'file://<path>' <internalStage> [ <option> = <value> ... ]
5052    /// ```
5053    /// Options include `PARALLEL`, `AUTO_COMPRESS`, `SOURCE_COMPRESSION`, `OVERWRITE`.
5054    /// See: <https://docs.snowflake.com/en/sql-reference/sql/put>
5055    Put {
5056        /// Local source URI as written in the statement, e.g. `file:///tmp/data.csv`.
5057        source: String,
5058        /// Target internal stage (e.g. `@mystage`, `@~`, `@%table`).
5059        stage: ObjectName,
5060        /// Trailing options (`PARALLEL=4`, `AUTO_COMPRESS=TRUE`, ...).
5061        options: KeyValueOptions,
5062    },
5063    /// Snowflake `REMOVE`
5064    /// See: <https://docs.snowflake.com/en/sql-reference/sql/remove>
5065    Remove(FileStagingCommand),
5066    /// RaiseError (MSSQL)
5067    /// RAISERROR ( { msg_id | msg_str | @local_variable }
5068    /// { , severity , state }
5069    /// [ , argument [ , ...n ] ] )
5070    /// [ WITH option [ , ...n ] ]
5071    /// See <https://learn.microsoft.com/en-us/sql/t-sql/language-elements/raiserror-transact-sql?view=sql-server-ver16>
5072    RaisError {
5073        /// Error message expression or identifier.
5074        message: Box<Expr>,
5075        /// Severity expression.
5076        severity: Box<Expr>,
5077        /// State expression.
5078        state: Box<Expr>,
5079        /// Substitution arguments for the message.
5080        arguments: Vec<Expr>,
5081        /// Additional `WITH` options for RAISERROR.
5082        options: Vec<RaisErrorOption>,
5083    },
5084    /// A MSSQL `THROW` statement.
5085    Throw(ThrowStatement),
5086    /// ```sql
5087    /// PRINT msg_str | @local_variable | string_expr
5088    /// ```
5089    ///
5090    /// See: <https://learn.microsoft.com/en-us/sql/t-sql/statements/print-transact-sql>
5091    Print(PrintStatement),
5092    /// MSSQL `WAITFOR` statement.
5093    ///
5094    /// See: <https://learn.microsoft.com/en-us/sql/t-sql/language-elements/waitfor-transact-sql>
5095    WaitFor(WaitForStatement),
5096    /// ```sql
5097    /// RETURN [ expression ]
5098    /// ```
5099    ///
5100    /// See [ReturnStatement]
5101    Return(ReturnStatement),
5102    /// Export data statement
5103    ///
5104    /// Example:
5105    /// ```sql
5106    /// EXPORT DATA OPTIONS(uri='gs://bucket/folder/*', format='PARQUET', overwrite=true) AS
5107    /// SELECT field1, field2 FROM mydataset.table1 ORDER BY field1 LIMIT 10
5108    /// ```
5109    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/export-statements)
5110    ExportData(ExportData),
5111    /// ```sql
5112    /// CREATE [OR REPLACE] USER <user> [IF NOT EXISTS]
5113    /// ```
5114    /// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/create-user)
5115    CreateUser(CreateUser),
5116    /// ```sql
5117    /// ALTER USER \[ IF EXISTS \] \[ <name> \]
5118    /// ```
5119    /// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/alter-user)
5120    AlterUser(AlterUser),
5121    /// Re-sorts rows and reclaims space in either a specified table or all tables in the current database
5122    ///
5123    /// ```sql
5124    /// VACUUM tbl
5125    /// ```
5126    /// [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_VACUUM_command.html)
5127    Vacuum(VacuumStatement),
5128    /// Restore the value of a run-time parameter to the default value.
5129    ///
5130    /// ```sql
5131    /// RESET configuration_parameter;
5132    /// RESET ALL;
5133    /// ```
5134    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-reset.html)
5135    Reset(ResetStatement),
5136    /// Replace the contents of a materialized view.
5137    ///
5138    /// ```sql
5139    /// REFRESH MATERIALIZED VIEW [ CONCURRENTLY ] name [ WITH [ NO ] DATA ]
5140    /// ```
5141    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-refreshmaterializedview.html)
5142    RefreshMaterializedView(RefreshMaterializedView),
5143}
5144
5145impl From<Analyze> for Statement {
5146    fn from(analyze: Analyze) -> Self {
5147        Statement::Analyze(analyze)
5148    }
5149}
5150
5151impl From<ddl::Truncate> for Statement {
5152    fn from(truncate: ddl::Truncate) -> Self {
5153        Statement::Truncate(truncate)
5154    }
5155}
5156
5157impl From<Lock> for Statement {
5158    fn from(lock: Lock) -> Self {
5159        Statement::Lock(lock)
5160    }
5161}
5162
5163impl From<ddl::Msck> for Statement {
5164    fn from(msck: ddl::Msck) -> Self {
5165        Statement::Msck(msck)
5166    }
5167}
5168
5169/// ```sql
5170/// {COPY | REVOKE} CURRENT GRANTS
5171/// ```
5172///
5173/// - [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/grant-ownership#optional-parameters)
5174#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5175#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5176#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5177pub enum CurrentGrantsKind {
5178    /// `COPY CURRENT GRANTS` (copy current grants to target).
5179    CopyCurrentGrants,
5180    /// `REVOKE CURRENT GRANTS` (revoke current grants from target).
5181    RevokeCurrentGrants,
5182}
5183
5184impl fmt::Display for CurrentGrantsKind {
5185    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5186        match self {
5187            CurrentGrantsKind::CopyCurrentGrants => write!(f, "COPY CURRENT GRANTS"),
5188            CurrentGrantsKind::RevokeCurrentGrants => write!(f, "REVOKE CURRENT GRANTS"),
5189        }
5190    }
5191}
5192
5193#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5194#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5195#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5196/// `RAISERROR` options
5197/// See <https://learn.microsoft.com/en-us/sql/t-sql/language-elements/raiserror-transact-sql?view=sql-server-ver16#options>
5198pub enum RaisErrorOption {
5199    /// Log the error.
5200    Log,
5201    /// Do not wait for completion.
5202    NoWait,
5203    /// Set the error state.
5204    SetError,
5205}
5206
5207impl fmt::Display for RaisErrorOption {
5208    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5209        match self {
5210            RaisErrorOption::Log => write!(f, "LOG"),
5211            RaisErrorOption::NoWait => write!(f, "NOWAIT"),
5212            RaisErrorOption::SetError => write!(f, "SETERROR"),
5213        }
5214    }
5215}
5216
5217impl fmt::Display for Statement {
5218    /// Formats a SQL statement with support for pretty printing.
5219    ///
5220    /// When using the alternate flag (`{:#}`), the statement will be formatted with proper
5221    /// indentation and line breaks. For example:
5222    ///
5223    /// ```
5224    /// # use sqlparser::dialect::GenericDialect;
5225    /// # use sqlparser::parser::Parser;
5226    /// let sql = "SELECT a, b FROM table_1";
5227    /// let ast = Parser::parse_sql(&GenericDialect, sql).unwrap();
5228    ///
5229    /// // Regular formatting
5230    /// assert_eq!(format!("{}", ast[0]), "SELECT a, b FROM table_1");
5231    ///
5232    /// // Pretty printing
5233    /// assert_eq!(format!("{:#}", ast[0]),
5234    /// r#"SELECT
5235    ///   a,
5236    ///   b
5237    /// FROM
5238    ///   table_1"#);
5239    /// ```
5240    #[expect(
5241        clippy::cognitive_complexity,
5242        reason = "splitting this match would need a struct for each `Statement` variant"
5243    )]
5244    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5245        match self {
5246            Statement::Flush {
5247                object_type,
5248                location,
5249                channel,
5250                read_lock,
5251                export,
5252                tables,
5253            } => {
5254                write!(f, "FLUSH")?;
5255                if let Some(location) = location {
5256                    f.write_str(" ")?;
5257                    location.fmt(f)?;
5258                }
5259                write!(f, " {object_type}")?;
5260
5261                if let Some(channel) = channel {
5262                    write!(f, " FOR CHANNEL {channel}")?;
5263                }
5264
5265                write!(
5266                    f,
5267                    "{tables}{read}{export}",
5268                    tables = if !tables.is_empty() {
5269                        format!(" {}", display_comma_separated(tables))
5270                    } else {
5271                        String::new()
5272                    },
5273                    export = if *export { " FOR EXPORT" } else { "" },
5274                    read = if *read_lock { " WITH READ LOCK" } else { "" }
5275                )
5276            }
5277            Statement::Kill { modifier, id } => {
5278                write!(f, "KILL ")?;
5279
5280                if let Some(m) = modifier {
5281                    write!(f, "{m} ")?;
5282                }
5283
5284                write!(f, "{id}")
5285            }
5286            Statement::ExplainTable {
5287                describe_alias,
5288                hive_format,
5289                has_table_keyword,
5290                table_name,
5291            } => {
5292                write!(f, "{describe_alias} ")?;
5293
5294                if let Some(format) = hive_format {
5295                    write!(f, "{format} ")?;
5296                }
5297                if *has_table_keyword {
5298                    write!(f, "TABLE ")?;
5299                }
5300
5301                write!(f, "{table_name}")
5302            }
5303            Statement::Explain {
5304                describe_alias,
5305                verbose,
5306                analyze,
5307                query_plan,
5308                estimate,
5309                statement,
5310                format,
5311                options,
5312            } => {
5313                write!(f, "{describe_alias} ")?;
5314
5315                if *query_plan {
5316                    write!(f, "QUERY PLAN ")?;
5317                }
5318                if *analyze {
5319                    write!(f, "ANALYZE ")?;
5320                }
5321                if *estimate {
5322                    write!(f, "ESTIMATE ")?;
5323                }
5324
5325                if *verbose {
5326                    write!(f, "VERBOSE ")?;
5327                }
5328
5329                if let Some(format) = format {
5330                    write!(f, "{format} ")?;
5331                }
5332
5333                if let Some(options) = options {
5334                    write!(f, "({}) ", display_comma_separated(options))?;
5335                }
5336
5337                write!(f, "{statement}")
5338            }
5339            Statement::Query(s) => s.fmt(f),
5340            Statement::Declare { stmts, separator } => {
5341                let sep = match separator {
5342                    DeclareSeparator::Comma => ", ",
5343                    DeclareSeparator::Semicolon => "; ",
5344                };
5345                write!(f, "DECLARE {}", display_separated(stmts, sep))
5346            }
5347            Statement::Fetch {
5348                name,
5349                direction,
5350                position,
5351                into,
5352            } => {
5353                write!(f, "FETCH {direction} {position} {name}")?;
5354
5355                if let Some(into) = into {
5356                    write!(f, " INTO {into}")?;
5357                }
5358
5359                Ok(())
5360            }
5361            Statement::Directory {
5362                overwrite,
5363                local,
5364                path,
5365                file_format,
5366                source,
5367            } => {
5368                write!(
5369                    f,
5370                    "INSERT{overwrite}{local} DIRECTORY '{path}'",
5371                    overwrite = if *overwrite { " OVERWRITE" } else { "" },
5372                    local = if *local { " LOCAL" } else { "" },
5373                    path = path
5374                )?;
5375                if let Some(ref ff) = file_format {
5376                    write!(f, " STORED AS {ff}")?
5377                }
5378                write!(f, " {source}")
5379            }
5380            Statement::Msck(msck) => msck.fmt(f),
5381            Statement::Truncate(truncate) => truncate.fmt(f),
5382            Statement::Case(stmt) => {
5383                write!(f, "{stmt}")
5384            }
5385            Statement::If(stmt) => {
5386                write!(f, "{stmt}")
5387            }
5388            Statement::While(stmt) => {
5389                write!(f, "{stmt}")
5390            }
5391            Statement::Raise(stmt) => {
5392                write!(f, "{stmt}")
5393            }
5394            Statement::AttachDatabase {
5395                schema_name,
5396                database_file_name,
5397                database,
5398            } => {
5399                let keyword = if *database { "DATABASE " } else { "" };
5400                write!(f, "ATTACH {keyword}{database_file_name} AS {schema_name}")
5401            }
5402            Statement::AttachDuckDBDatabase {
5403                if_not_exists,
5404                database,
5405                database_path,
5406                database_alias,
5407                attach_options,
5408            } => {
5409                write!(
5410                    f,
5411                    "ATTACH{database}{if_not_exists} {database_path}",
5412                    database = if *database { " DATABASE" } else { "" },
5413                    if_not_exists = if *if_not_exists { " IF NOT EXISTS" } else { "" },
5414                )?;
5415                if let Some(alias) = database_alias {
5416                    write!(f, " AS {alias}")?;
5417                }
5418                if !attach_options.is_empty() {
5419                    write!(f, " ({})", display_comma_separated(attach_options))?;
5420                }
5421                Ok(())
5422            }
5423            Statement::DetachDuckDBDatabase {
5424                if_exists,
5425                database,
5426                database_alias,
5427            } => {
5428                write!(
5429                    f,
5430                    "DETACH{database}{if_exists} {database_alias}",
5431                    database = if *database { " DATABASE" } else { "" },
5432                    if_exists = if *if_exists { " IF EXISTS" } else { "" },
5433                )?;
5434                Ok(())
5435            }
5436            Statement::Analyze(analyze) => analyze.fmt(f),
5437            Statement::Insert(insert) => insert.fmt(f),
5438            Statement::Install {
5439                extension_name: name,
5440            } => write!(f, "INSTALL {name}"),
5441
5442            Statement::Load {
5443                extension_name: name,
5444            } => write!(f, "LOAD {name}"),
5445
5446            Statement::Call(function) => write!(f, "CALL {function}"),
5447
5448            Statement::Copy {
5449                source,
5450                to,
5451                target,
5452                options,
5453                legacy_options,
5454                payload,
5455            } => {
5456                write!(f, "COPY")?;
5457                match source {
5458                    CopySource::Query(query) => write!(f, " ({query})")?,
5459                    CopySource::Table {
5460                        table_name,
5461                        columns,
5462                    } => {
5463                        write!(f, " {table_name}")?;
5464                        if !columns.is_empty() {
5465                            write!(f, " ({})", display_comma_separated(columns))?;
5466                        }
5467                    }
5468                }
5469                write!(f, " {} {}", if *to { "TO" } else { "FROM" }, target)?;
5470                if !options.is_empty() {
5471                    write!(f, " ({})", display_comma_separated(options))?;
5472                }
5473                if !legacy_options.is_empty() {
5474                    write!(f, " {}", display_separated(legacy_options, " "))?;
5475                }
5476                if let Some(payload) = payload {
5477                    // The payload starts on the line after the command and ends
5478                    // at the `\.` terminator line, which is only written when
5479                    // present in the source.
5480                    writeln!(f, ";")?;
5481                    write!(f, "{}", payload.data)?;
5482                    if payload.terminated {
5483                        write!(f, "\\.")?;
5484                    }
5485                }
5486                Ok(())
5487            }
5488            Statement::Update(update) => update.fmt(f),
5489            Statement::Delete(delete) => delete.fmt(f),
5490            Statement::Open(open) => open.fmt(f),
5491            Statement::Close { cursor } => {
5492                write!(f, "CLOSE {cursor}")?;
5493
5494                Ok(())
5495            }
5496            Statement::CreateDatabase {
5497                db_name,
5498                if_not_exists,
5499                location,
5500                managed_location,
5501                or_replace,
5502                transient,
5503                clone,
5504                data_retention_time_in_days,
5505                max_data_extension_time_in_days,
5506                external_volume,
5507                catalog,
5508                replace_invalid_characters,
5509                default_ddl_collation,
5510                storage_serialization_policy,
5511                comment,
5512                default_charset,
5513                default_collation,
5514                catalog_sync,
5515                catalog_sync_namespace_mode,
5516                catalog_sync_namespace_flatten_delimiter,
5517                with_tags,
5518                with_contacts,
5519            } => {
5520                write!(
5521                    f,
5522                    "CREATE {or_replace}{transient}DATABASE {if_not_exists}{name}",
5523                    or_replace = if *or_replace { "OR REPLACE " } else { "" },
5524                    transient = if *transient { "TRANSIENT " } else { "" },
5525                    if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
5526                    name = db_name,
5527                )?;
5528
5529                if let Some(l) = location {
5530                    write!(f, " LOCATION '{l}'")?;
5531                }
5532                if let Some(ml) = managed_location {
5533                    write!(f, " MANAGEDLOCATION '{ml}'")?;
5534                }
5535                if let Some(clone) = clone {
5536                    write!(f, " CLONE {clone}")?;
5537                }
5538
5539                if let Some(value) = data_retention_time_in_days {
5540                    write!(f, " DATA_RETENTION_TIME_IN_DAYS = {value}")?;
5541                }
5542
5543                if let Some(value) = max_data_extension_time_in_days {
5544                    write!(f, " MAX_DATA_EXTENSION_TIME_IN_DAYS = {value}")?;
5545                }
5546
5547                if let Some(vol) = external_volume {
5548                    write!(f, " EXTERNAL_VOLUME = '{vol}'")?;
5549                }
5550
5551                if let Some(cat) = catalog {
5552                    write!(f, " CATALOG = '{cat}'")?;
5553                }
5554
5555                if let Some(true) = replace_invalid_characters {
5556                    write!(f, " REPLACE_INVALID_CHARACTERS = TRUE")?;
5557                } else if let Some(false) = replace_invalid_characters {
5558                    write!(f, " REPLACE_INVALID_CHARACTERS = FALSE")?;
5559                }
5560
5561                if let Some(collation) = default_ddl_collation {
5562                    write!(f, " DEFAULT_DDL_COLLATION = '{collation}'")?;
5563                }
5564
5565                if let Some(policy) = storage_serialization_policy {
5566                    write!(f, " STORAGE_SERIALIZATION_POLICY = {policy}")?;
5567                }
5568
5569                if let Some(comment) = comment {
5570                    write!(f, " COMMENT = '{comment}'")?;
5571                }
5572
5573                if let Some(charset) = default_charset {
5574                    write!(f, " DEFAULT CHARACTER SET {charset}")?;
5575                }
5576
5577                if let Some(collation) = default_collation {
5578                    write!(f, " DEFAULT COLLATE {collation}")?;
5579                }
5580
5581                if let Some(sync) = catalog_sync {
5582                    write!(f, " CATALOG_SYNC = '{sync}'")?;
5583                }
5584
5585                if let Some(mode) = catalog_sync_namespace_mode {
5586                    write!(f, " CATALOG_SYNC_NAMESPACE_MODE = {mode}")?;
5587                }
5588
5589                if let Some(delim) = catalog_sync_namespace_flatten_delimiter {
5590                    write!(f, " CATALOG_SYNC_NAMESPACE_FLATTEN_DELIMITER = '{delim}'")?;
5591                }
5592
5593                if let Some(tags) = with_tags {
5594                    write!(f, " WITH TAG ({})", display_comma_separated(tags))?;
5595                }
5596
5597                if let Some(contacts) = with_contacts {
5598                    write!(f, " WITH CONTACT ({})", display_comma_separated(contacts))?;
5599                }
5600                Ok(())
5601            }
5602            Statement::CreateFunction(create_function) => create_function.fmt(f),
5603            Statement::CreateDomain(create_domain) => create_domain.fmt(f),
5604            Statement::CreateTrigger(create_trigger) => create_trigger.fmt(f),
5605            Statement::DropTrigger(drop_trigger) => drop_trigger.fmt(f),
5606            Statement::CreateProcedure {
5607                name,
5608                or_alter,
5609                params,
5610                language,
5611                body,
5612            } => {
5613                write!(
5614                    f,
5615                    "CREATE {or_alter}PROCEDURE {name}",
5616                    or_alter = if *or_alter { "OR ALTER " } else { "" },
5617                    name = name
5618                )?;
5619
5620                if let Some(p) = params {
5621                    write!(f, " ({})", display_comma_separated(p))?;
5622                }
5623
5624                if let Some(language) = language {
5625                    write!(f, " LANGUAGE {language}")?;
5626                }
5627
5628                match body {
5629                    CreateProcedureBody::As(body) => write!(f, " AS {body}"),
5630                    CreateProcedureBody::BeginAtomic(BeginEndStatements { statements, .. }) => {
5631                        format_begin_atomic(f, statements)
5632                    }
5633                }
5634            }
5635            Statement::CreateMacro {
5636                or_replace,
5637                temporary,
5638                name,
5639                args,
5640                definition,
5641            } => {
5642                write!(
5643                    f,
5644                    "CREATE {or_replace}{temp}MACRO {name}",
5645                    temp = if *temporary { "TEMPORARY " } else { "" },
5646                    or_replace = if *or_replace { "OR REPLACE " } else { "" },
5647                )?;
5648                write!(
5649                    f,
5650                    "({})",
5651                    display_comma_separated(args.as_deref().unwrap_or(&[]))
5652                )?;
5653                match definition {
5654                    MacroDefinition::Expr(expr) => write!(f, " AS {expr}")?,
5655                    MacroDefinition::Table(query) => write!(f, " AS TABLE {query}")?,
5656                }
5657                Ok(())
5658            }
5659            Statement::CreateView(create_view) => create_view.fmt(f),
5660            Statement::CreateTable(create_table) => create_table.fmt(f),
5661            Statement::LoadData {
5662                local,
5663                inpath,
5664                overwrite,
5665                table_name,
5666                partitioned,
5667                table_format,
5668            } => {
5669                write!(
5670                    f,
5671                    "LOAD DATA {local}INPATH '{inpath}' {overwrite}INTO TABLE {table_name}",
5672                    local = if *local { "LOCAL " } else { "" },
5673                    inpath = inpath,
5674                    overwrite = if *overwrite { "OVERWRITE " } else { "" },
5675                    table_name = table_name,
5676                )?;
5677                if let Some(ref parts) = &partitioned {
5678                    if !parts.is_empty() {
5679                        write!(f, " PARTITION ({})", display_comma_separated(parts))?;
5680                    }
5681                }
5682                if let Some(HiveLoadDataFormat {
5683                    serde,
5684                    input_format,
5685                }) = &table_format
5686                {
5687                    write!(f, " INPUTFORMAT {input_format} SERDE {serde}")?;
5688                }
5689                Ok(())
5690            }
5691            Statement::CreateVirtualTable {
5692                name,
5693                if_not_exists,
5694                module_name,
5695                module_args,
5696            } => {
5697                write!(
5698                    f,
5699                    "CREATE VIRTUAL TABLE {if_not_exists}{name} USING {module_name}",
5700                    if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
5701                    name = name,
5702                    module_name = module_name
5703                )?;
5704                if !module_args.is_empty() {
5705                    write!(f, " ({})", display_comma_separated(module_args))?;
5706                }
5707                Ok(())
5708            }
5709            Statement::CreateIndex(create_index) => create_index.fmt(f),
5710            Statement::CreateExtension(create_extension) => write!(f, "{create_extension}"),
5711            Statement::CreateCollation(create_collation) => write!(f, "{create_collation}"),
5712            Statement::DropExtension(drop_extension) => write!(f, "{drop_extension}"),
5713            Statement::DropOperator(drop_operator) => write!(f, "{drop_operator}"),
5714            Statement::DropOperatorFamily(drop_operator_family) => {
5715                write!(f, "{drop_operator_family}")
5716            }
5717            Statement::DropOperatorClass(drop_operator_class) => {
5718                write!(f, "{drop_operator_class}")
5719            }
5720            Statement::CreateRole(create_role) => write!(f, "{create_role}"),
5721            Statement::CreateSecret {
5722                or_replace,
5723                temporary,
5724                if_not_exists,
5725                name,
5726                storage_specifier,
5727                secret_type,
5728                options,
5729            } => {
5730                write!(
5731                    f,
5732                    "CREATE {or_replace}",
5733                    or_replace = if *or_replace { "OR REPLACE " } else { "" },
5734                )?;
5735                if let Some(t) = temporary {
5736                    write!(f, "{}", if *t { "TEMPORARY " } else { "PERSISTENT " })?;
5737                }
5738                write!(
5739                    f,
5740                    "SECRET {if_not_exists}",
5741                    if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
5742                )?;
5743                if let Some(n) = name {
5744                    write!(f, "{n} ")?;
5745                };
5746                if let Some(s) = storage_specifier {
5747                    write!(f, "IN {s} ")?;
5748                }
5749                write!(f, "( TYPE {secret_type}",)?;
5750                if !options.is_empty() {
5751                    write!(f, ", {o}", o = display_comma_separated(options))?;
5752                }
5753                write!(f, " )")?;
5754                Ok(())
5755            }
5756            Statement::CreateServer(stmt) => {
5757                write!(f, "{stmt}")
5758            }
5759            Statement::CreateForeignTable(stmt) => write!(f, "{stmt}"),
5760            Statement::CreateForeignDataWrapper(stmt) => write!(f, "{stmt}"),
5761            Statement::CreateUserMapping(stmt) => write!(f, "{stmt}"),
5762            Statement::CreatePolicy(policy) => write!(f, "{policy}"),
5763            Statement::CreateRule(rule) => write!(f, "{rule}"),
5764            Statement::CreateConnector(create_connector) => create_connector.fmt(f),
5765            Statement::CreateOperator(create_operator) => create_operator.fmt(f),
5766            Statement::CreateOperatorFamily(create_operator_family) => {
5767                create_operator_family.fmt(f)
5768            }
5769            Statement::CreateOperatorClass(create_operator_class) => create_operator_class.fmt(f),
5770            Statement::CreateAggregate(create_aggregate) => create_aggregate.fmt(f),
5771            Statement::CreateTextSearch(create_text_search) => create_text_search.fmt(f),
5772            Statement::AlterTable(alter_table) => write!(f, "{alter_table}"),
5773            Statement::AlterIndex { name, operation } => {
5774                write!(f, "ALTER INDEX {name} {operation}")
5775            }
5776            Statement::AlterView(alter_view) => write!(f, "{alter_view}"),
5777            Statement::AlterFunction(alter_function) => write!(f, "{alter_function}"),
5778            Statement::AlterType(AlterType { name, operation }) => {
5779                write!(f, "ALTER TYPE {name} {operation}")
5780            }
5781            Statement::AlterCollation(alter_collation) => write!(f, "{alter_collation}"),
5782            Statement::AlterOperator(alter_operator) => write!(f, "{alter_operator}"),
5783            Statement::AlterOperatorFamily(alter_operator_family) => {
5784                write!(f, "{alter_operator_family}")
5785            }
5786            Statement::AlterOperatorClass(alter_operator_class) => {
5787                write!(f, "{alter_operator_class}")
5788            }
5789            Statement::AlterTextSearch(alter_text_search) => write!(f, "{alter_text_search}"),
5790            Statement::AlterRole { name, operation } => {
5791                write!(f, "ALTER ROLE {name} {operation}")
5792            }
5793            Statement::AlterPolicy(alter_policy) => write!(f, "{alter_policy}"),
5794            Statement::AlterTrigger(alter_trigger) => write!(f, "{alter_trigger}"),
5795            Statement::AlterConnector {
5796                name,
5797                properties,
5798                url,
5799                owner,
5800            } => {
5801                write!(f, "ALTER CONNECTOR {name}")?;
5802                if let Some(properties) = properties {
5803                    write!(
5804                        f,
5805                        " SET DCPROPERTIES({})",
5806                        display_comma_separated(properties)
5807                    )?;
5808                }
5809                if let Some(url) = url {
5810                    write!(f, " SET URL '{url}'")?;
5811                }
5812                if let Some(owner) = owner {
5813                    write!(f, " SET OWNER {owner}")?;
5814                }
5815                Ok(())
5816            }
5817            Statement::AlterSession {
5818                set,
5819                session_params,
5820            } => {
5821                write!(
5822                    f,
5823                    "ALTER SESSION {set}",
5824                    set = if *set { "SET" } else { "UNSET" }
5825                )?;
5826                if !session_params.options.is_empty() {
5827                    if *set {
5828                        write!(f, " {session_params}")?;
5829                    } else {
5830                        let options = session_params
5831                            .options
5832                            .iter()
5833                            .map(|p| p.option_name.clone())
5834                            .collect::<Vec<_>>();
5835                        write!(f, " {}", display_separated(&options, ", "))?;
5836                    }
5837                }
5838                Ok(())
5839            }
5840            Statement::Drop {
5841                object_type,
5842                if_exists,
5843                names,
5844                cascade,
5845                restrict,
5846                purge,
5847                temporary,
5848                table,
5849            } => {
5850                write!(
5851                    f,
5852                    "DROP {}{}{} {}{}{}{}",
5853                    if *temporary { "TEMPORARY " } else { "" },
5854                    object_type,
5855                    if *if_exists { " IF EXISTS" } else { "" },
5856                    display_comma_separated(names),
5857                    if *cascade { " CASCADE" } else { "" },
5858                    if *restrict { " RESTRICT" } else { "" },
5859                    if *purge { " PURGE" } else { "" },
5860                )?;
5861                if let Some(table_name) = table.as_ref() {
5862                    write!(f, " ON {table_name}")?;
5863                };
5864                Ok(())
5865            }
5866            Statement::DropFunction(drop_function) => write!(f, "{drop_function}"),
5867            Statement::DropDomain(DropDomain {
5868                if_exists,
5869                name,
5870                drop_behavior,
5871            }) => {
5872                write!(
5873                    f,
5874                    "DROP DOMAIN{} {name}",
5875                    if *if_exists { " IF EXISTS" } else { "" },
5876                )?;
5877                if let Some(op) = drop_behavior {
5878                    write!(f, " {op}")?;
5879                }
5880                Ok(())
5881            }
5882            Statement::DropProcedure {
5883                if_exists,
5884                proc_desc,
5885                drop_behavior,
5886            } => {
5887                write!(
5888                    f,
5889                    "DROP PROCEDURE{} {}",
5890                    if *if_exists { " IF EXISTS" } else { "" },
5891                    display_comma_separated(proc_desc),
5892                )?;
5893                if let Some(op) = drop_behavior {
5894                    write!(f, " {op}")?;
5895                }
5896                Ok(())
5897            }
5898            Statement::DropSecret {
5899                if_exists,
5900                temporary,
5901                name,
5902                storage_specifier,
5903            } => {
5904                write!(f, "DROP ")?;
5905                if let Some(t) = temporary {
5906                    write!(f, "{}", if *t { "TEMPORARY " } else { "PERSISTENT " })?;
5907                }
5908                write!(
5909                    f,
5910                    "SECRET {if_exists}{name}",
5911                    if_exists = if *if_exists { "IF EXISTS " } else { "" },
5912                )?;
5913                if let Some(s) = storage_specifier {
5914                    write!(f, " FROM {s}")?;
5915                }
5916                Ok(())
5917            }
5918            Statement::DropPolicy(policy) => write!(f, "{policy}"),
5919            Statement::DropRule(rule) => write!(f, "{rule}"),
5920            Statement::DropConnector { if_exists, name } => {
5921                write!(
5922                    f,
5923                    "DROP CONNECTOR {if_exists}{name}",
5924                    if_exists = if *if_exists { "IF EXISTS " } else { "" }
5925                )?;
5926                Ok(())
5927            }
5928            Statement::Discard { object_type } => {
5929                write!(f, "DISCARD {object_type}")?;
5930                Ok(())
5931            }
5932            Self::Set(set) => write!(f, "{set}"),
5933            Statement::ShowVariable { variable } => {
5934                write!(f, "SHOW")?;
5935                if !variable.is_empty() {
5936                    write!(f, " {}", display_separated(variable, " "))?;
5937                }
5938                Ok(())
5939            }
5940            Statement::ShowStatus {
5941                filter,
5942                global,
5943                session,
5944            } => {
5945                write!(f, "SHOW")?;
5946                if *global {
5947                    write!(f, " GLOBAL")?;
5948                }
5949                if *session {
5950                    write!(f, " SESSION")?;
5951                }
5952                write!(f, " STATUS")?;
5953                if let Some(filter) = filter {
5954                    write!(f, " {}", filter)?;
5955                }
5956                Ok(())
5957            }
5958            Statement::ShowVariables {
5959                filter,
5960                global,
5961                session,
5962            } => {
5963                write!(f, "SHOW")?;
5964                if *global {
5965                    write!(f, " GLOBAL")?;
5966                }
5967                if *session {
5968                    write!(f, " SESSION")?;
5969                }
5970                write!(f, " VARIABLES")?;
5971                if let Some(filter) = filter {
5972                    write!(f, " {}", filter)?;
5973                }
5974                Ok(())
5975            }
5976            Statement::ShowCreate { obj_type, obj_name } => {
5977                write!(f, "SHOW CREATE {obj_type} {obj_name}",)?;
5978                Ok(())
5979            }
5980            Statement::ShowColumns {
5981                extended,
5982                full,
5983                show_options,
5984            } => {
5985                write!(
5986                    f,
5987                    "SHOW {extended}{full}COLUMNS{show_options}",
5988                    extended = if *extended { "EXTENDED " } else { "" },
5989                    full = if *full { "FULL " } else { "" },
5990                )?;
5991                Ok(())
5992            }
5993            Statement::ShowDatabases {
5994                terse,
5995                history,
5996                show_options,
5997            } => {
5998                write!(
5999                    f,
6000                    "SHOW {terse}DATABASES{history}{show_options}",
6001                    terse = if *terse { "TERSE " } else { "" },
6002                    history = if *history { " HISTORY" } else { "" },
6003                )?;
6004                Ok(())
6005            }
6006            Statement::ShowCatalogs {
6007                terse,
6008                history,
6009                show_options,
6010            } => {
6011                write!(
6012                    f,
6013                    "SHOW {terse}CATALOGS{history}{show_options}",
6014                    terse = if *terse { "TERSE " } else { "" },
6015                    history = if *history { " HISTORY" } else { "" },
6016                )?;
6017                Ok(())
6018            }
6019            Statement::ShowProcessList { full } => {
6020                write!(
6021                    f,
6022                    "SHOW {full}PROCESSLIST",
6023                    full = if *full { "FULL " } else { "" },
6024                )?;
6025                Ok(())
6026            }
6027            Statement::ShowSchemas {
6028                terse,
6029                history,
6030                show_options,
6031            } => {
6032                write!(
6033                    f,
6034                    "SHOW {terse}SCHEMAS{history}{show_options}",
6035                    terse = if *terse { "TERSE " } else { "" },
6036                    history = if *history { " HISTORY" } else { "" },
6037                )?;
6038                Ok(())
6039            }
6040            Statement::ShowObjects(ShowObjects {
6041                terse,
6042                show_options,
6043            }) => {
6044                write!(
6045                    f,
6046                    "SHOW {terse}OBJECTS{show_options}",
6047                    terse = if *terse { "TERSE " } else { "" },
6048                )?;
6049                Ok(())
6050            }
6051            Statement::ShowTables {
6052                terse,
6053                history,
6054                extended,
6055                full,
6056                external,
6057                show_options,
6058            } => {
6059                write!(
6060                    f,
6061                    "SHOW {terse}{extended}{full}{external}TABLES{history}{show_options}",
6062                    terse = if *terse { "TERSE " } else { "" },
6063                    extended = if *extended { "EXTENDED " } else { "" },
6064                    full = if *full { "FULL " } else { "" },
6065                    external = if *external { "EXTERNAL " } else { "" },
6066                    history = if *history { " HISTORY" } else { "" },
6067                )?;
6068                Ok(())
6069            }
6070            Statement::ShowViews {
6071                terse,
6072                materialized,
6073                show_options,
6074            } => {
6075                write!(
6076                    f,
6077                    "SHOW {terse}{materialized}VIEWS{show_options}",
6078                    terse = if *terse { "TERSE " } else { "" },
6079                    materialized = if *materialized { "MATERIALIZED " } else { "" }
6080                )?;
6081                Ok(())
6082            }
6083            Statement::ShowFunctions { filter } => {
6084                write!(f, "SHOW FUNCTIONS")?;
6085                if let Some(filter) = filter {
6086                    write!(f, " {filter}")?;
6087                }
6088                Ok(())
6089            }
6090            Statement::Use(use_expr) => use_expr.fmt(f),
6091            Statement::ShowCollation { filter } => {
6092                write!(f, "SHOW COLLATION")?;
6093                if let Some(filter) = filter {
6094                    write!(f, " {filter}")?;
6095                }
6096                Ok(())
6097            }
6098            Statement::ShowCharset(show_stm) => show_stm.fmt(f),
6099            Statement::StartTransaction {
6100                modes,
6101                begin: syntax_begin,
6102                transaction,
6103                modifier,
6104                statements,
6105                exception,
6106                has_end_keyword,
6107            } => {
6108                if *syntax_begin {
6109                    if let Some(modifier) = *modifier {
6110                        write!(f, "BEGIN {modifier}")?;
6111                    } else {
6112                        write!(f, "BEGIN")?;
6113                    }
6114                } else {
6115                    write!(f, "START")?;
6116                }
6117                if let Some(transaction) = transaction {
6118                    write!(f, " {transaction}")?;
6119                }
6120                if !modes.is_empty() {
6121                    write!(f, " {}", display_comma_separated(modes))?;
6122                }
6123                if !statements.is_empty() {
6124                    write!(f, " ")?;
6125                    format_statement_list(f, statements)?;
6126                }
6127                if let Some(exception_when) = exception {
6128                    write!(f, " EXCEPTION")?;
6129                    for when in exception_when {
6130                        write!(f, " {when}")?;
6131                    }
6132                }
6133                if *has_end_keyword {
6134                    write!(f, " END")?;
6135                }
6136                Ok(())
6137            }
6138            Statement::Commit {
6139                chain,
6140                end: end_syntax,
6141                modifier,
6142            } => {
6143                if *end_syntax {
6144                    write!(f, "END")?;
6145                    if let Some(modifier) = *modifier {
6146                        write!(f, " {modifier}")?;
6147                    }
6148                    if *chain {
6149                        write!(f, " AND CHAIN")?;
6150                    }
6151                } else {
6152                    write!(f, "COMMIT{}", if *chain { " AND CHAIN" } else { "" })?;
6153                }
6154                Ok(())
6155            }
6156            Statement::Rollback { chain, savepoint } => {
6157                write!(f, "ROLLBACK")?;
6158
6159                if *chain {
6160                    write!(f, " AND CHAIN")?;
6161                }
6162
6163                if let Some(savepoint) = savepoint {
6164                    write!(f, " TO SAVEPOINT {savepoint}")?;
6165                }
6166
6167                Ok(())
6168            }
6169            Statement::CreateSchema {
6170                schema_name,
6171                or_replace,
6172                if_not_exists,
6173                with,
6174                options,
6175                default_collate_spec,
6176                clone,
6177            } => {
6178                write!(
6179                    f,
6180                    "CREATE {or_replace}SCHEMA {if_not_exists}{name}",
6181                    or_replace = if *or_replace { "OR REPLACE " } else { "" },
6182                    if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
6183                    name = schema_name
6184                )?;
6185
6186                if let Some(collate) = default_collate_spec {
6187                    write!(f, " DEFAULT COLLATE {collate}")?;
6188                }
6189
6190                if let Some(with) = with {
6191                    write!(f, " WITH ({})", display_comma_separated(with))?;
6192                }
6193
6194                if let Some(options) = options {
6195                    write!(f, " OPTIONS({})", display_comma_separated(options))?;
6196                }
6197
6198                if let Some(clone) = clone {
6199                    write!(f, " CLONE {clone}")?;
6200                }
6201                Ok(())
6202            }
6203            Statement::Assert { condition, message } => {
6204                write!(f, "ASSERT {condition}")?;
6205                if let Some(m) = message {
6206                    write!(f, " AS {m}")?;
6207                }
6208                Ok(())
6209            }
6210            Statement::Grant(grant) => write!(f, "{grant}"),
6211            Statement::Deny(s) => write!(f, "{s}"),
6212            Statement::Revoke(revoke) => write!(f, "{revoke}"),
6213            Statement::GrantRole(grant) => write!(f, "{grant}"),
6214            Statement::RevokeRole(revoke) => write!(f, "{revoke}"),
6215            Statement::AlterDefaultPrivileges(stmt) => write!(f, "{stmt}"),
6216            Statement::Deallocate { name, prepare } => write!(
6217                f,
6218                "DEALLOCATE {prepare}{name}",
6219                prepare = if *prepare { "PREPARE " } else { "" },
6220                name = name,
6221            ),
6222            Statement::Execute {
6223                name,
6224                parameters,
6225                has_parentheses,
6226                immediate,
6227                into,
6228                using,
6229                output,
6230                default,
6231            } => {
6232                let (open, close) = if *has_parentheses {
6233                    // Space before `(` only when there is no name directly preceding it.
6234                    (if name.is_some() { "(" } else { " (" }, ")")
6235                } else {
6236                    (if parameters.is_empty() { "" } else { " " }, "")
6237                };
6238                write!(f, "EXECUTE")?;
6239                if *immediate {
6240                    write!(f, " IMMEDIATE")?;
6241                }
6242                if let Some(name) = name {
6243                    write!(f, " {name}")?;
6244                }
6245                write!(f, "{open}{}{close}", display_comma_separated(parameters),)?;
6246                if !into.is_empty() {
6247                    write!(f, " INTO {}", display_comma_separated(into))?;
6248                }
6249                if !using.is_empty() {
6250                    write!(f, " USING {}", display_comma_separated(using))?;
6251                };
6252                if *output {
6253                    write!(f, " OUTPUT")?;
6254                }
6255                if *default {
6256                    write!(f, " DEFAULT")?;
6257                }
6258                Ok(())
6259            }
6260            Statement::Prepare {
6261                name,
6262                data_types,
6263                statement,
6264            } => {
6265                write!(f, "PREPARE {name} ")?;
6266                if !data_types.is_empty() {
6267                    write!(f, "({}) ", display_comma_separated(data_types))?;
6268                }
6269                write!(f, "AS {statement}")
6270            }
6271            Statement::Comment {
6272                object_type,
6273                object_name,
6274                comment,
6275                if_exists,
6276            } => {
6277                write!(f, "COMMENT ")?;
6278                if *if_exists {
6279                    write!(f, "IF EXISTS ")?
6280                };
6281                write!(f, "ON {object_type} {object_name} IS ")?;
6282                if let Some(c) = comment {
6283                    write!(f, "'{c}'")
6284                } else {
6285                    write!(f, "NULL")
6286                }
6287            }
6288            Statement::Savepoint { name } => {
6289                write!(f, "SAVEPOINT ")?;
6290                write!(f, "{name}")
6291            }
6292            Statement::ReleaseSavepoint { name } => {
6293                write!(f, "RELEASE SAVEPOINT {name}")
6294            }
6295            Statement::Merge(merge) => merge.fmt(f),
6296            Statement::Cache {
6297                table_name,
6298                table_flag,
6299                has_as,
6300                options,
6301                query,
6302            } => {
6303                if let Some(table_flag) = table_flag {
6304                    write!(f, "CACHE {table_flag} TABLE {table_name}")?;
6305                } else {
6306                    write!(f, "CACHE TABLE {table_name}")?;
6307                }
6308
6309                if !options.is_empty() {
6310                    write!(f, " OPTIONS({})", display_comma_separated(options))?;
6311                }
6312
6313                match (*has_as, query) {
6314                    (true, Some(query)) => write!(f, " AS {query}"),
6315                    (true, None) => f.write_str(" AS"),
6316                    (false, Some(query)) => write!(f, " {query}"),
6317                    (false, None) => Ok(()),
6318                }
6319            }
6320            Statement::UNCache {
6321                table_name,
6322                if_exists,
6323            } => {
6324                if *if_exists {
6325                    write!(f, "UNCACHE TABLE IF EXISTS {table_name}")
6326                } else {
6327                    write!(f, "UNCACHE TABLE {table_name}")
6328                }
6329            }
6330            Statement::CreateSequence {
6331                temporary,
6332                if_not_exists,
6333                name,
6334                sequence_options,
6335            } => {
6336                write!(
6337                    f,
6338                    "CREATE {temporary}SEQUENCE {if_not_exists}{name}",
6339                    if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
6340                    temporary = if *temporary { "TEMPORARY " } else { "" },
6341                    name = name,
6342                )?;
6343                for sequence_option in sequence_options {
6344                    write!(f, "{sequence_option}")?;
6345                }
6346                Ok(())
6347            }
6348            Statement::CreateStage {
6349                or_replace,
6350                temporary,
6351                if_not_exists,
6352                name,
6353                stage_params,
6354                directory_table_params,
6355                file_format,
6356                copy_options,
6357                comment,
6358                ..
6359            } => {
6360                write!(
6361                    f,
6362                    "CREATE {or_replace}{temp}STAGE {if_not_exists}{name}{stage_params}",
6363                    temp = if *temporary { "TEMPORARY " } else { "" },
6364                    or_replace = if *or_replace { "OR REPLACE " } else { "" },
6365                    if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
6366                )?;
6367                if !directory_table_params.options.is_empty() {
6368                    write!(f, " DIRECTORY=({directory_table_params})")?;
6369                }
6370                if !file_format.options.is_empty() {
6371                    write!(f, " FILE_FORMAT=({file_format})")?;
6372                }
6373                if !copy_options.options.is_empty() {
6374                    write!(f, " COPY_OPTIONS=({copy_options})")?;
6375                }
6376                if let Some(comment) = comment {
6377                    write!(f, " COMMENT='{}'", comment)?;
6378                }
6379                Ok(())
6380            }
6381            Statement::CreateFileFormat {
6382                or_replace,
6383                temporary,
6384                volatile,
6385                if_not_exists,
6386                name,
6387                options,
6388                comment,
6389            } => {
6390                write!(
6391                    f,
6392                    "CREATE {or_replace}{temp}{volatile}FILE FORMAT {if_not_exists}{name}",
6393                    or_replace = if *or_replace { "OR REPLACE " } else { "" },
6394                    temp = if *temporary { "TEMPORARY " } else { "" },
6395                    volatile = if *volatile { "VOLATILE " } else { "" },
6396                    if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
6397                )?;
6398                if !options.options.is_empty() {
6399                    write!(f, " {options}")?;
6400                }
6401                if let Some(comment) = comment {
6402                    write!(f, " COMMENT='{}'", comment)?;
6403                }
6404                Ok(())
6405            }
6406            Statement::CreateWarehouse(s) => write!(f, "{s}"),
6407            Statement::CopyIntoSnowflake {
6408                kind,
6409                into,
6410                into_columns,
6411                from_obj,
6412                from_obj_alias,
6413                stage_params,
6414                from_transformations,
6415                from_query,
6416                files,
6417                pattern,
6418                file_format,
6419                copy_options,
6420                validation_mode,
6421                partition,
6422            } => {
6423                write!(f, "COPY INTO {into}")?;
6424                if let Some(into_columns) = into_columns {
6425                    write!(f, " ({})", display_comma_separated(into_columns))?;
6426                }
6427                if let Some(from_transformations) = from_transformations {
6428                    // Data load with transformation
6429                    if let Some(from_stage) = from_obj {
6430                        write!(
6431                            f,
6432                            " FROM (SELECT {} FROM {}{}",
6433                            display_separated(from_transformations, ", "),
6434                            from_stage,
6435                            stage_params
6436                        )?;
6437                    }
6438                    if let Some(from_obj_alias) = from_obj_alias {
6439                        write!(f, " AS {from_obj_alias}")?;
6440                    }
6441                    write!(f, ")")?;
6442                } else if let Some(from_obj) = from_obj {
6443                    // Standard data load
6444                    write!(f, " FROM {from_obj}{stage_params}")?;
6445                    if let Some(from_obj_alias) = from_obj_alias {
6446                        write!(f, " AS {from_obj_alias}")?;
6447                    }
6448                } else if let Some(from_query) = from_query {
6449                    // Data unload from query
6450                    write!(f, " FROM ({from_query})")?;
6451                }
6452
6453                if let Some(files) = files {
6454                    write!(f, " FILES = ('{}')", display_separated(files, "', '"))?;
6455                }
6456                if let Some(pattern) = pattern {
6457                    write!(f, " PATTERN = '{pattern}'")?;
6458                }
6459                if let Some(partition) = partition {
6460                    write!(f, " PARTITION BY {partition}")?;
6461                }
6462                if !file_format.options.is_empty() {
6463                    write!(f, " FILE_FORMAT=({file_format})")?;
6464                }
6465                if !copy_options.options.is_empty() {
6466                    match kind {
6467                        CopyIntoSnowflakeKind::Table => {
6468                            write!(f, " COPY_OPTIONS=({copy_options})")?
6469                        }
6470                        CopyIntoSnowflakeKind::Location => write!(f, " {copy_options}")?,
6471                    }
6472                }
6473                if let Some(validation_mode) = validation_mode {
6474                    write!(f, " VALIDATION_MODE = {validation_mode}")?;
6475                }
6476                Ok(())
6477            }
6478            Statement::CreateType {
6479                name,
6480                representation,
6481            } => {
6482                write!(f, "CREATE TYPE {name}")?;
6483                if let Some(repr) = representation {
6484                    write!(f, " {repr}")?;
6485                }
6486                Ok(())
6487            }
6488            Statement::Pragma { name, value, is_eq } => {
6489                write!(f, "PRAGMA {name}")?;
6490                if let Some(value) = value {
6491                    if *is_eq {
6492                        write!(f, " = {value}")?;
6493                    } else {
6494                        write!(f, "({value})")?;
6495                    }
6496                }
6497                Ok(())
6498            }
6499            Statement::Lock(lock) => lock.fmt(f),
6500            Statement::LockTables { tables } => {
6501                write!(f, "LOCK TABLES {}", display_comma_separated(tables))
6502            }
6503            Statement::UnlockTables => {
6504                write!(f, "UNLOCK TABLES")
6505            }
6506            Statement::Unload {
6507                query,
6508                query_text,
6509                to,
6510                auth,
6511                with,
6512                options,
6513            } => {
6514                write!(f, "UNLOAD(")?;
6515                if let Some(query) = query {
6516                    write!(f, "{query}")?;
6517                }
6518                if let Some(query_text) = query_text {
6519                    write!(f, "'{query_text}'")?;
6520                }
6521                write!(f, ") TO {to}")?;
6522                if let Some(auth) = auth {
6523                    write!(f, " IAM_ROLE {auth}")?;
6524                }
6525                if !with.is_empty() {
6526                    write!(f, " WITH ({})", display_comma_separated(with))?;
6527                }
6528                if !options.is_empty() {
6529                    write!(f, " {}", display_separated(options, " "))?;
6530                }
6531                Ok(())
6532            }
6533            Statement::OptimizeTable {
6534                name,
6535                has_table_keyword,
6536                on_cluster,
6537                partition,
6538                include_final,
6539                deduplicate,
6540                predicate,
6541                zorder,
6542            } => {
6543                write!(f, "OPTIMIZE")?;
6544                if *has_table_keyword {
6545                    write!(f, " TABLE")?;
6546                }
6547                write!(f, " {name}")?;
6548                if let Some(on_cluster) = on_cluster {
6549                    write!(f, " ON CLUSTER {on_cluster}")?;
6550                }
6551                if let Some(partition) = partition {
6552                    write!(f, " {partition}")?;
6553                }
6554                if *include_final {
6555                    write!(f, " FINAL")?;
6556                }
6557                if let Some(deduplicate) = deduplicate {
6558                    write!(f, " {deduplicate}")?;
6559                }
6560                if let Some(predicate) = predicate {
6561                    write!(f, " WHERE {predicate}")?;
6562                }
6563                if let Some(zorder) = zorder {
6564                    write!(f, " ZORDER BY ({})", display_comma_separated(zorder))?;
6565                }
6566                Ok(())
6567            }
6568            Statement::LISTEN { channel } => {
6569                write!(f, "LISTEN {channel}")?;
6570                Ok(())
6571            }
6572            Statement::UNLISTEN { channel } => {
6573                write!(f, "UNLISTEN {channel}")?;
6574                Ok(())
6575            }
6576            Statement::NOTIFY { channel, payload } => {
6577                write!(f, "NOTIFY {channel}")?;
6578                if let Some(payload) = payload {
6579                    write!(f, ", '{payload}'")?;
6580                }
6581                Ok(())
6582            }
6583            Statement::RenameTable(rename_tables) => {
6584                write!(f, "RENAME TABLE {}", display_comma_separated(rename_tables))
6585            }
6586            Statement::RaisError {
6587                message,
6588                severity,
6589                state,
6590                arguments,
6591                options,
6592            } => {
6593                write!(f, "RAISERROR({message}, {severity}, {state}")?;
6594                if !arguments.is_empty() {
6595                    write!(f, ", {}", display_comma_separated(arguments))?;
6596                }
6597                write!(f, ")")?;
6598                if !options.is_empty() {
6599                    write!(f, " WITH {}", display_comma_separated(options))?;
6600                }
6601                Ok(())
6602            }
6603            Statement::Throw(s) => write!(f, "{s}"),
6604            Statement::Print(s) => write!(f, "{s}"),
6605            Statement::WaitFor(s) => write!(f, "{s}"),
6606            Statement::Return(r) => write!(f, "{r}"),
6607            Statement::List(command) => write!(f, "LIST {command}"),
6608            Statement::Put {
6609                source,
6610                stage,
6611                options,
6612            } => {
6613                write!(f, "PUT '{source}' {stage}")?;
6614                if !options.options.is_empty() {
6615                    write!(f, " {options}")?;
6616                }
6617                Ok(())
6618            }
6619            Statement::Remove(command) => write!(f, "REMOVE {command}"),
6620            Statement::ExportData(e) => write!(f, "{e}"),
6621            Statement::CreateUser(s) => write!(f, "{s}"),
6622            Statement::AlterSchema(s) => write!(f, "{s}"),
6623            Statement::Vacuum(s) => write!(f, "{s}"),
6624            Statement::AlterUser(s) => write!(f, "{s}"),
6625            Statement::Reset(s) => write!(f, "{s}"),
6626            Statement::RefreshMaterializedView(s) => write!(f, "{s}"),
6627        }
6628    }
6629}
6630
6631/// Can use to describe options in create sequence or table column type identity
6632/// ```sql
6633/// [ AS data_type ] [ INCREMENT [ BY ] increment ]
6634///     [ MINVALUE minvalue | NO MINVALUE ] [ MAXVALUE maxvalue | NO MAXVALUE ]
6635///     [ START [ WITH ] start ] [ CACHE cache ] [ [ NO ] CYCLE ]
6636///     [ OWNED BY { table_name.column_name | NONE } ]
6637/// ```
6638///
6639/// The options form an unordered list, so they are stored in the order written.
6640/// `AS` and `OWNED BY` are only accepted by `CREATE SEQUENCE`, not by an
6641/// identity column.
6642#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6643#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6644#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6645pub enum SequenceOptions {
6646    /// `AS <data_type>` option.
6647    DataType(DataType),
6648    /// `INCREMENT [BY] <expr>` option; second value indicates presence of `BY` keyword.
6649    IncrementBy(Expr, bool),
6650    /// `MINVALUE <expr>` or `NO MINVALUE`.
6651    MinValue(Option<Expr>),
6652    /// `MAXVALUE <expr>` or `NO MAXVALUE`.
6653    MaxValue(Option<Expr>),
6654    /// `START [WITH] <expr>`; second value indicates presence of `WITH`.
6655    StartWith(Expr, bool),
6656    /// `CACHE <expr>` option.
6657    Cache(Expr),
6658    /// `CYCLE` or `NO CYCLE` option.
6659    Cycle(bool),
6660    /// `OWNED BY <object_name>`, or `OWNED BY NONE` when no target is given.
6661    OwnedBy(Option<ObjectName>),
6662}
6663
6664impl fmt::Display for SequenceOptions {
6665    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6666        match self {
6667            SequenceOptions::DataType(data_type) => {
6668                write!(f, " AS {data_type}")
6669            }
6670            SequenceOptions::IncrementBy(increment, by) => {
6671                write!(
6672                    f,
6673                    " INCREMENT{by} {increment}",
6674                    by = if *by { " BY" } else { "" },
6675                    increment = increment
6676                )
6677            }
6678            SequenceOptions::MinValue(Some(expr)) => {
6679                write!(f, " MINVALUE {expr}")
6680            }
6681            SequenceOptions::MinValue(None) => {
6682                write!(f, " NO MINVALUE")
6683            }
6684            SequenceOptions::MaxValue(Some(expr)) => {
6685                write!(f, " MAXVALUE {expr}")
6686            }
6687            SequenceOptions::MaxValue(None) => {
6688                write!(f, " NO MAXVALUE")
6689            }
6690            SequenceOptions::StartWith(start, with) => {
6691                write!(
6692                    f,
6693                    " START{with} {start}",
6694                    with = if *with { " WITH" } else { "" },
6695                    start = start
6696                )
6697            }
6698            SequenceOptions::Cache(cache) => {
6699                write!(f, " CACHE {}", *cache)
6700            }
6701            SequenceOptions::Cycle(no) => {
6702                write!(f, " {}CYCLE", if *no { "NO " } else { "" })
6703            }
6704            SequenceOptions::OwnedBy(Some(object_name)) => {
6705                write!(f, " OWNED BY {object_name}")
6706            }
6707            SequenceOptions::OwnedBy(None) => {
6708                write!(f, " OWNED BY NONE")
6709            }
6710        }
6711    }
6712}
6713
6714/// Assignment for a `SET` statement (name [=|TO] value)
6715#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6716#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6717#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6718pub struct SetAssignment {
6719    /// Optional context scope (e.g., SESSION or LOCAL).
6720    pub scope: Option<ContextModifier>,
6721    /// Assignment target name.
6722    pub name: ObjectName,
6723    /// Assigned expression value.
6724    pub value: Expr,
6725}
6726
6727impl fmt::Display for SetAssignment {
6728    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6729        write!(
6730            f,
6731            "{}{} = {}",
6732            self.scope.map(|s| format!("{s}")).unwrap_or_default(),
6733            self.name,
6734            self.value
6735        )
6736    }
6737}
6738
6739/// Target of a `TRUNCATE TABLE` command
6740///
6741/// Note this is its own struct because `visit_relation` requires an `ObjectName` (not a `Vec<ObjectName>`)
6742#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6743#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6744#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6745pub struct TruncateTableTarget {
6746    /// name of the table being truncated
6747    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6748    pub name: ObjectName,
6749    /// Postgres-specific option: explicitly exclude descendants (also default without ONLY)
6750    /// ```sql
6751    /// TRUNCATE TABLE ONLY name
6752    /// ```
6753    /// <https://www.postgresql.org/docs/current/sql-truncate.html>
6754    pub only: bool,
6755    /// Postgres-specific option: asterisk after table name to explicitly indicate descendants
6756    /// ```sql
6757    /// TRUNCATE TABLE name [ * ]
6758    /// ```
6759    /// <https://www.postgresql.org/docs/current/sql-truncate.html>
6760    pub has_asterisk: bool,
6761}
6762
6763impl fmt::Display for TruncateTableTarget {
6764    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6765        if self.only {
6766            write!(f, "ONLY ")?;
6767        };
6768        write!(f, "{}", self.name)?;
6769        if self.has_asterisk {
6770            write!(f, " *")?;
6771        };
6772        Ok(())
6773    }
6774}
6775
6776/// A `LOCK` statement.
6777///
6778/// See <https://www.postgresql.org/docs/current/sql-lock.html>
6779#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6780#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6781#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6782pub struct Lock {
6783    /// List of tables to lock.
6784    pub tables: Vec<LockTableTarget>,
6785    /// Lock mode.
6786    pub lock_mode: Option<LockTableMode>,
6787    /// Whether `NOWAIT` was specified.
6788    pub nowait: bool,
6789}
6790
6791impl fmt::Display for Lock {
6792    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6793        write!(f, "LOCK TABLE {}", display_comma_separated(&self.tables))?;
6794        if let Some(lock_mode) = &self.lock_mode {
6795            write!(f, " IN {lock_mode} MODE")?;
6796        }
6797        if self.nowait {
6798            write!(f, " NOWAIT")?;
6799        }
6800        Ok(())
6801    }
6802}
6803
6804/// Target of a `LOCK TABLE` command
6805///
6806/// See <https://www.postgresql.org/docs/current/sql-lock.html>
6807#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6808#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6809#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6810pub struct LockTableTarget {
6811    /// Name of the table being locked.
6812    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6813    pub name: ObjectName,
6814    /// Whether `ONLY` was specified to exclude descendant tables.
6815    pub only: bool,
6816    /// Whether `*` was specified to explicitly include descendant tables.
6817    pub has_asterisk: bool,
6818}
6819
6820impl fmt::Display for LockTableTarget {
6821    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6822        if self.only {
6823            write!(f, "ONLY ")?;
6824        }
6825        write!(f, "{}", self.name)?;
6826        if self.has_asterisk {
6827            write!(f, " *")?;
6828        }
6829        Ok(())
6830    }
6831}
6832
6833/// PostgreSQL lock modes for `LOCK TABLE`.
6834///
6835/// See <https://www.postgresql.org/docs/current/sql-lock.html>
6836#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6837#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6838#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6839pub enum LockTableMode {
6840    /// `ACCESS SHARE`
6841    AccessShare,
6842    /// `ROW SHARE`
6843    RowShare,
6844    /// `ROW EXCLUSIVE`
6845    RowExclusive,
6846    /// `SHARE UPDATE EXCLUSIVE`
6847    ShareUpdateExclusive,
6848    /// `SHARE`
6849    Share,
6850    /// `SHARE ROW EXCLUSIVE`
6851    ShareRowExclusive,
6852    /// `EXCLUSIVE`
6853    Exclusive,
6854    /// `ACCESS EXCLUSIVE`
6855    AccessExclusive,
6856}
6857
6858impl fmt::Display for LockTableMode {
6859    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6860        let text = match self {
6861            Self::AccessShare => "ACCESS SHARE",
6862            Self::RowShare => "ROW SHARE",
6863            Self::RowExclusive => "ROW EXCLUSIVE",
6864            Self::ShareUpdateExclusive => "SHARE UPDATE EXCLUSIVE",
6865            Self::Share => "SHARE",
6866            Self::ShareRowExclusive => "SHARE ROW EXCLUSIVE",
6867            Self::Exclusive => "EXCLUSIVE",
6868            Self::AccessExclusive => "ACCESS EXCLUSIVE",
6869        };
6870        write!(f, "{text}")
6871    }
6872}
6873
6874/// PostgreSQL identity option for TRUNCATE table
6875/// [ RESTART IDENTITY | CONTINUE IDENTITY ]
6876#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6877#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6878#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6879pub enum TruncateIdentityOption {
6880    /// Restart identity values (RESTART IDENTITY).
6881    Restart,
6882    /// Continue identity values (CONTINUE IDENTITY).
6883    Continue,
6884}
6885
6886/// Cascade/restrict option for Postgres TRUNCATE table, MySQL GRANT/REVOKE, etc.
6887/// [ CASCADE | RESTRICT ]
6888#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6889#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6890#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6891pub enum CascadeOption {
6892    /// Apply cascading action (e.g., CASCADE).
6893    Cascade,
6894    /// Restrict the action (e.g., RESTRICT).
6895    Restrict,
6896}
6897
6898impl Display for CascadeOption {
6899    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6900        match self {
6901            CascadeOption::Cascade => write!(f, "CASCADE"),
6902            CascadeOption::Restrict => write!(f, "RESTRICT"),
6903        }
6904    }
6905}
6906
6907/// Transaction started with [ TRANSACTION | WORK | TRAN ]
6908#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6909#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6910#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6911pub enum BeginTransactionKind {
6912    /// Standard `TRANSACTION` keyword.
6913    Transaction,
6914    /// Alternate `WORK` keyword.
6915    Work,
6916    /// MSSQL shorthand `TRAN` keyword.
6917    /// See <https://learn.microsoft.com/en-us/sql/t-sql/language-elements/begin-transaction-transact-sql>
6918    Tran,
6919}
6920
6921impl Display for BeginTransactionKind {
6922    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6923        match self {
6924            BeginTransactionKind::Transaction => write!(f, "TRANSACTION"),
6925            BeginTransactionKind::Work => write!(f, "WORK"),
6926            BeginTransactionKind::Tran => write!(f, "TRAN"),
6927        }
6928    }
6929}
6930
6931/// Can use to describe options in  create sequence or table column type identity
6932/// [ MINVALUE minvalue | NO MINVALUE ] [ MAXVALUE maxvalue | NO MAXVALUE ]
6933#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6934#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6935#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6936pub enum MinMaxValue {
6937    /// Clause is not specified.
6938    Empty,
6939    /// NO MINVALUE / NO MAXVALUE.
6940    None,
6941    /// `MINVALUE <expr>` / `MAXVALUE <expr>`.
6942    Some(Expr),
6943}
6944
6945#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6946#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6947#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6948#[non_exhaustive]
6949/// Behavior to apply for `INSERT` when a conflict occurs.
6950pub enum OnInsert {
6951    /// ON DUPLICATE KEY UPDATE (MySQL when the key already exists, then execute an update instead)
6952    DuplicateKeyUpdate(Vec<Assignment>),
6953    /// ON CONFLICT is a PostgreSQL and Sqlite extension
6954    OnConflict(OnConflict),
6955}
6956
6957#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6958#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6959#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6960/// Optional aliases for `INSERT` targets: row alias and optional column aliases.
6961pub struct InsertAliases {
6962    /// Row alias (table-style alias) for the inserted values.
6963    pub row_alias: ObjectName,
6964    /// Optional list of column aliases for the inserted values.
6965    pub col_aliases: Option<Vec<Ident>>,
6966}
6967
6968#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6969#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6970#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6971/// Optional alias for an `INSERT` table; i.e. the table to be inserted into
6972pub struct TableAliasWithoutColumns {
6973    /// `true` if the aliases was explicitly introduced with the "AS" keyword
6974    pub explicit: bool,
6975    /// the alias name itself
6976    pub alias: Ident,
6977}
6978
6979#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6980#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6981#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6982/// `ON CONFLICT` clause representation.
6983pub struct OnConflict {
6984    /// Optional conflict target specifying columns or constraint.
6985    pub conflict_target: Option<ConflictTarget>,
6986    /// Action to take when a conflict occurs.
6987    pub action: OnConflictAction,
6988}
6989#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6990#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6991#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6992/// Target specification for an `ON CONFLICT` clause.
6993pub enum ConflictTarget {
6994    /// Target specified as a list of columns, optionally followed by
6995    /// `WHERE index_predicate`, which lets a partial unique index be inferred as the arbiter:
6996    /// `ON CONFLICT (a) WHERE b > 0 DO ...`. PostgreSQL and SQLite both accept the predicate.
6997    ///
6998    /// See <https://www.postgresql.org/docs/current/sql-insert.html>
6999    /// and <https://www.sqlite.org/lang_upsert.html>
7000    Columns {
7001        /// The columns of the conflict target.
7002        columns: Vec<Ident>,
7003        /// The `WHERE index_predicate` after the columns, if any.
7004        predicate: Option<Expr>,
7005    },
7006    /// Target specified as a named constraint.
7007    OnConstraint(ObjectName),
7008}
7009#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7010#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7011#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7012/// Action to perform when an `ON CONFLICT` target is matched.
7013pub enum OnConflictAction {
7014    /// Do nothing on conflict.
7015    DoNothing,
7016    /// Perform an update on conflict.
7017    DoUpdate(DoUpdate),
7018}
7019
7020#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7021#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7022#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7023/// Details for `DO UPDATE` action of an `ON CONFLICT` clause.
7024pub struct DoUpdate {
7025    /// Column assignments to perform on update.
7026    pub assignments: Vec<Assignment>,
7027    /// Optional WHERE clause limiting the update.
7028    pub selection: Option<Expr>,
7029}
7030
7031impl fmt::Display for OnInsert {
7032    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7033        match self {
7034            Self::DuplicateKeyUpdate(expr) => write!(
7035                f,
7036                " ON DUPLICATE KEY UPDATE {}",
7037                display_comma_separated(expr)
7038            ),
7039            Self::OnConflict(o) => write!(f, "{o}"),
7040        }
7041    }
7042}
7043impl fmt::Display for OnConflict {
7044    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7045        write!(f, " ON CONFLICT")?;
7046        if let Some(target) = &self.conflict_target {
7047            write!(f, "{target}")?;
7048        }
7049        write!(f, " {}", self.action)
7050    }
7051}
7052impl fmt::Display for ConflictTarget {
7053    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7054        match self {
7055            ConflictTarget::Columns { columns, predicate } => {
7056                write!(f, "({})", display_comma_separated(columns))?;
7057                if let Some(predicate) = predicate {
7058                    write!(f, " WHERE {predicate}")?;
7059                }
7060                Ok(())
7061            }
7062            ConflictTarget::OnConstraint(name) => write!(f, " ON CONSTRAINT {name}"),
7063        }
7064    }
7065}
7066impl fmt::Display for OnConflictAction {
7067    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7068        match self {
7069            Self::DoNothing => write!(f, "DO NOTHING"),
7070            Self::DoUpdate(do_update) => {
7071                write!(f, "DO UPDATE")?;
7072                if !do_update.assignments.is_empty() {
7073                    write!(
7074                        f,
7075                        " SET {}",
7076                        display_comma_separated(&do_update.assignments)
7077                    )?;
7078                }
7079                if let Some(selection) = &do_update.selection {
7080                    write!(f, " WHERE {selection}")?;
7081                }
7082                Ok(())
7083            }
7084        }
7085    }
7086}
7087
7088/// Privileges granted in a GRANT statement or revoked in a REVOKE statement.
7089#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7090#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7091#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7092pub enum Privileges {
7093    /// All privileges applicable to the object type
7094    All {
7095        /// Optional keyword from the spec, ignored in practice
7096        with_privileges_keyword: bool,
7097    },
7098    /// Specific privileges (e.g. `SELECT`, `INSERT`)
7099    Actions(Vec<Action>),
7100}
7101
7102impl fmt::Display for Privileges {
7103    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7104        match self {
7105            Privileges::All {
7106                with_privileges_keyword,
7107            } => {
7108                write!(
7109                    f,
7110                    "ALL{}",
7111                    if *with_privileges_keyword {
7112                        " PRIVILEGES"
7113                    } else {
7114                        ""
7115                    }
7116                )
7117            }
7118            Privileges::Actions(actions) => {
7119                write!(f, "{}", display_comma_separated(actions))
7120            }
7121        }
7122    }
7123}
7124
7125/// Specific direction for FETCH statement
7126#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7127#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7128#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7129pub enum FetchDirection {
7130    /// Fetch a specific count of rows.
7131    Count {
7132        /// The limit value for the count.
7133        limit: ValueWithSpan,
7134    },
7135    /// Fetch the next row.
7136    Next,
7137    /// Fetch the prior row.
7138    Prior,
7139    /// Fetch the first row.
7140    First,
7141    /// Fetch the last row.
7142    Last,
7143    /// Fetch an absolute row by index.
7144    Absolute {
7145        /// The absolute index value.
7146        limit: ValueWithSpan,
7147    },
7148    /// Fetch a row relative to the current position.
7149    Relative {
7150        /// The relative offset value.
7151        limit: ValueWithSpan,
7152    },
7153    /// Fetch all rows.
7154    All,
7155    // FORWARD
7156    // FORWARD count
7157    /// Fetch forward by an optional limit.
7158    Forward {
7159        /// Optional forward limit.
7160        limit: Option<ValueWithSpan>,
7161    },
7162    /// Fetch all forward rows.
7163    ForwardAll,
7164    // BACKWARD
7165    // BACKWARD count
7166    /// Fetch backward by an optional limit.
7167    Backward {
7168        /// Optional backward limit.
7169        limit: Option<ValueWithSpan>,
7170    },
7171    /// Fetch all backward rows.
7172    BackwardAll,
7173}
7174
7175impl fmt::Display for FetchDirection {
7176    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7177        match self {
7178            FetchDirection::Count { limit } => f.write_str(&limit.to_string())?,
7179            FetchDirection::Next => f.write_str("NEXT")?,
7180            FetchDirection::Prior => f.write_str("PRIOR")?,
7181            FetchDirection::First => f.write_str("FIRST")?,
7182            FetchDirection::Last => f.write_str("LAST")?,
7183            FetchDirection::Absolute { limit } => {
7184                f.write_str("ABSOLUTE ")?;
7185                f.write_str(&limit.to_string())?;
7186            }
7187            FetchDirection::Relative { limit } => {
7188                f.write_str("RELATIVE ")?;
7189                f.write_str(&limit.to_string())?;
7190            }
7191            FetchDirection::All => f.write_str("ALL")?,
7192            FetchDirection::Forward { limit } => {
7193                f.write_str("FORWARD")?;
7194
7195                if let Some(l) = limit {
7196                    f.write_str(" ")?;
7197                    f.write_str(&l.to_string())?;
7198                }
7199            }
7200            FetchDirection::ForwardAll => f.write_str("FORWARD ALL")?,
7201            FetchDirection::Backward { limit } => {
7202                f.write_str("BACKWARD")?;
7203
7204                if let Some(l) = limit {
7205                    f.write_str(" ")?;
7206                    f.write_str(&l.to_string())?;
7207                }
7208            }
7209            FetchDirection::BackwardAll => f.write_str("BACKWARD ALL")?,
7210        };
7211
7212        Ok(())
7213    }
7214}
7215
7216/// The "position" for a FETCH statement.
7217///
7218/// [MsSql](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/fetch-transact-sql)
7219#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7220#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7221#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7222pub enum FetchPosition {
7223    /// Use `FROM <pos>` position specifier.
7224    From,
7225    /// Use `IN <pos>` position specifier.
7226    In,
7227}
7228
7229impl fmt::Display for FetchPosition {
7230    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7231        match self {
7232            FetchPosition::From => f.write_str("FROM")?,
7233            FetchPosition::In => f.write_str("IN")?,
7234        };
7235
7236        Ok(())
7237    }
7238}
7239
7240/// A privilege on a database object (table, sequence, etc.).
7241#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7242#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7243#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7244pub enum Action {
7245    /// Add a search optimization.
7246    AddSearchOptimization,
7247    /// Apply an `APPLY` operation with a specific type.
7248    Apply {
7249        /// The type of apply operation.
7250        apply_type: ActionApplyType,
7251    },
7252    /// Apply a budget operation.
7253    ApplyBudget,
7254    /// Attach a listing.
7255    AttachListing,
7256    /// Attach a policy.
7257    AttachPolicy,
7258    /// Audit operation.
7259    Audit,
7260    /// Bind a service endpoint.
7261    BindServiceEndpoint,
7262    /// Connect permission.
7263    Connect,
7264    /// Create action, optionally specifying an object type.
7265    Create {
7266        /// Optional object type to create.
7267        obj_type: Option<ActionCreateObjectType>,
7268    },
7269    /// Actions related to database roles.
7270    DatabaseRole {
7271        /// The role name.
7272        role: ObjectName,
7273    },
7274    /// Delete permission.
7275    Delete,
7276    /// Drop permission.
7277    Drop,
7278    /// Evolve schema permission.
7279    EvolveSchema,
7280    /// Exec action (execute) with optional object type.
7281    Exec {
7282        /// Optional execute object type.
7283        obj_type: Option<ActionExecuteObjectType>,
7284    },
7285    /// Execute action with optional object type.
7286    Execute {
7287        /// Optional execute object type.
7288        obj_type: Option<ActionExecuteObjectType>,
7289    },
7290    /// Failover operation.
7291    Failover,
7292    /// Use imported privileges.
7293    ImportedPrivileges,
7294    /// Import a share.
7295    ImportShare,
7296    /// Insert rows with optional column list.
7297    Insert {
7298        /// Optional list of target columns for insert.
7299        columns: Option<Vec<Ident>>,
7300    },
7301    /// Manage operation with a specific manage type.
7302    Manage {
7303        /// The specific manage sub-type.
7304        manage_type: ActionManageType,
7305    },
7306    /// Manage releases.
7307    ManageReleases,
7308    /// Manage versions.
7309    ManageVersions,
7310    /// Modify operation with an optional modify type.
7311    Modify {
7312        /// The optional modify sub-type.
7313        modify_type: Option<ActionModifyType>,
7314    },
7315    /// Monitor operation with an optional monitor type.
7316    Monitor {
7317        /// The optional monitor sub-type.
7318        monitor_type: Option<ActionMonitorType>,
7319    },
7320    /// Operate permission.
7321    Operate,
7322    /// Override share restrictions.
7323    OverrideShareRestrictions,
7324    /// Ownership permission.
7325    Ownership,
7326    /// Purchase a data exchange listing.
7327    PurchaseDataExchangeListing,
7328
7329    /// Read access.
7330    Read,
7331    /// Read session-level access.
7332    ReadSession,
7333    /// References with optional column list.
7334    References {
7335        /// Optional list of referenced column identifiers.
7336        columns: Option<Vec<Ident>>,
7337    },
7338    /// Replication permission.
7339    Replicate,
7340    /// Resolve all references.
7341    ResolveAll,
7342    /// Role-related permission with target role name.
7343    Role {
7344        /// The target role name.
7345        role: ObjectName,
7346    },
7347    /// Select permission with optional column list.
7348    Select {
7349        /// Optional list of selected columns.
7350        columns: Option<Vec<Ident>>,
7351    },
7352    /// Temporary object permission.
7353    Temporary,
7354    /// Trigger-related permission.
7355    Trigger,
7356    /// Truncate permission.
7357    Truncate,
7358    /// Update permission with optional affected columns.
7359    Update {
7360        /// Optional list of columns affected by update.
7361        columns: Option<Vec<Ident>>,
7362    },
7363    /// Usage permission.
7364    Usage,
7365}
7366
7367impl fmt::Display for Action {
7368    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7369        match self {
7370            Action::AddSearchOptimization => f.write_str("ADD SEARCH OPTIMIZATION")?,
7371            Action::Apply { apply_type } => write!(f, "APPLY {apply_type}")?,
7372            Action::ApplyBudget => f.write_str("APPLYBUDGET")?,
7373            Action::AttachListing => f.write_str("ATTACH LISTING")?,
7374            Action::AttachPolicy => f.write_str("ATTACH POLICY")?,
7375            Action::Audit => f.write_str("AUDIT")?,
7376            Action::BindServiceEndpoint => f.write_str("BIND SERVICE ENDPOINT")?,
7377            Action::Connect => f.write_str("CONNECT")?,
7378            Action::Create { obj_type } => {
7379                f.write_str("CREATE")?;
7380                if let Some(obj_type) = obj_type {
7381                    write!(f, " {obj_type}")?
7382                }
7383            }
7384            Action::DatabaseRole { role } => write!(f, "DATABASE ROLE {role}")?,
7385            Action::Delete => f.write_str("DELETE")?,
7386            Action::Drop => f.write_str("DROP")?,
7387            Action::EvolveSchema => f.write_str("EVOLVE SCHEMA")?,
7388            Action::Exec { obj_type } => {
7389                f.write_str("EXEC")?;
7390                if let Some(obj_type) = obj_type {
7391                    write!(f, " {obj_type}")?
7392                }
7393            }
7394            Action::Execute { obj_type } => {
7395                f.write_str("EXECUTE")?;
7396                if let Some(obj_type) = obj_type {
7397                    write!(f, " {obj_type}")?
7398                }
7399            }
7400            Action::Failover => f.write_str("FAILOVER")?,
7401            Action::ImportedPrivileges => f.write_str("IMPORTED PRIVILEGES")?,
7402            Action::ImportShare => f.write_str("IMPORT SHARE")?,
7403            Action::Insert { .. } => f.write_str("INSERT")?,
7404            Action::Manage { manage_type } => write!(f, "MANAGE {manage_type}")?,
7405            Action::ManageReleases => f.write_str("MANAGE RELEASES")?,
7406            Action::ManageVersions => f.write_str("MANAGE VERSIONS")?,
7407            Action::Modify { modify_type } => {
7408                write!(f, "MODIFY")?;
7409                if let Some(modify_type) = modify_type {
7410                    write!(f, " {modify_type}")?;
7411                }
7412            }
7413            Action::Monitor { monitor_type } => {
7414                write!(f, "MONITOR")?;
7415                if let Some(monitor_type) = monitor_type {
7416                    write!(f, " {monitor_type}")?
7417                }
7418            }
7419            Action::Operate => f.write_str("OPERATE")?,
7420            Action::OverrideShareRestrictions => f.write_str("OVERRIDE SHARE RESTRICTIONS")?,
7421            Action::Ownership => f.write_str("OWNERSHIP")?,
7422            Action::PurchaseDataExchangeListing => f.write_str("PURCHASE DATA EXCHANGE LISTING")?,
7423            Action::Read => f.write_str("READ")?,
7424            Action::ReadSession => f.write_str("READ SESSION")?,
7425            Action::References { .. } => f.write_str("REFERENCES")?,
7426            Action::Replicate => f.write_str("REPLICATE")?,
7427            Action::ResolveAll => f.write_str("RESOLVE ALL")?,
7428            Action::Role { role } => write!(f, "ROLE {role}")?,
7429            Action::Select { .. } => f.write_str("SELECT")?,
7430            Action::Temporary => f.write_str("TEMPORARY")?,
7431            Action::Trigger => f.write_str("TRIGGER")?,
7432            Action::Truncate => f.write_str("TRUNCATE")?,
7433            Action::Update { .. } => f.write_str("UPDATE")?,
7434            Action::Usage => f.write_str("USAGE")?,
7435        };
7436        match self {
7437            Action::Insert { columns }
7438            | Action::References { columns }
7439            | Action::Select { columns }
7440            | Action::Update { columns } => {
7441                if let Some(columns) = columns {
7442                    write!(f, " ({})", display_comma_separated(columns))?;
7443                }
7444            }
7445            _ => (),
7446        };
7447        Ok(())
7448    }
7449}
7450
7451#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7452#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7453#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7454/// See <https://docs.snowflake.com/en/sql-reference/sql/grant-privilege>
7455/// under `globalPrivileges` in the `CREATE` privilege.
7456pub enum ActionCreateObjectType {
7457    /// An account-level object.
7458    Account,
7459    /// An application object.
7460    Application,
7461    /// An application package object.
7462    ApplicationPackage,
7463    /// A compute pool object.
7464    ComputePool,
7465    /// A data exchange listing.
7466    DataExchangeListing,
7467    /// A database object.
7468    Database,
7469    /// An external volume object.
7470    ExternalVolume,
7471    /// A failover group object.
7472    FailoverGroup,
7473    /// An integration object.
7474    Integration,
7475    /// A network policy object.
7476    NetworkPolicy,
7477    /// An organization listing.
7478    OrganiationListing,
7479    /// A replication group object.
7480    ReplicationGroup,
7481    /// A role object.
7482    Role,
7483    /// A schema object.
7484    Schema,
7485    /// A share object.
7486    Share,
7487    /// A user object.
7488    User,
7489    /// A warehouse object.
7490    Warehouse,
7491}
7492
7493impl fmt::Display for ActionCreateObjectType {
7494    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7495        match self {
7496            ActionCreateObjectType::Account => write!(f, "ACCOUNT"),
7497            ActionCreateObjectType::Application => write!(f, "APPLICATION"),
7498            ActionCreateObjectType::ApplicationPackage => write!(f, "APPLICATION PACKAGE"),
7499            ActionCreateObjectType::ComputePool => write!(f, "COMPUTE POOL"),
7500            ActionCreateObjectType::DataExchangeListing => write!(f, "DATA EXCHANGE LISTING"),
7501            ActionCreateObjectType::Database => write!(f, "DATABASE"),
7502            ActionCreateObjectType::ExternalVolume => write!(f, "EXTERNAL VOLUME"),
7503            ActionCreateObjectType::FailoverGroup => write!(f, "FAILOVER GROUP"),
7504            ActionCreateObjectType::Integration => write!(f, "INTEGRATION"),
7505            ActionCreateObjectType::NetworkPolicy => write!(f, "NETWORK POLICY"),
7506            ActionCreateObjectType::OrganiationListing => write!(f, "ORGANIZATION LISTING"),
7507            ActionCreateObjectType::ReplicationGroup => write!(f, "REPLICATION GROUP"),
7508            ActionCreateObjectType::Role => write!(f, "ROLE"),
7509            ActionCreateObjectType::Schema => write!(f, "SCHEMA"),
7510            ActionCreateObjectType::Share => write!(f, "SHARE"),
7511            ActionCreateObjectType::User => write!(f, "USER"),
7512            ActionCreateObjectType::Warehouse => write!(f, "WAREHOUSE"),
7513        }
7514    }
7515}
7516
7517#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7518#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7519#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7520/// See <https://docs.snowflake.com/en/sql-reference/sql/grant-privilege>
7521/// under `globalPrivileges` in the `APPLY` privilege.
7522pub enum ActionApplyType {
7523    /// Apply an aggregation policy.
7524    AggregationPolicy,
7525    /// Apply an authentication policy.
7526    AuthenticationPolicy,
7527    /// Apply a join policy.
7528    JoinPolicy,
7529    /// Apply a masking policy.
7530    MaskingPolicy,
7531    /// Apply a packages policy.
7532    PackagesPolicy,
7533    /// Apply a password policy.
7534    PasswordPolicy,
7535    /// Apply a projection policy.
7536    ProjectionPolicy,
7537    /// Apply a row access policy.
7538    RowAccessPolicy,
7539    /// Apply a session policy.
7540    SessionPolicy,
7541    /// Apply a tag.
7542    Tag,
7543}
7544
7545impl fmt::Display for ActionApplyType {
7546    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7547        match self {
7548            ActionApplyType::AggregationPolicy => write!(f, "AGGREGATION POLICY"),
7549            ActionApplyType::AuthenticationPolicy => write!(f, "AUTHENTICATION POLICY"),
7550            ActionApplyType::JoinPolicy => write!(f, "JOIN POLICY"),
7551            ActionApplyType::MaskingPolicy => write!(f, "MASKING POLICY"),
7552            ActionApplyType::PackagesPolicy => write!(f, "PACKAGES POLICY"),
7553            ActionApplyType::PasswordPolicy => write!(f, "PASSWORD POLICY"),
7554            ActionApplyType::ProjectionPolicy => write!(f, "PROJECTION POLICY"),
7555            ActionApplyType::RowAccessPolicy => write!(f, "ROW ACCESS POLICY"),
7556            ActionApplyType::SessionPolicy => write!(f, "SESSION POLICY"),
7557            ActionApplyType::Tag => write!(f, "TAG"),
7558        }
7559    }
7560}
7561
7562#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7563#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7564#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7565/// See <https://docs.snowflake.com/en/sql-reference/sql/grant-privilege>
7566/// under `globalPrivileges` in the `EXECUTE` privilege.
7567pub enum ActionExecuteObjectType {
7568    /// Alert object.
7569    Alert,
7570    /// Data metric function object.
7571    DataMetricFunction,
7572    /// Managed alert object.
7573    ManagedAlert,
7574    /// Managed task object.
7575    ManagedTask,
7576    /// Task object.
7577    Task,
7578}
7579
7580impl fmt::Display for ActionExecuteObjectType {
7581    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7582        match self {
7583            ActionExecuteObjectType::Alert => write!(f, "ALERT"),
7584            ActionExecuteObjectType::DataMetricFunction => write!(f, "DATA METRIC FUNCTION"),
7585            ActionExecuteObjectType::ManagedAlert => write!(f, "MANAGED ALERT"),
7586            ActionExecuteObjectType::ManagedTask => write!(f, "MANAGED TASK"),
7587            ActionExecuteObjectType::Task => write!(f, "TASK"),
7588        }
7589    }
7590}
7591
7592#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7593#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7594#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7595/// See <https://docs.snowflake.com/en/sql-reference/sql/grant-privilege>
7596/// under `globalPrivileges` in the `MANAGE` privilege.
7597pub enum ActionManageType {
7598    /// Account support cases management.
7599    AccountSupportCases,
7600    /// Event sharing management.
7601    EventSharing,
7602    /// Grants management.
7603    Grants,
7604    /// Listing auto-fulfillment management.
7605    ListingAutoFulfillment,
7606    /// Organization support cases management.
7607    OrganizationSupportCases,
7608    /// User support cases management.
7609    UserSupportCases,
7610    /// Warehouses management.
7611    Warehouses,
7612}
7613
7614impl fmt::Display for ActionManageType {
7615    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7616        match self {
7617            ActionManageType::AccountSupportCases => write!(f, "ACCOUNT SUPPORT CASES"),
7618            ActionManageType::EventSharing => write!(f, "EVENT SHARING"),
7619            ActionManageType::Grants => write!(f, "GRANTS"),
7620            ActionManageType::ListingAutoFulfillment => write!(f, "LISTING AUTO FULFILLMENT"),
7621            ActionManageType::OrganizationSupportCases => write!(f, "ORGANIZATION SUPPORT CASES"),
7622            ActionManageType::UserSupportCases => write!(f, "USER SUPPORT CASES"),
7623            ActionManageType::Warehouses => write!(f, "WAREHOUSES"),
7624        }
7625    }
7626}
7627
7628#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7629#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7630#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7631/// See <https://docs.snowflake.com/en/sql-reference/sql/grant-privilege>
7632/// under `globalPrivileges` in the `MODIFY` privilege.
7633pub enum ActionModifyType {
7634    /// Modify log level.
7635    LogLevel,
7636    /// Modify trace level.
7637    TraceLevel,
7638    /// Modify session log level.
7639    SessionLogLevel,
7640    /// Modify session trace level.
7641    SessionTraceLevel,
7642}
7643
7644impl fmt::Display for ActionModifyType {
7645    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7646        match self {
7647            ActionModifyType::LogLevel => write!(f, "LOG LEVEL"),
7648            ActionModifyType::TraceLevel => write!(f, "TRACE LEVEL"),
7649            ActionModifyType::SessionLogLevel => write!(f, "SESSION LOG LEVEL"),
7650            ActionModifyType::SessionTraceLevel => write!(f, "SESSION TRACE LEVEL"),
7651        }
7652    }
7653}
7654
7655#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7656#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7657#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7658/// See <https://docs.snowflake.com/en/sql-reference/sql/grant-privilege>
7659/// under `globalPrivileges` in the `MONITOR` privilege.
7660pub enum ActionMonitorType {
7661    /// Monitor execution.
7662    Execution,
7663    /// Monitor security.
7664    Security,
7665    /// Monitor usage.
7666    Usage,
7667}
7668
7669impl fmt::Display for ActionMonitorType {
7670    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7671        match self {
7672            ActionMonitorType::Execution => write!(f, "EXECUTION"),
7673            ActionMonitorType::Security => write!(f, "SECURITY"),
7674            ActionMonitorType::Usage => write!(f, "USAGE"),
7675        }
7676    }
7677}
7678
7679/// The principal that receives the privileges
7680#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7681#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7682#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7683pub struct Grantee {
7684    /// The category/type of grantee (role, user, share, etc.).
7685    pub grantee_type: GranteesType,
7686    /// Optional name of the grantee (identifier or user@host).
7687    pub name: Option<GranteeName>,
7688}
7689
7690impl fmt::Display for Grantee {
7691    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7692        let keyword = match self.grantee_type {
7693            GranteesType::Role => "ROLE",
7694            GranteesType::Share => "SHARE",
7695            GranteesType::User => "USER",
7696            GranteesType::Group => "GROUP",
7697            GranteesType::Public => "PUBLIC",
7698            GranteesType::DatabaseRole => "DATABASE ROLE",
7699            GranteesType::Application => "APPLICATION",
7700            GranteesType::ApplicationRole => "APPLICATION ROLE",
7701            GranteesType::None => "",
7702        };
7703        f.write_str(keyword)?;
7704        if let Some(name) = &self.name {
7705            if !keyword.is_empty() {
7706                f.write_str(" ")?;
7707            }
7708            name.fmt(f)?;
7709        }
7710        Ok(())
7711    }
7712}
7713
7714#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7715#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7716#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7717/// The kind of principal receiving privileges.
7718pub enum GranteesType {
7719    /// A role principal.
7720    Role,
7721    /// A share principal.
7722    Share,
7723    /// A user principal.
7724    User,
7725    /// A group principal.
7726    Group,
7727    /// The public principal.
7728    Public,
7729    /// A database role principal.
7730    DatabaseRole,
7731    /// An application principal.
7732    Application,
7733    /// An application role principal.
7734    ApplicationRole,
7735    /// No specific principal (e.g. `NONE`).
7736    None,
7737}
7738
7739/// Users/roles designated in a GRANT/REVOKE
7740#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7741#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7742#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7743pub enum GranteeName {
7744    /// A bare identifier
7745    ObjectName(ObjectName),
7746    /// A MySQL user/host pair such as 'root'@'%'
7747    UserHost {
7748        /// The user identifier portion.
7749        user: Ident,
7750        /// The host identifier portion.
7751        host: Ident,
7752    },
7753}
7754
7755impl fmt::Display for GranteeName {
7756    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7757        match self {
7758            GranteeName::ObjectName(name) => name.fmt(f),
7759            GranteeName::UserHost { user, host } => {
7760                write!(f, "{user}@{host}")
7761            }
7762        }
7763    }
7764}
7765
7766/// Objects on which privileges are granted in a GRANT statement.
7767#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7768#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7769#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7770pub enum GrantObjects {
7771    /// Grant privileges on `ALL SEQUENCES IN SCHEMA <schema_name> [, ...]`
7772    AllSequencesInSchema {
7773        /// The target schema names.
7774        schemas: Vec<ObjectName>,
7775    },
7776    /// Grant privileges on `ALL TABLES IN SCHEMA <schema_name> [, ...]`
7777    AllTablesInSchema {
7778        /// The target schema names.
7779        schemas: Vec<ObjectName>,
7780    },
7781    /// Grant privileges on `ALL VIEWS IN SCHEMA <schema_name> [, ...]`
7782    AllViewsInSchema {
7783        /// The target schema names.
7784        schemas: Vec<ObjectName>,
7785    },
7786    /// Grant privileges on `ALL MATERIALIZED VIEWS IN SCHEMA <schema_name> [, ...]`
7787    AllMaterializedViewsInSchema {
7788        /// The target schema names.
7789        schemas: Vec<ObjectName>,
7790    },
7791    /// Grant privileges on `ALL EXTERNAL TABLES IN SCHEMA <schema_name> [, ...]`
7792    AllExternalTablesInSchema {
7793        /// The target schema names.
7794        schemas: Vec<ObjectName>,
7795    },
7796    /// Grant privileges on `ALL FUNCTIONS IN SCHEMA <schema_name> [, ...]`
7797    AllFunctionsInSchema {
7798        /// The target schema names.
7799        schemas: Vec<ObjectName>,
7800    },
7801    /// Grant privileges on `ALL PROCEDURES IN SCHEMA <schema_name> [, ...]`
7802    AllProceduresInSchema {
7803        /// The target schema names.
7804        schemas: Vec<ObjectName>,
7805    },
7806    /// Grant privileges on `ALL ROUTINES IN SCHEMA <schema_name> [, ...]`
7807    AllRoutinesInSchema {
7808        /// The target schema names.
7809        schemas: Vec<ObjectName>,
7810    },
7811    /// Grant privileges on `FUTURE SCHEMAS IN DATABASE <database_name> [, ...]`
7812    FutureSchemasInDatabase {
7813        /// The target database names.
7814        databases: Vec<ObjectName>,
7815    },
7816    /// Grant privileges on `FUTURE TABLES IN SCHEMA <schema_name> [, ...]`
7817    FutureTablesInSchema {
7818        /// The target schema names.
7819        schemas: Vec<ObjectName>,
7820    },
7821    /// Grant privileges on `FUTURE VIEWS IN SCHEMA <schema_name> [, ...]`
7822    FutureViewsInSchema {
7823        /// The target schema names.
7824        schemas: Vec<ObjectName>,
7825    },
7826    /// Grant privileges on `FUTURE EXTERNAL TABLES IN SCHEMA <schema_name> [, ...]`
7827    FutureExternalTablesInSchema {
7828        /// The target schema names.
7829        schemas: Vec<ObjectName>,
7830    },
7831    /// Grant privileges on `FUTURE MATERIALIZED VIEWS IN SCHEMA <schema_name> [, ...]`
7832    FutureMaterializedViewsInSchema {
7833        /// The target schema names.
7834        schemas: Vec<ObjectName>,
7835    },
7836    /// Grant privileges on `FUTURE SEQUENCES IN SCHEMA <schema_name> [, ...]`
7837    FutureSequencesInSchema {
7838        /// The target schema names.
7839        schemas: Vec<ObjectName>,
7840    },
7841    /// Grant privileges on specific databases
7842    Databases(Vec<ObjectName>),
7843    /// Grant privileges on specific schemas
7844    Schemas(Vec<ObjectName>),
7845    /// Grant privileges on specific sequences
7846    Sequences(Vec<ObjectName>),
7847    /// Grant privileges on specific tables
7848    Tables(Vec<ObjectName>),
7849    /// Grant privileges on specific views
7850    Views(Vec<ObjectName>),
7851    /// Grant privileges on specific warehouses
7852    Warehouses(Vec<ObjectName>),
7853    /// Grant privileges on specific integrations
7854    Integrations(Vec<ObjectName>),
7855    /// Grant privileges on resource monitors
7856    ResourceMonitors(Vec<ObjectName>),
7857    /// Grant privileges on users
7858    Users(Vec<ObjectName>),
7859    /// Grant privileges on compute pools
7860    ComputePools(Vec<ObjectName>),
7861    /// Grant privileges on connections
7862    Connections(Vec<ObjectName>),
7863    /// Grant privileges on failover groups
7864    FailoverGroup(Vec<ObjectName>),
7865    /// Grant privileges on replication group
7866    ReplicationGroup(Vec<ObjectName>),
7867    /// Grant privileges on external volumes
7868    ExternalVolumes(Vec<ObjectName>),
7869    /// Grant privileges on procedures, each with an optional argument list.
7870    ///
7871    /// For example:
7872    /// `GRANT USAGE ON PROCEDURE foo(varchar) TO ROLE role1`
7873    Procedures(Vec<FunctionDesc>),
7874    /// Grant privileges on functions, each with an optional argument list.
7875    ///
7876    /// For example:
7877    /// `GRANT EXECUTE ON FUNCTION foo(p_id uuid), bar() TO role1`
7878    Functions(Vec<FunctionDesc>),
7879    /// Grant privileges on routines, which name functions and procedures alike.
7880    ///
7881    /// For example:
7882    /// `GRANT EXECUTE ON ROUTINE foo(p_id uuid), bar() TO role1`
7883    ///
7884    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-grant.html)
7885    Routines(Vec<FunctionDesc>),
7886}
7887
7888impl fmt::Display for GrantObjects {
7889    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7890        match self {
7891            GrantObjects::Sequences(sequences) => {
7892                write!(f, "SEQUENCE {}", display_comma_separated(sequences))
7893            }
7894            GrantObjects::Databases(databases) => {
7895                write!(f, "DATABASE {}", display_comma_separated(databases))
7896            }
7897            GrantObjects::Schemas(schemas) => {
7898                write!(f, "SCHEMA {}", display_comma_separated(schemas))
7899            }
7900            GrantObjects::Tables(tables) => {
7901                write!(f, "{}", display_comma_separated(tables))
7902            }
7903            GrantObjects::Views(views) => {
7904                write!(f, "VIEW {}", display_comma_separated(views))
7905            }
7906            GrantObjects::Warehouses(warehouses) => {
7907                write!(f, "WAREHOUSE {}", display_comma_separated(warehouses))
7908            }
7909            GrantObjects::Integrations(integrations) => {
7910                write!(f, "INTEGRATION {}", display_comma_separated(integrations))
7911            }
7912            GrantObjects::AllSequencesInSchema { schemas } => {
7913                write!(
7914                    f,
7915                    "ALL SEQUENCES IN SCHEMA {}",
7916                    display_comma_separated(schemas)
7917                )
7918            }
7919            GrantObjects::AllTablesInSchema { schemas } => {
7920                write!(
7921                    f,
7922                    "ALL TABLES IN SCHEMA {}",
7923                    display_comma_separated(schemas)
7924                )
7925            }
7926            GrantObjects::AllExternalTablesInSchema { schemas } => {
7927                write!(
7928                    f,
7929                    "ALL EXTERNAL TABLES IN SCHEMA {}",
7930                    display_comma_separated(schemas)
7931                )
7932            }
7933            GrantObjects::AllViewsInSchema { schemas } => {
7934                write!(
7935                    f,
7936                    "ALL VIEWS IN SCHEMA {}",
7937                    display_comma_separated(schemas)
7938                )
7939            }
7940            GrantObjects::AllMaterializedViewsInSchema { schemas } => {
7941                write!(
7942                    f,
7943                    "ALL MATERIALIZED VIEWS IN SCHEMA {}",
7944                    display_comma_separated(schemas)
7945                )
7946            }
7947            GrantObjects::AllFunctionsInSchema { schemas } => {
7948                write!(
7949                    f,
7950                    "ALL FUNCTIONS IN SCHEMA {}",
7951                    display_comma_separated(schemas)
7952                )
7953            }
7954            GrantObjects::AllProceduresInSchema { schemas } => {
7955                write!(
7956                    f,
7957                    "ALL PROCEDURES IN SCHEMA {}",
7958                    display_comma_separated(schemas)
7959                )
7960            }
7961            GrantObjects::AllRoutinesInSchema { schemas } => {
7962                write!(
7963                    f,
7964                    "ALL ROUTINES IN SCHEMA {}",
7965                    display_comma_separated(schemas)
7966                )
7967            }
7968            GrantObjects::FutureSchemasInDatabase { databases } => {
7969                write!(
7970                    f,
7971                    "FUTURE SCHEMAS IN DATABASE {}",
7972                    display_comma_separated(databases)
7973                )
7974            }
7975            GrantObjects::FutureTablesInSchema { schemas } => {
7976                write!(
7977                    f,
7978                    "FUTURE TABLES IN SCHEMA {}",
7979                    display_comma_separated(schemas)
7980                )
7981            }
7982            GrantObjects::FutureExternalTablesInSchema { schemas } => {
7983                write!(
7984                    f,
7985                    "FUTURE EXTERNAL TABLES IN SCHEMA {}",
7986                    display_comma_separated(schemas)
7987                )
7988            }
7989            GrantObjects::FutureViewsInSchema { schemas } => {
7990                write!(
7991                    f,
7992                    "FUTURE VIEWS IN SCHEMA {}",
7993                    display_comma_separated(schemas)
7994                )
7995            }
7996            GrantObjects::FutureMaterializedViewsInSchema { schemas } => {
7997                write!(
7998                    f,
7999                    "FUTURE MATERIALIZED VIEWS IN SCHEMA {}",
8000                    display_comma_separated(schemas)
8001                )
8002            }
8003            GrantObjects::FutureSequencesInSchema { schemas } => {
8004                write!(
8005                    f,
8006                    "FUTURE SEQUENCES IN SCHEMA {}",
8007                    display_comma_separated(schemas)
8008                )
8009            }
8010            GrantObjects::ResourceMonitors(objects) => {
8011                write!(f, "RESOURCE MONITOR {}", display_comma_separated(objects))
8012            }
8013            GrantObjects::Users(objects) => {
8014                write!(f, "USER {}", display_comma_separated(objects))
8015            }
8016            GrantObjects::ComputePools(objects) => {
8017                write!(f, "COMPUTE POOL {}", display_comma_separated(objects))
8018            }
8019            GrantObjects::Connections(objects) => {
8020                write!(f, "CONNECTION {}", display_comma_separated(objects))
8021            }
8022            GrantObjects::FailoverGroup(objects) => {
8023                write!(f, "FAILOVER GROUP {}", display_comma_separated(objects))
8024            }
8025            GrantObjects::ReplicationGroup(objects) => {
8026                write!(f, "REPLICATION GROUP {}", display_comma_separated(objects))
8027            }
8028            GrantObjects::ExternalVolumes(objects) => {
8029                write!(f, "EXTERNAL VOLUME {}", display_comma_separated(objects))
8030            }
8031            GrantObjects::Procedures(procedures) => {
8032                write!(f, "PROCEDURE {}", display_comma_separated(procedures))
8033            }
8034            GrantObjects::Functions(functions) => {
8035                write!(f, "FUNCTION {}", display_comma_separated(functions))
8036            }
8037            GrantObjects::Routines(routines) => {
8038                write!(f, "ROUTINE {}", display_comma_separated(routines))
8039            }
8040        }
8041    }
8042}
8043
8044/// A `DENY` statement
8045///
8046/// [MsSql](https://learn.microsoft.com/en-us/sql/t-sql/statements/deny-transact-sql)
8047#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8048#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8049#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8050pub struct DenyStatement {
8051    /// The privileges to deny.
8052    pub privileges: Privileges,
8053    /// The objects the privileges apply to.
8054    pub objects: GrantObjects,
8055    /// The grantees (users/roles) to whom the denial applies.
8056    pub grantees: Vec<Grantee>,
8057    /// Optional identifier of the principal that performed the grant.
8058    pub granted_by: Option<Ident>,
8059    /// Optional cascade option controlling dependent objects.
8060    pub cascade: Option<CascadeOption>,
8061}
8062
8063impl fmt::Display for DenyStatement {
8064    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8065        write!(f, "DENY {}", self.privileges)?;
8066        write!(f, " ON {}", self.objects)?;
8067        if !self.grantees.is_empty() {
8068            write!(f, " TO {}", display_comma_separated(&self.grantees))?;
8069        }
8070        if let Some(cascade) = &self.cascade {
8071            write!(f, " {cascade}")?;
8072        }
8073        if let Some(granted_by) = &self.granted_by {
8074            write!(f, " AS {granted_by}")?;
8075        }
8076        Ok(())
8077    }
8078}
8079
8080/// SQL assignment `foo = expr` as used in SQLUpdate
8081#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8082#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8083#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8084pub struct Assignment {
8085    /// The left-hand side of the assignment.
8086    pub target: AssignmentTarget,
8087    /// The expression assigned to the target.
8088    pub value: Expr,
8089}
8090
8091impl fmt::Display for Assignment {
8092    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8093        write!(f, "{} = {}", self.target, self.value)
8094    }
8095}
8096
8097/// Left-hand side of an assignment in an UPDATE statement,
8098/// e.g. `foo` in `foo = 5` (ColumnName assignment) or
8099/// `(a, b)` in `(a, b) = (1, 2)` (Tuple assignment).
8100#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8101#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8102#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8103pub enum AssignmentTarget {
8104    /// A single column
8105    ColumnName(ObjectName),
8106    /// A tuple of columns
8107    Tuple(Vec<ObjectName>),
8108}
8109
8110impl fmt::Display for AssignmentTarget {
8111    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8112        match self {
8113            AssignmentTarget::ColumnName(column) => write!(f, "{column}"),
8114            AssignmentTarget::Tuple(columns) => write!(f, "({})", display_comma_separated(columns)),
8115        }
8116    }
8117}
8118
8119#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8120#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8121#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8122/// Expression forms allowed as a function argument.
8123pub enum FunctionArgExpr {
8124    /// A normal expression argument.
8125    Expr(Expr),
8126    /// Qualified wildcard, e.g. `alias.*` or `schema.table.*`.
8127    QualifiedWildcard(ObjectName),
8128    /// An unqualified `*` wildcard.
8129    Wildcard,
8130    /// An unqualified `*` wildcard with additional options, e.g. `* EXCLUDE(col)`.
8131    ///
8132    /// Used in Snowflake to support expressions like `HASH(* EXCLUDE(col))`.
8133    WildcardWithOptions(WildcardAdditionalOptions),
8134}
8135
8136impl From<Expr> for FunctionArgExpr {
8137    fn from(wildcard_expr: Expr) -> Self {
8138        match wildcard_expr {
8139            Expr::QualifiedWildcard(prefix, _) => Self::QualifiedWildcard(prefix),
8140            Expr::Wildcard(_) => Self::Wildcard,
8141            expr => Self::Expr(expr),
8142        }
8143    }
8144}
8145
8146impl fmt::Display for FunctionArgExpr {
8147    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8148        match self {
8149            FunctionArgExpr::Expr(expr) => write!(f, "{expr}"),
8150            FunctionArgExpr::QualifiedWildcard(prefix) => write!(f, "{prefix}.*"),
8151            FunctionArgExpr::Wildcard => f.write_str("*"),
8152            FunctionArgExpr::WildcardWithOptions(opts) => write!(f, "*{opts}"),
8153        }
8154    }
8155}
8156
8157#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8158#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8159#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8160/// Operator used to separate function arguments
8161pub enum FunctionArgOperator {
8162    /// function(arg1 = value1)
8163    Equals,
8164    /// function(arg1 => value1)
8165    RightArrow,
8166    /// function(arg1 := value1)
8167    Assignment,
8168    /// function(arg1 : value1)
8169    Colon,
8170    /// function(arg1 VALUE value1)
8171    Value,
8172    /// function(arg1 value1), with no operator between the name and the value,
8173    /// as in PostgreSQL `XMLPARSE(DOCUMENT value)`
8174    ///
8175    /// [PostgreSQL](https://www.postgresql.org/docs/current/datatype-xml.html#DATATYPE-XML-CREATING)
8176    Space,
8177}
8178
8179impl fmt::Display for FunctionArgOperator {
8180    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8181        match self {
8182            FunctionArgOperator::Equals => f.write_str("="),
8183            FunctionArgOperator::RightArrow => f.write_str("=>"),
8184            FunctionArgOperator::Assignment => f.write_str(":="),
8185            FunctionArgOperator::Colon => f.write_str(":"),
8186            FunctionArgOperator::Value => f.write_str("VALUE"),
8187            FunctionArgOperator::Space => Ok(()),
8188        }
8189    }
8190}
8191
8192#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8193#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8194#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8195/// Forms of function arguments (named, expression-named, or positional).
8196pub enum FunctionArg {
8197    /// `name` is identifier
8198    ///
8199    /// Enabled when `Dialect::supports_named_fn_args_with_expr_name` returns 'false'
8200    Named {
8201        /// The identifier name of the argument.
8202        name: Ident,
8203        /// The argument expression or wildcard form.
8204        arg: FunctionArgExpr,
8205        /// The operator separating name and value.
8206        operator: FunctionArgOperator,
8207    },
8208    /// `name` is arbitrary expression
8209    ///
8210    /// Enabled when `Dialect::supports_named_fn_args_with_expr_name` returns 'true'
8211    ExprNamed {
8212        /// The expression used as the argument name.
8213        name: Expr,
8214        /// The argument expression or wildcard form.
8215        arg: FunctionArgExpr,
8216        /// The operator separating name and value.
8217        operator: FunctionArgOperator,
8218    },
8219    /// An unnamed argument (positional), given by expression or wildcard.
8220    Unnamed(FunctionArgExpr),
8221}
8222
8223impl fmt::Display for FunctionArg {
8224    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8225        match self {
8226            FunctionArg::Named {
8227                name,
8228                arg,
8229                operator,
8230            } => fmt_named_function_arg(f, name, operator, arg),
8231            FunctionArg::ExprNamed {
8232                name,
8233                arg,
8234                operator,
8235            } => fmt_named_function_arg(f, name, operator, arg),
8236            FunctionArg::Unnamed(unnamed_arg) => write!(f, "{unnamed_arg}"),
8237        }
8238    }
8239}
8240
8241/// Whether `expr` renders with an operator character first. A prefix `-` or `!`
8242/// must not abut one, since `--` starts a line comment and compound tokens
8243/// like `!!` or `!~` alter the parsed AST or fail to parse.
8244fn starts_with_operator_char(expr: &Expr) -> bool {
8245    first_char(expr).is_some_and(|c| OPERATOR_CHARS.contains(c))
8246}
8247
8248/// `FunctionArgOperator::Space` has no token of its own, so the name and the
8249/// value are separated by a single space instead.
8250fn fmt_named_function_arg(
8251    f: &mut fmt::Formatter,
8252    name: &impl fmt::Display,
8253    operator: &FunctionArgOperator,
8254    arg: &FunctionArgExpr,
8255) -> fmt::Result {
8256    match operator {
8257        FunctionArgOperator::Space => write!(f, "{name} {arg}"),
8258        _ => write!(f, "{name} {operator} {arg}"),
8259    }
8260}
8261
8262#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8263#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8264#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8265/// Which cursor(s) to close.
8266pub enum CloseCursor {
8267    /// Close all cursors.
8268    All,
8269    /// Close a specific cursor by name.
8270    Specific {
8271        /// The name of the cursor to close.
8272        name: Ident,
8273    },
8274}
8275
8276impl fmt::Display for CloseCursor {
8277    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8278        match self {
8279            CloseCursor::All => write!(f, "ALL"),
8280            CloseCursor::Specific { name } => write!(f, "{name}"),
8281        }
8282    }
8283}
8284
8285/// A Drop Domain statement
8286#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8287#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8288#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8289pub struct DropDomain {
8290    /// Whether to drop the domain if it exists
8291    pub if_exists: bool,
8292    /// The name of the domain to drop
8293    pub name: ObjectName,
8294    /// The behavior to apply when dropping the domain
8295    pub drop_behavior: Option<DropBehavior>,
8296}
8297
8298/// A constant of form `<data_type> 'value'`.
8299/// This can represent ANSI SQL `DATE`, `TIME`, and `TIMESTAMP` literals (such as `DATE '2020-01-01'`),
8300/// as well as constants of other types (a non-standard PostgreSQL extension).
8301#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8302#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8303#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8304pub struct TypedString {
8305    /// The data type of the typed string (e.g. DATE, TIME, TIMESTAMP).
8306    pub data_type: DataType,
8307    /// The value of the constant.
8308    /// Hint: you can unwrap the string value using `value.into_string()`.
8309    pub value: ValueWithSpan,
8310    /// Flags whether this TypedString uses the [ODBC syntax].
8311    ///
8312    /// Example:
8313    /// ```sql
8314    /// -- An ODBC date literal:
8315    /// SELECT {d '2025-07-16'}
8316    /// -- This is equivalent to the standard ANSI SQL literal:
8317    /// SELECT DATE '2025-07-16'
8318    ///
8319    /// [ODBC syntax]: https://learn.microsoft.com/en-us/sql/odbc/reference/develop-app/date-time-and-timestamp-literals?view=sql-server-2017
8320    pub uses_odbc_syntax: bool,
8321}
8322
8323impl fmt::Display for TypedString {
8324    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8325        let data_type = &self.data_type;
8326        let value = &self.value;
8327        match self.uses_odbc_syntax {
8328            false => {
8329                write!(f, "{data_type}")?;
8330                write!(f, " {value}")
8331            }
8332            true => {
8333                let prefix = match data_type {
8334                    DataType::Date => "d",
8335                    DataType::Time(..) => "t",
8336                    DataType::Timestamp(..) => "ts",
8337                    _ => "?",
8338                };
8339                write!(f, "{{{prefix} {value}}}")
8340            }
8341        }
8342    }
8343}
8344
8345/// A function call
8346#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8347#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8348#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8349pub struct Function {
8350    /// The function name (may be qualified).
8351    pub name: ObjectName,
8352    /// Flags whether this function call uses the [ODBC syntax].
8353    ///
8354    /// Example:
8355    /// ```sql
8356    /// SELECT {fn CONCAT('foo', 'bar')}
8357    /// ```
8358    ///
8359    /// [ODBC syntax]: https://learn.microsoft.com/en-us/sql/odbc/reference/develop-app/scalar-function-calls?view=sql-server-2017
8360    pub uses_odbc_syntax: bool,
8361    /// The parameters to the function, including any options specified within the
8362    /// delimiting parentheses.
8363    ///
8364    /// Example:
8365    /// ```plaintext
8366    /// HISTOGRAM(0.5, 0.6)(x, y)
8367    /// ```
8368    ///
8369    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/aggregate-functions/parametric-functions)
8370    pub parameters: FunctionArguments,
8371    /// The arguments to the function, including any options specified within the
8372    /// delimiting parentheses.
8373    pub args: FunctionArguments,
8374    /// A clause used with certain aggregate functions to control the ordering
8375    /// within grouped sets before the function is applied.
8376    ///
8377    /// Syntax:
8378    /// ```plaintext
8379    /// <aggregate_function>(expression) WITHIN GROUP (ORDER BY key [ASC | DESC], ...)
8380    /// ```
8381    pub within_group: Vec<OrderByExpr>,
8382    /// e.g. `x > 5` in `COUNT(x) FILTER (WHERE x > 5)`
8383    pub filter: Option<Box<Expr>>,
8384    /// Indicates how `NULL`s should be handled in the calculation.
8385    ///
8386    /// Example:
8387    /// ```plaintext
8388    /// FIRST_VALUE( <expr> ) [ { IGNORE | RESPECT } NULLS ] OVER ...
8389    /// ```
8390    ///
8391    /// [Snowflake](https://docs.snowflake.com/en/sql-reference/functions/first_value)
8392    pub null_treatment: Option<NullTreatment>,
8393    /// The `OVER` clause, indicating a window function call.
8394    pub over: Option<WindowType>,
8395}
8396
8397impl fmt::Display for Function {
8398    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8399        if self.uses_odbc_syntax {
8400            write!(f, "{{fn ")?;
8401        }
8402
8403        write!(f, "{}{}{}", self.name, self.parameters, self.args)?;
8404
8405        if !self.within_group.is_empty() {
8406            write!(
8407                f,
8408                " WITHIN GROUP (ORDER BY {})",
8409                display_comma_separated(&self.within_group)
8410            )?;
8411        }
8412
8413        if let Some(filter_cond) = &self.filter {
8414            write!(f, " FILTER (WHERE {filter_cond})")?;
8415        }
8416
8417        if let Some(null_treatment) = &self.null_treatment {
8418            write!(f, " {null_treatment}")?;
8419        }
8420
8421        if let Some(o) = &self.over {
8422            f.write_str(" OVER ")?;
8423            o.fmt(f)?;
8424        }
8425
8426        if self.uses_odbc_syntax {
8427            write!(f, "}}")?;
8428        }
8429
8430        Ok(())
8431    }
8432}
8433
8434/// The arguments passed to a function call.
8435#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8436#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8437#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8438pub enum FunctionArguments {
8439    /// Used for special functions like `CURRENT_TIMESTAMP` that are invoked
8440    /// without parentheses.
8441    None,
8442    /// On some dialects, a subquery can be passed without surrounding
8443    /// parentheses if it's the sole argument to the function.
8444    Subquery(Box<Query>),
8445    /// A normal function argument list, including any clauses within it such as
8446    /// `DISTINCT` or `ORDER BY`.
8447    List(FunctionArgumentList),
8448}
8449
8450impl fmt::Display for FunctionArguments {
8451    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8452        match self {
8453            FunctionArguments::None => Ok(()),
8454            FunctionArguments::Subquery(query) => write!(f, "({query})"),
8455            FunctionArguments::List(args) => write!(f, "({args})"),
8456        }
8457    }
8458}
8459
8460/// This represents everything inside the parentheses when calling a function.
8461#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8462#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8463#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8464pub struct FunctionArgumentList {
8465    /// `[ ALL | DISTINCT ]`
8466    pub duplicate_treatment: Option<DuplicateTreatment>,
8467    /// The function arguments.
8468    pub args: Vec<FunctionArg>,
8469    /// Additional clauses specified within the argument list.
8470    pub clauses: Vec<FunctionArgumentClause>,
8471}
8472
8473impl fmt::Display for FunctionArgumentList {
8474    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8475        if let Some(duplicate_treatment) = self.duplicate_treatment {
8476            write!(f, "{duplicate_treatment} ")?;
8477        }
8478        write!(f, "{}", display_comma_separated(&self.args))?;
8479        if !self.clauses.is_empty() {
8480            if !self.args.is_empty() {
8481                write!(f, " ")?;
8482            }
8483            write!(f, "{}", display_separated(&self.clauses, " "))?;
8484        }
8485        Ok(())
8486    }
8487}
8488
8489#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8490#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8491#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8492/// Clauses that can appear inside a function argument list.
8493pub enum FunctionArgumentClause {
8494    /// Indicates how `NULL`s should be handled in the calculation, e.g. in `FIRST_VALUE` on [BigQuery].
8495    ///
8496    /// Syntax:
8497    /// ```plaintext
8498    /// { IGNORE | RESPECT } NULLS ]
8499    /// ```
8500    ///
8501    /// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/navigation_functions#first_value
8502    IgnoreOrRespectNulls(NullTreatment),
8503    /// The inline `WHERE` filter clause on an aggregate call, e.g.
8504    /// `COUNT(* WHERE cond)` / `SUM(x WHERE cond)` / `ARRAY_AGG(x WHERE cond ORDER BY ..)`.
8505    /// Popularized by [GoogleSQL]; equivalent to the standard `AGG(x) FILTER (WHERE cond)`.
8506    /// Accepted for all dialects since `WHERE` cannot otherwise begin a function argument.
8507    ///
8508    /// [GoogleSQL]: https://cloud.google.com/bigquery/docs/reference/standard-sql/aggregate_functions#grouping_and_filtering
8509    Where(Expr),
8510    /// Specifies the the ordering for some ordered set aggregates, e.g. `ARRAY_AGG` on [BigQuery].
8511    ///
8512    /// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/aggregate_functions#array_agg
8513    OrderBy(Vec<OrderByExpr>),
8514    /// Specifies a limit for the `ARRAY_AGG` and `ARRAY_CONCAT_AGG` functions on BigQuery.
8515    Limit(Expr),
8516    /// Specifies the behavior on overflow of the `LISTAGG` function.
8517    ///
8518    /// See <https://trino.io/docs/current/functions/aggregate.html>.
8519    OnOverflow(ListAggOnOverflow),
8520    /// Specifies a minimum or maximum bound on the input to [`ANY_VALUE`] on BigQuery.
8521    ///
8522    /// Syntax:
8523    /// ```plaintext
8524    /// HAVING { MAX | MIN } expression
8525    /// ```
8526    ///
8527    /// [`ANY_VALUE`]: https://cloud.google.com/bigquery/docs/reference/standard-sql/aggregate_functions#any_value
8528    Having(HavingBound),
8529    /// The `SEPARATOR` clause to the [`GROUP_CONCAT`] function in MySQL.
8530    ///
8531    /// [`GROUP_CONCAT`]: https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat
8532    Separator(ValueWithSpan),
8533    /// The `ON NULL` clause for some JSON functions.
8534    ///
8535    /// [MSSQL `JSON_ARRAY`](https://learn.microsoft.com/en-us/sql/t-sql/functions/json-array-transact-sql?view=sql-server-ver16)
8536    /// [MSSQL `JSON_OBJECT`](https://learn.microsoft.com/en-us/sql/t-sql/functions/json-object-transact-sql?view=sql-server-ver16>)
8537    /// [PostgreSQL JSON functions](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING)
8538    JsonNullClause(JsonNullClause),
8539    /// The `RETURNING` clause for some JSON functions in PostgreSQL
8540    ///
8541    /// [`JSON_OBJECT`](https://www.postgresql.org/docs/current/functions-json.html#:~:text=json_object)
8542    JsonReturningClause(JsonReturningClause),
8543}
8544
8545impl fmt::Display for FunctionArgumentClause {
8546    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8547        match self {
8548            FunctionArgumentClause::IgnoreOrRespectNulls(null_treatment) => {
8549                write!(f, "{null_treatment}")
8550            }
8551            FunctionArgumentClause::Where(expr) => write!(f, "WHERE {expr}"),
8552            FunctionArgumentClause::OrderBy(order_by) => {
8553                write!(f, "ORDER BY {}", display_comma_separated(order_by))
8554            }
8555            FunctionArgumentClause::Limit(limit) => write!(f, "LIMIT {limit}"),
8556            FunctionArgumentClause::OnOverflow(on_overflow) => write!(f, "{on_overflow}"),
8557            FunctionArgumentClause::Having(bound) => write!(f, "{bound}"),
8558            FunctionArgumentClause::Separator(sep) => write!(f, "SEPARATOR {sep}"),
8559            FunctionArgumentClause::JsonNullClause(null_clause) => write!(f, "{null_clause}"),
8560            FunctionArgumentClause::JsonReturningClause(returning_clause) => {
8561                write!(f, "{returning_clause}")
8562            }
8563        }
8564    }
8565}
8566
8567/// A method call
8568#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8569#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8570#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8571pub struct Method {
8572    /// The expression on which the method is invoked.
8573    pub expr: Box<Expr>,
8574    // always non-empty
8575    /// The sequence of chained method calls.
8576    pub method_chain: Vec<Function>,
8577}
8578
8579impl fmt::Display for Method {
8580    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8581        write!(
8582            f,
8583            "{}.{}",
8584            self.expr,
8585            display_separated(&self.method_chain, ".")
8586        )
8587    }
8588}
8589
8590#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8591#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8592#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8593/// How duplicate values are treated inside function argument lists.
8594pub enum DuplicateTreatment {
8595    /// Consider only unique values.
8596    Distinct,
8597    /// Retain all duplicate values (the default).
8598    All,
8599}
8600
8601impl fmt::Display for DuplicateTreatment {
8602    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8603        match self {
8604            DuplicateTreatment::Distinct => write!(f, "DISTINCT"),
8605            DuplicateTreatment::All => write!(f, "ALL"),
8606        }
8607    }
8608}
8609
8610#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8611#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8612#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8613/// How the `ANALYZE`/`EXPLAIN ANALYZE` format is specified.
8614pub enum AnalyzeFormatKind {
8615    /// Format provided as a keyword, e.g. `FORMAT JSON`.
8616    Keyword(AnalyzeFormat),
8617    /// Format provided as an assignment, e.g. `FORMAT=JSON`.
8618    Assignment(AnalyzeFormat),
8619}
8620
8621impl fmt::Display for AnalyzeFormatKind {
8622    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
8623        match self {
8624            AnalyzeFormatKind::Keyword(format) => write!(f, "FORMAT {format}"),
8625            AnalyzeFormatKind::Assignment(format) => write!(f, "FORMAT={format}"),
8626        }
8627    }
8628}
8629
8630#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8631#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8632#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8633/// Output formats supported for `ANALYZE`/`EXPLAIN ANALYZE`.
8634pub enum AnalyzeFormat {
8635    /// Plain text format.
8636    TEXT,
8637    /// Graphviz DOT format.
8638    GRAPHVIZ,
8639    /// JSON format.
8640    JSON,
8641    /// Traditional explain output.
8642    TRADITIONAL,
8643    /// Tree-style explain output.
8644    TREE,
8645}
8646
8647/// Optional type constraint for `IS JSON`.
8648#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
8649#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8650#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8651pub enum JsonPredicateType {
8652    /// `VALUE` form.
8653    Value,
8654    /// `SCALAR` form.
8655    Scalar,
8656    /// `ARRAY` form.
8657    Array,
8658    /// `OBJECT` form.
8659    Object,
8660}
8661
8662impl fmt::Display for JsonPredicateType {
8663    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8664        match self {
8665            JsonPredicateType::Value => write!(f, "VALUE"),
8666            JsonPredicateType::Scalar => write!(f, "SCALAR"),
8667            JsonPredicateType::Array => write!(f, "ARRAY"),
8668            JsonPredicateType::Object => write!(f, "OBJECT"),
8669        }
8670    }
8671}
8672
8673/// Optional duplicate-key handling for `IS JSON`.
8674#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
8675#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8676#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8677pub enum JsonKeyUniqueness {
8678    /// `WITH UNIQUE KEYS` form.
8679    WithUniqueKeys,
8680    /// `WITHOUT UNIQUE KEYS` form.
8681    WithoutUniqueKeys,
8682}
8683
8684impl fmt::Display for JsonKeyUniqueness {
8685    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8686        match self {
8687            JsonKeyUniqueness::WithUniqueKeys => write!(f, "WITH UNIQUE KEYS"),
8688            JsonKeyUniqueness::WithoutUniqueKeys => write!(f, "WITHOUT UNIQUE KEYS"),
8689        }
8690    }
8691}
8692
8693impl fmt::Display for AnalyzeFormat {
8694    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
8695        f.write_str(match self {
8696            AnalyzeFormat::TEXT => "TEXT",
8697            AnalyzeFormat::GRAPHVIZ => "GRAPHVIZ",
8698            AnalyzeFormat::JSON => "JSON",
8699            AnalyzeFormat::TRADITIONAL => "TRADITIONAL",
8700            AnalyzeFormat::TREE => "TREE",
8701        })
8702    }
8703}
8704
8705/// External table's available file format
8706#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8707#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8708#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8709pub enum FileFormat {
8710    /// Text file format.
8711    TEXTFILE,
8712    /// Sequence file format.
8713    SEQUENCEFILE,
8714    /// ORC file format.
8715    ORC,
8716    /// Parquet file format.
8717    PARQUET,
8718    /// Avro file format.
8719    AVRO,
8720    /// RCFile format.
8721    RCFILE,
8722    /// JSON file format.
8723    JSONFILE,
8724}
8725
8726impl fmt::Display for FileFormat {
8727    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8728        use self::FileFormat::*;
8729        f.write_str(match self {
8730            TEXTFILE => "TEXTFILE",
8731            SEQUENCEFILE => "SEQUENCEFILE",
8732            ORC => "ORC",
8733            PARQUET => "PARQUET",
8734            AVRO => "AVRO",
8735            RCFILE => "RCFILE",
8736            JSONFILE => "JSONFILE",
8737        })
8738    }
8739}
8740
8741/// The `ON OVERFLOW` clause of a LISTAGG invocation
8742#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8743#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8744#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8745pub enum ListAggOnOverflow {
8746    /// `ON OVERFLOW ERROR`
8747    Error,
8748
8749    /// `ON OVERFLOW TRUNCATE [ <filler> ] WITH[OUT] COUNT`
8750    Truncate {
8751        /// Optional filler expression used when truncating.
8752        filler: Option<Box<Expr>>,
8753        /// Whether to include a count when truncating.
8754        with_count: bool,
8755    },
8756}
8757
8758impl fmt::Display for ListAggOnOverflow {
8759    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8760        write!(f, "ON OVERFLOW")?;
8761        match self {
8762            ListAggOnOverflow::Error => write!(f, " ERROR"),
8763            ListAggOnOverflow::Truncate { filler, with_count } => {
8764                write!(f, " TRUNCATE")?;
8765                if let Some(filler) = filler {
8766                    write!(f, " {filler}")?;
8767                }
8768                if *with_count {
8769                    write!(f, " WITH")?;
8770                } else {
8771                    write!(f, " WITHOUT")?;
8772                }
8773                write!(f, " COUNT")
8774            }
8775        }
8776    }
8777}
8778
8779/// The `HAVING` clause in a call to `ANY_VALUE` on BigQuery.
8780#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8781#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8782#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8783pub struct HavingBound(pub HavingBoundKind, pub Expr);
8784
8785impl fmt::Display for HavingBound {
8786    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8787        write!(f, "HAVING {} {}", self.0, self.1)
8788    }
8789}
8790
8791#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8792#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8793#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8794/// Which bound is used in a HAVING clause for ANY_VALUE on BigQuery.
8795pub enum HavingBoundKind {
8796    /// The minimum bound.
8797    Min,
8798    /// The maximum bound.
8799    Max,
8800}
8801
8802impl fmt::Display for HavingBoundKind {
8803    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8804        match self {
8805            HavingBoundKind::Min => write!(f, "MIN"),
8806            HavingBoundKind::Max => write!(f, "MAX"),
8807        }
8808    }
8809}
8810
8811#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8812#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8813#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8814/// Types of database objects referenced by DDL statements.
8815pub enum ObjectType {
8816    /// A collation.
8817    Collation,
8818    /// A table.
8819    Table,
8820    /// A foreign table.
8821    ForeignTable,
8822    /// A view.
8823    View,
8824    /// A materialized view.
8825    MaterializedView,
8826    /// An index.
8827    Index,
8828    /// A schema.
8829    Schema,
8830    /// A database.
8831    Database,
8832    /// A role.
8833    Role,
8834    /// A user group.
8835    Group,
8836    /// A sequence.
8837    Sequence,
8838    /// A stage.
8839    Stage,
8840    /// A type definition.
8841    Type,
8842    /// A user.
8843    User,
8844    /// A stream.
8845    Stream,
8846    /// A warehouse.
8847    Warehouse,
8848}
8849
8850impl fmt::Display for ObjectType {
8851    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8852        f.write_str(match self {
8853            ObjectType::Collation => "COLLATION",
8854            ObjectType::Table => "TABLE",
8855            ObjectType::ForeignTable => "FOREIGN TABLE",
8856            ObjectType::View => "VIEW",
8857            ObjectType::MaterializedView => "MATERIALIZED VIEW",
8858            ObjectType::Index => "INDEX",
8859            ObjectType::Schema => "SCHEMA",
8860            ObjectType::Database => "DATABASE",
8861            ObjectType::Role => "ROLE",
8862            ObjectType::Group => "GROUP",
8863            ObjectType::Sequence => "SEQUENCE",
8864            ObjectType::Stage => "STAGE",
8865            ObjectType::Type => "TYPE",
8866            ObjectType::User => "USER",
8867            ObjectType::Stream => "STREAM",
8868            ObjectType::Warehouse => "WAREHOUSE",
8869        })
8870    }
8871}
8872
8873#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8874#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8875#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8876/// Types supported by `KILL` statements.
8877pub enum KillType {
8878    /// Kill a connection.
8879    Connection,
8880    /// Kill a running query.
8881    Query,
8882    /// Kill a mutation (ClickHouse).
8883    Mutation,
8884}
8885
8886impl fmt::Display for KillType {
8887    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8888        f.write_str(match self {
8889            // MySQL
8890            KillType::Connection => "CONNECTION",
8891            KillType::Query => "QUERY",
8892            // Clickhouse supports Mutation
8893            KillType::Mutation => "MUTATION",
8894        })
8895    }
8896}
8897
8898#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8899#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8900#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8901/// Distribution style options for Hive tables.
8902pub enum HiveDistributionStyle {
8903    /// Partitioned distribution with the given columns.
8904    PARTITIONED {
8905        /// Columns used for partitioning.
8906        columns: Vec<ColumnDef>,
8907    },
8908    /// Skewed distribution definition.
8909    SKEWED {
8910        /// Columns participating in the skew definition.
8911        columns: Vec<ColumnDef>,
8912        /// Columns listed in the `ON` clause for skewing.
8913        on: Vec<ColumnDef>,
8914        /// Whether skewed data is stored as directories.
8915        stored_as_directories: bool,
8916    },
8917    /// No distribution style specified.
8918    NONE,
8919}
8920
8921#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8922#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8923#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8924/// Row format specification for Hive tables (SERDE or DELIMITED).
8925pub enum HiveRowFormat {
8926    /// SerDe class specification with the implementing class name.
8927    SERDE {
8928        /// The SerDe implementation class name.
8929        class: String,
8930    },
8931    /// Delimited row format with one or more delimiter specifications.
8932    DELIMITED {
8933        /// The list of delimiters used for delimiting fields/lines.
8934        delimiters: Vec<HiveRowDelimiter>,
8935    },
8936}
8937
8938#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8939#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8940#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8941/// Format specification for `LOAD DATA` Hive operations.
8942pub struct HiveLoadDataFormat {
8943    /// SerDe expression used for the table.
8944    pub serde: Expr,
8945    /// Input format expression.
8946    pub input_format: Expr,
8947}
8948
8949#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8950#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8951#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8952/// A single row delimiter specification for Hive `ROW FORMAT`.
8953pub struct HiveRowDelimiter {
8954    /// The delimiter kind (fields/lines/etc.).
8955    pub delimiter: HiveDelimiter,
8956    /// The delimiter character identifier.
8957    pub char: Ident,
8958}
8959
8960impl fmt::Display for HiveRowDelimiter {
8961    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8962        write!(f, "{} ", self.delimiter)?;
8963        write!(f, "{}", self.char)
8964    }
8965}
8966
8967#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8968#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8969#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8970/// Kind of delimiter used in Hive `ROW FORMAT` definitions.
8971pub enum HiveDelimiter {
8972    /// Fields terminated by a delimiter.
8973    FieldsTerminatedBy,
8974    /// Fields escaped by a character.
8975    FieldsEscapedBy,
8976    /// Collection items terminated by a delimiter.
8977    CollectionItemsTerminatedBy,
8978    /// Map keys terminated by a delimiter.
8979    MapKeysTerminatedBy,
8980    /// Lines terminated by a delimiter.
8981    LinesTerminatedBy,
8982    /// Null represented by a specific token.
8983    NullDefinedAs,
8984}
8985
8986impl fmt::Display for HiveDelimiter {
8987    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8988        use HiveDelimiter::*;
8989        f.write_str(match self {
8990            FieldsTerminatedBy => "FIELDS TERMINATED BY",
8991            FieldsEscapedBy => "ESCAPED BY",
8992            CollectionItemsTerminatedBy => "COLLECTION ITEMS TERMINATED BY",
8993            MapKeysTerminatedBy => "MAP KEYS TERMINATED BY",
8994            LinesTerminatedBy => "LINES TERMINATED BY",
8995            NullDefinedAs => "NULL DEFINED AS",
8996        })
8997    }
8998}
8999
9000#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9001#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9002#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9003/// Describe output format options for Hive `DESCRIBE`/`EXPLAIN`.
9004pub enum HiveDescribeFormat {
9005    /// Extended describe output.
9006    Extended,
9007    /// Formatted describe output.
9008    Formatted,
9009}
9010
9011impl fmt::Display for HiveDescribeFormat {
9012    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9013        use HiveDescribeFormat::*;
9014        f.write_str(match self {
9015            Extended => "EXTENDED",
9016            Formatted => "FORMATTED",
9017        })
9018    }
9019}
9020
9021#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9022#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9023#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9024/// Aliases accepted for describe-style commands.
9025pub enum DescribeAlias {
9026    /// `DESCRIBE` alias.
9027    Describe,
9028    /// `EXPLAIN` alias.
9029    Explain,
9030    /// `DESC` alias.
9031    Desc,
9032}
9033
9034impl fmt::Display for DescribeAlias {
9035    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9036        use DescribeAlias::*;
9037        f.write_str(match self {
9038            Describe => "DESCRIBE",
9039            Explain => "EXPLAIN",
9040            Desc => "DESC",
9041        })
9042    }
9043}
9044
9045#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9046#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9047#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9048/// Hive input/output format specification used in `CREATE TABLE`.
9049pub enum HiveIOFormat {
9050    /// Generic IO format with separate input and output expressions.
9051    IOF {
9052        /// Expression for the input format.
9053        input_format: Expr,
9054        /// Expression for the output format.
9055        output_format: Expr,
9056    },
9057    /// File format wrapper referencing a `FileFormat` variant.
9058    FileFormat {
9059        /// The file format used for storage.
9060        format: FileFormat,
9061    },
9062    /// `USING <format>` syntax used by Spark SQL.
9063    ///
9064    /// Example: `CREATE TABLE t (i INT) USING PARQUET`
9065    ///
9066    /// See <https://spark.apache.org/docs/latest/sql-ref-syntax-ddl-create-table-datasource.html>
9067    Using {
9068        /// The data source or format name, e.g. `parquet`, `delta`, `csv`.
9069        format: Ident,
9070    },
9071}
9072
9073#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Default)]
9074#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9075#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9076/// Hive table format and storage-related options.
9077pub struct HiveFormat {
9078    /// Optional row format specification.
9079    pub row_format: Option<HiveRowFormat>,
9080    /// Optional SerDe properties expressed as SQL options.
9081    pub serde_properties: Option<Vec<SqlOption>>,
9082    /// Optional input/output storage format details.
9083    pub storage: Option<HiveIOFormat>,
9084    /// Optional location (URI or path) for table data.
9085    pub location: Option<String>,
9086}
9087
9088#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9089#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9090#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9091/// A clustered index column specification.
9092pub struct ClusteredIndex {
9093    /// Column identifier for the clustered index entry.
9094    pub name: Ident,
9095    /// Optional sort direction: `Some(true)` for ASC, `Some(false)` for DESC, `None` for unspecified.
9096    pub asc: Option<bool>,
9097}
9098
9099impl fmt::Display for ClusteredIndex {
9100    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9101        write!(f, "{}", self.name)?;
9102        match self.asc {
9103            Some(true) => write!(f, " ASC"),
9104            Some(false) => write!(f, " DESC"),
9105            _ => Ok(()),
9106        }
9107    }
9108}
9109
9110#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9111#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9112#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9113/// Clustered options used for `CREATE TABLE` clustered/indexed storage.
9114pub enum TableOptionsClustered {
9115    /// Use a columnstore index.
9116    ColumnstoreIndex,
9117    /// Columnstore index with an explicit ordering of columns.
9118    ColumnstoreIndexOrder(Vec<Ident>),
9119    /// A named clustered index with one or more columns.
9120    Index(Vec<ClusteredIndex>),
9121}
9122
9123impl fmt::Display for TableOptionsClustered {
9124    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9125        match self {
9126            TableOptionsClustered::ColumnstoreIndex => {
9127                write!(f, "CLUSTERED COLUMNSTORE INDEX")
9128            }
9129            TableOptionsClustered::ColumnstoreIndexOrder(values) => {
9130                write!(
9131                    f,
9132                    "CLUSTERED COLUMNSTORE INDEX ORDER ({})",
9133                    display_comma_separated(values)
9134                )
9135            }
9136            TableOptionsClustered::Index(values) => {
9137                write!(f, "CLUSTERED INDEX ({})", display_comma_separated(values))
9138            }
9139        }
9140    }
9141}
9142
9143/// Specifies which partition the boundary values on table partitioning belongs to.
9144#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
9145#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9146#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9147pub enum PartitionRangeDirection {
9148    /// LEFT range direction.
9149    Left,
9150    /// RIGHT range direction.
9151    Right,
9152}
9153
9154#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9155#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9156#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9157/// SQL option syntax used in table and server definitions.
9158pub enum SqlOption {
9159    /// Clustered represents the clustered version of table storage for MSSQL.
9160    ///
9161    /// <https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-azure-sql-data-warehouse?view=aps-pdw-2016-au7#TableOptions>
9162    Clustered(TableOptionsClustered),
9163    /// Option name without a value, e.g. `HEAP` for MSSQL or a PostgreSQL storage
9164    /// parameter. The name may be namespaced, e.g. `toast.autovacuum_enabled`.
9165    ///
9166    /// <https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-azure-sql-data-warehouse?view=aps-pdw-2016-au7#TableOptions>
9167    Ident(ObjectName),
9168    /// Any option that consists of a key value pair where the value is an expression. e.g.
9169    ///
9170    ///   WITH(DISTRIBUTION = ROUND_ROBIN)
9171    ///   WITH (toast.autovacuum_enabled = false)
9172    KeyValue {
9173        /// The option key.
9174        key: ObjectName,
9175        /// The expression value for the option.
9176        value: Expr,
9177    },
9178    /// One or more table partitions and represents which partition the boundary values belong to,
9179    /// e.g.
9180    ///
9181    ///   PARTITION (id RANGE LEFT FOR VALUES (10, 20, 30, 40))
9182    ///
9183    /// <https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-azure-sql-data-warehouse?view=aps-pdw-2016-au7#TablePartitionOptions>
9184    Partition {
9185        /// The partition column name.
9186        column_name: Ident,
9187        /// Optional direction for the partition range (LEFT/RIGHT).
9188        range_direction: Option<PartitionRangeDirection>,
9189        /// Values that define the partition boundaries.
9190        for_values: Vec<Expr>,
9191    },
9192    /// Comment parameter (supports `=` and no `=` syntax)
9193    Comment(CommentDef),
9194    /// MySQL TableSpace option
9195    /// <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
9196    TableSpace(TablespaceOption),
9197    /// An option representing a key value pair, where the value is a parenthesized list and with an optional name
9198    /// e.g.
9199    ///
9200    ///   UNION  = (tbl_name\[,tbl_name\]...) <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
9201    ///   ENGINE = ReplicatedMergeTree('/table_name','{replica}', ver) <https://clickhouse.com/docs/engines/table-engines/mergetree-family/replication>
9202    ///   ENGINE = SummingMergeTree(\[columns\]) <https://clickhouse.com/docs/engines/table-engines/mergetree-family/summingmergetree>
9203    NamedParenthesizedList(NamedParenthesizedList),
9204}
9205
9206impl fmt::Display for SqlOption {
9207    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9208        match self {
9209            SqlOption::Clustered(c) => write!(f, "{c}"),
9210            SqlOption::Ident(ident) => {
9211                write!(f, "{ident}")
9212            }
9213            SqlOption::KeyValue { key: name, value } => {
9214                write!(f, "{name} = {value}")
9215            }
9216            SqlOption::Partition {
9217                column_name,
9218                range_direction,
9219                for_values,
9220            } => {
9221                let direction = match range_direction {
9222                    Some(PartitionRangeDirection::Left) => " LEFT",
9223                    Some(PartitionRangeDirection::Right) => " RIGHT",
9224                    None => "",
9225                };
9226
9227                write!(
9228                    f,
9229                    "PARTITION ({} RANGE{} FOR VALUES ({}))",
9230                    column_name,
9231                    direction,
9232                    display_comma_separated(for_values)
9233                )
9234            }
9235            SqlOption::TableSpace(tablespace_option) => {
9236                write!(f, "TABLESPACE {}", tablespace_option.name)?;
9237                match tablespace_option.storage {
9238                    Some(StorageType::Disk) => write!(f, " STORAGE DISK"),
9239                    Some(StorageType::Memory) => write!(f, " STORAGE MEMORY"),
9240                    None => Ok(()),
9241                }
9242            }
9243            SqlOption::Comment(comment) => match comment {
9244                CommentDef::WithEq(comment) => {
9245                    write!(f, "COMMENT = '{comment}'")
9246                }
9247                CommentDef::WithoutEq(comment) => {
9248                    write!(f, "COMMENT '{comment}'")
9249                }
9250            },
9251            SqlOption::NamedParenthesizedList(value) => {
9252                write!(f, "{} = ", value.key)?;
9253                if let Some(key) = &value.name {
9254                    write!(f, "{key}")?;
9255                }
9256                if !value.values.is_empty() {
9257                    write!(f, "({})", display_comma_separated(&value.values))?
9258                }
9259                Ok(())
9260            }
9261        }
9262    }
9263}
9264
9265#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
9266#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9267#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9268/// Storage type options for a tablespace.
9269pub enum StorageType {
9270    /// Store on disk.
9271    Disk,
9272    /// Store in memory.
9273    Memory,
9274}
9275
9276#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
9277#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9278#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9279/// MySql TableSpace option
9280/// <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
9281pub struct TablespaceOption {
9282    /// Name of the tablespace.
9283    pub name: String,
9284    /// Optional storage type for the tablespace.
9285    pub storage: Option<StorageType>,
9286}
9287
9288#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9289#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9290#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9291/// A key/value identifier pair used for secret or key-based options.
9292pub struct SecretOption {
9293    /// The option key identifier.
9294    pub key: Ident,
9295    /// The option value identifier.
9296    pub value: Ident,
9297}
9298
9299impl fmt::Display for SecretOption {
9300    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9301        write!(f, "{} {}", self.key, self.value)
9302    }
9303}
9304
9305/// A `CREATE SERVER` statement.
9306///
9307/// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-createserver.html)
9308#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9309#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9310#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9311pub struct CreateServerStatement {
9312    /// The server name.
9313    pub name: ObjectName,
9314    /// Whether `IF NOT EXISTS` was specified.
9315    pub if_not_exists: bool,
9316    /// Optional server type identifier.
9317    pub server_type: Option<Ident>,
9318    /// Optional server version identifier.
9319    pub version: Option<Ident>,
9320    /// Foreign-data wrapper object name.
9321    pub foreign_data_wrapper: ObjectName,
9322    /// Optional list of server options.
9323    pub options: Option<Vec<CreateServerOption>>,
9324}
9325
9326impl fmt::Display for CreateServerStatement {
9327    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9328        let CreateServerStatement {
9329            name,
9330            if_not_exists,
9331            server_type,
9332            version,
9333            foreign_data_wrapper,
9334            options,
9335        } = self;
9336
9337        write!(
9338            f,
9339            "CREATE SERVER {if_not_exists}{name} ",
9340            if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
9341        )?;
9342
9343        if let Some(st) = server_type {
9344            write!(f, "TYPE {st} ")?;
9345        }
9346
9347        if let Some(v) = version {
9348            write!(f, "VERSION {v} ")?;
9349        }
9350
9351        write!(f, "FOREIGN DATA WRAPPER {foreign_data_wrapper}")?;
9352
9353        if let Some(o) = options {
9354            write!(f, " OPTIONS ({o})", o = display_comma_separated(o))?;
9355        }
9356
9357        Ok(())
9358    }
9359}
9360
9361/// A key/value entry in a Postgres `OPTIONS ( ... )` clause.
9362#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9363#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9364#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9365pub struct CreateServerOption {
9366    /// Option key identifier.
9367    pub key: Ident,
9368    /// Option value identifier.
9369    pub value: Ident,
9370}
9371
9372impl fmt::Display for CreateServerOption {
9373    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9374        write!(f, "{} {}", self.key, self.value)
9375    }
9376}
9377
9378#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9379#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9380#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9381/// Options supported by DuckDB for `ATTACH DATABASE`.
9382pub enum AttachDuckDBDatabaseOption {
9383    /// READ_ONLY option, optional boolean value.
9384    ReadOnly(Option<bool>),
9385    /// TYPE option specifying a database type identifier.
9386    Type(Ident),
9387}
9388
9389impl fmt::Display for AttachDuckDBDatabaseOption {
9390    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9391        match self {
9392            AttachDuckDBDatabaseOption::ReadOnly(Some(true)) => write!(f, "READ_ONLY true"),
9393            AttachDuckDBDatabaseOption::ReadOnly(Some(false)) => write!(f, "READ_ONLY false"),
9394            AttachDuckDBDatabaseOption::ReadOnly(None) => write!(f, "READ_ONLY"),
9395            AttachDuckDBDatabaseOption::Type(t) => write!(f, "TYPE {t}"),
9396        }
9397    }
9398}
9399
9400#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9401#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9402#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9403/// Mode for transactions: access mode or isolation level.
9404pub enum TransactionMode {
9405    /// Access mode for a transaction (e.g. `READ ONLY` / `READ WRITE`).
9406    AccessMode(TransactionAccessMode),
9407    /// Isolation level for a transaction (e.g. `SERIALIZABLE`).
9408    IsolationLevel(TransactionIsolationLevel),
9409}
9410
9411impl fmt::Display for TransactionMode {
9412    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9413        use TransactionMode::*;
9414        match self {
9415            AccessMode(access_mode) => write!(f, "{access_mode}"),
9416            IsolationLevel(iso_level) => write!(f, "ISOLATION LEVEL {iso_level}"),
9417        }
9418    }
9419}
9420
9421#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9422#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9423#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9424/// Transaction access mode (READ ONLY / READ WRITE).
9425pub enum TransactionAccessMode {
9426    /// READ ONLY access mode.
9427    ReadOnly,
9428    /// READ WRITE access mode.
9429    ReadWrite,
9430}
9431
9432impl fmt::Display for TransactionAccessMode {
9433    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9434        use TransactionAccessMode::*;
9435        f.write_str(match self {
9436            ReadOnly => "READ ONLY",
9437            ReadWrite => "READ WRITE",
9438        })
9439    }
9440}
9441
9442#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9443#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9444#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9445/// Transaction isolation levels.
9446pub enum TransactionIsolationLevel {
9447    /// READ UNCOMMITTED isolation level.
9448    ReadUncommitted,
9449    /// READ COMMITTED isolation level.
9450    ReadCommitted,
9451    /// REPEATABLE READ isolation level.
9452    RepeatableRead,
9453    /// SERIALIZABLE isolation level.
9454    Serializable,
9455    /// SNAPSHOT isolation level.
9456    Snapshot,
9457}
9458
9459impl fmt::Display for TransactionIsolationLevel {
9460    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9461        use TransactionIsolationLevel::*;
9462        f.write_str(match self {
9463            ReadUncommitted => "READ UNCOMMITTED",
9464            ReadCommitted => "READ COMMITTED",
9465            RepeatableRead => "REPEATABLE READ",
9466            Serializable => "SERIALIZABLE",
9467            Snapshot => "SNAPSHOT",
9468        })
9469    }
9470}
9471
9472/// Modifier for the transaction in the `BEGIN` syntax
9473///
9474/// SQLite: <https://sqlite.org/lang_transaction.html>
9475/// MS-SQL: <https://learn.microsoft.com/en-us/sql/t-sql/language-elements/try-catch-transact-sql>
9476#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9477#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9478#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9479pub enum TransactionModifier {
9480    /// DEFERRED transaction modifier.
9481    Deferred,
9482    /// IMMEDIATE transaction modifier.
9483    Immediate,
9484    /// EXCLUSIVE transaction modifier.
9485    Exclusive,
9486    /// TRY block modifier (MS-SQL style TRY/CATCH).
9487    Try,
9488    /// CATCH block modifier (MS-SQL style TRY/CATCH).
9489    Catch,
9490}
9491
9492impl fmt::Display for TransactionModifier {
9493    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9494        use TransactionModifier::*;
9495        f.write_str(match self {
9496            Deferred => "DEFERRED",
9497            Immediate => "IMMEDIATE",
9498            Exclusive => "EXCLUSIVE",
9499            Try => "TRY",
9500            Catch => "CATCH",
9501        })
9502    }
9503}
9504
9505#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9506#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9507#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9508/// Filter forms usable in SHOW statements.
9509pub enum ShowStatementFilter {
9510    /// Filter using LIKE pattern.
9511    Like(String),
9512    /// Filter using ILIKE pattern.
9513    ILike(String),
9514    /// Filter using a WHERE expression.
9515    Where(Expr),
9516    /// Filter provided without a keyword (raw string).
9517    NoKeyword(String),
9518}
9519
9520impl fmt::Display for ShowStatementFilter {
9521    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9522        use ShowStatementFilter::*;
9523        match self {
9524            Like(pattern) => write!(f, "LIKE '{}'", value::escape_single_quote_string(pattern)),
9525            ILike(pattern) => write!(f, "ILIKE {}", value::escape_single_quote_string(pattern)),
9526            Where(expr) => write!(f, "WHERE {expr}"),
9527            NoKeyword(pattern) => write!(f, "'{}'", value::escape_single_quote_string(pattern)),
9528        }
9529    }
9530}
9531
9532#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9533#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9534#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9535/// Clause types used with SHOW ... IN/FROM.
9536pub enum ShowStatementInClause {
9537    /// Use the `IN` clause.
9538    IN,
9539    /// Use the `FROM` clause.
9540    FROM,
9541}
9542
9543impl fmt::Display for ShowStatementInClause {
9544    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9545        use ShowStatementInClause::*;
9546        match self {
9547            FROM => write!(f, "FROM"),
9548            IN => write!(f, "IN"),
9549        }
9550    }
9551}
9552
9553/// Sqlite specific syntax
9554///
9555/// See [Sqlite documentation](https://sqlite.org/lang_conflict.html)
9556/// for more details.
9557#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9558#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9559#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9560pub enum SqliteOnConflict {
9561    /// Use ROLLBACK on conflict.
9562    Rollback,
9563    /// Use ABORT on conflict.
9564    Abort,
9565    /// Use FAIL on conflict.
9566    Fail,
9567    /// Use IGNORE on conflict.
9568    Ignore,
9569    /// Use REPLACE on conflict.
9570    Replace,
9571}
9572
9573impl fmt::Display for SqliteOnConflict {
9574    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9575        use SqliteOnConflict::*;
9576        match self {
9577            Rollback => write!(f, "OR ROLLBACK"),
9578            Abort => write!(f, "OR ABORT"),
9579            Fail => write!(f, "OR FAIL"),
9580            Ignore => write!(f, "OR IGNORE"),
9581            Replace => write!(f, "OR REPLACE"),
9582        }
9583    }
9584}
9585
9586/// Mysql specific syntax
9587///
9588/// See [Mysql documentation](https://dev.mysql.com/doc/refman/8.0/en/replace.html)
9589/// See [Mysql documentation](https://dev.mysql.com/doc/refman/8.0/en/insert.html)
9590/// for more details.
9591#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9592#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9593#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9594pub enum MysqlInsertPriority {
9595    /// LOW_PRIORITY modifier for INSERT/REPLACE.
9596    LowPriority,
9597    /// DELAYED modifier for INSERT/REPLACE.
9598    Delayed,
9599    /// HIGH_PRIORITY modifier for INSERT/REPLACE.
9600    HighPriority,
9601}
9602
9603impl fmt::Display for crate::ast::MysqlInsertPriority {
9604    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9605        use MysqlInsertPriority::*;
9606        match self {
9607            LowPriority => write!(f, "LOW_PRIORITY"),
9608            Delayed => write!(f, "DELAYED"),
9609            HighPriority => write!(f, "HIGH_PRIORITY"),
9610        }
9611    }
9612}
9613
9614#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9615#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9616#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9617/// Source for the `COPY` command: a table or a query.
9618pub enum CopySource {
9619    /// Copy from a table with optional column list.
9620    Table {
9621        /// The name of the table to copy from.
9622        table_name: ObjectName,
9623        /// A list of column names to copy. Empty list means that all columns
9624        /// are copied.
9625        columns: Vec<Ident>,
9626    },
9627    /// Copy from the results of a query.
9628    Query(Box<Query>),
9629}
9630
9631#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9632#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9633#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9634/// Target for the `COPY` command: STDIN, STDOUT, a file, or a program.
9635pub enum CopyTarget {
9636    /// Use standard input as the source.
9637    Stdin,
9638    /// Use standard output as the target.
9639    Stdout,
9640    /// Read from or write to a file.
9641    File {
9642        /// The path name of the input or output file.
9643        filename: String,
9644    },
9645    /// Use a program as the source or target (shell command).
9646    Program {
9647        /// A command to execute
9648        command: String,
9649    },
9650}
9651
9652impl fmt::Display for CopyTarget {
9653    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9654        use CopyTarget::*;
9655        match self {
9656            Stdin => write!(f, "STDIN"),
9657            Stdout => write!(f, "STDOUT"),
9658            File { filename } => write!(f, "'{}'", value::escape_single_quote_string(filename)),
9659            Program { command } => write!(
9660                f,
9661                "PROGRAM '{}'",
9662                value::escape_single_quote_string(command)
9663            ),
9664        }
9665    }
9666}
9667
9668#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9669#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9670#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9671/// The inline payload of a `COPY ... FROM STDIN` statement, captured
9672/// verbatim from the source text.
9673pub struct CopyPayload {
9674    /// The payload as written, starting on the line after the command and
9675    /// running up to the `\.` terminator line. Field separators, escapes and
9676    /// the `\N` null marker are left for the caller to interpret.
9677    pub data: String,
9678    /// Whether the `\.` terminator line was present.
9679    pub terminated: bool,
9680}
9681
9682#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9683#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9684#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9685/// Action to take `ON COMMIT` for temporary tables.
9686pub enum OnCommit {
9687    /// Delete rows on commit.
9688    DeleteRows,
9689    /// Preserve rows on commit.
9690    PreserveRows,
9691    /// Drop the table on commit.
9692    Drop,
9693}
9694
9695/// An option in `COPY` statement.
9696///
9697/// <https://www.postgresql.org/docs/14/sql-copy.html>
9698#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9699#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9700#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9701pub enum CopyOption {
9702    /// FORMAT format_name
9703    Format(Ident),
9704    /// FREEZE \[ boolean \]
9705    Freeze(bool),
9706    /// DELIMITER 'delimiter_character'
9707    Delimiter(char),
9708    /// NULL 'null_string'
9709    Null(String),
9710    /// HEADER \[ boolean \]
9711    Header(bool),
9712    /// QUOTE 'quote_character'
9713    Quote(char),
9714    /// ESCAPE 'escape_character'
9715    Escape(char),
9716    /// FORCE_QUOTE { ( column_name [, ...] ) | * }
9717    ForceQuote(Vec<Ident>),
9718    /// FORCE_NOT_NULL ( column_name [, ...] )
9719    ForceNotNull(Vec<Ident>),
9720    /// FORCE_NULL ( column_name [, ...] )
9721    ForceNull(Vec<Ident>),
9722    /// ENCODING 'encoding_name'
9723    Encoding(String),
9724}
9725
9726impl fmt::Display for CopyOption {
9727    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9728        use CopyOption::*;
9729        match self {
9730            Format(name) => write!(f, "FORMAT {name}"),
9731            Freeze(true) => write!(f, "FREEZE"),
9732            Freeze(false) => write!(f, "FREEZE FALSE"),
9733            Delimiter(char) => write!(f, "DELIMITER '{char}'"),
9734            Null(string) => write!(f, "NULL '{}'", value::escape_single_quote_string(string)),
9735            Header(true) => write!(f, "HEADER"),
9736            Header(false) => write!(f, "HEADER FALSE"),
9737            Quote(char) => write!(f, "QUOTE '{char}'"),
9738            Escape(char) => write!(f, "ESCAPE '{char}'"),
9739            ForceQuote(columns) => write!(f, "FORCE_QUOTE ({})", display_comma_separated(columns)),
9740            ForceNotNull(columns) => {
9741                write!(f, "FORCE_NOT_NULL ({})", display_comma_separated(columns))
9742            }
9743            ForceNull(columns) => write!(f, "FORCE_NULL ({})", display_comma_separated(columns)),
9744            Encoding(name) => write!(f, "ENCODING '{}'", value::escape_single_quote_string(name)),
9745        }
9746    }
9747}
9748
9749/// An option in `COPY` statement before PostgreSQL version 9.0.
9750///
9751/// [PostgreSQL](https://www.postgresql.org/docs/8.4/sql-copy.html)
9752/// [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_COPY-alphabetical-parm-list.html)
9753#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9754#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9755#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9756pub enum CopyLegacyOption {
9757    /// ACCEPTANYDATE
9758    AcceptAnyDate,
9759    /// ACCEPTINVCHARS
9760    AcceptInvChars(Option<String>),
9761    /// ADDQUOTES
9762    AddQuotes,
9763    /// ALLOWOVERWRITE
9764    AllowOverwrite,
9765    /// BINARY
9766    Binary,
9767    /// BLANKSASNULL
9768    BlankAsNull,
9769    /// BZIP2
9770    Bzip2,
9771    /// CLEANPATH
9772    CleanPath,
9773    /// COMPUPDATE [ PRESET | { ON | TRUE } | { OFF | FALSE } ]
9774    CompUpdate {
9775        /// Whether the COMPUPDATE PRESET option was used.
9776        preset: bool,
9777        /// Optional enabled flag for COMPUPDATE.
9778        enabled: Option<bool>,
9779    },
9780    /// CSV ...
9781    Csv(Vec<CopyLegacyCsvOption>),
9782    /// DATEFORMAT \[ AS \] {'dateformat_string' | 'auto' }
9783    DateFormat(Option<String>),
9784    /// DELIMITER \[ AS \] 'delimiter_character'
9785    Delimiter(char),
9786    /// EMPTYASNULL
9787    EmptyAsNull,
9788    /// `ENCRYPTED \[ AUTO \]`
9789    Encrypted {
9790        /// Whether `AUTO` was specified for encryption.
9791        auto: bool,
9792    },
9793    /// ESCAPE
9794    Escape,
9795    /// EXTENSION 'extension-name'
9796    Extension(String),
9797    /// FIXEDWIDTH \[ AS \] 'fixedwidth-spec'
9798    FixedWidth(String),
9799    /// GZIP
9800    Gzip,
9801    /// HEADER
9802    Header,
9803    /// IAM_ROLE { DEFAULT | 'arn:aws:iam::123456789:role/role1' }
9804    IamRole(IamRoleKind),
9805    /// IGNOREHEADER \[ AS \] number_rows
9806    IgnoreHeader(u64),
9807    /// JSON \[ AS \] 'json_option'
9808    Json(Option<String>),
9809    /// MANIFEST \[ VERBOSE \]
9810    Manifest {
9811        /// Whether the MANIFEST is verbose.
9812        verbose: bool,
9813    },
9814    /// MAXFILESIZE \[ AS \] max-size \[ MB | GB \]
9815    MaxFileSize(FileSize),
9816    /// `NULL \[ AS \] 'null_string'`
9817    Null(String),
9818    /// `PARALLEL [ { ON | TRUE } | { OFF | FALSE } ]`
9819    Parallel(Option<bool>),
9820    /// PARQUET
9821    Parquet,
9822    /// PARTITION BY ( column_name [, ... ] ) \[ INCLUDE \]
9823    PartitionBy(UnloadPartitionBy),
9824    /// REGION \[ AS \] 'aws-region' }
9825    Region(String),
9826    /// REMOVEQUOTES
9827    RemoveQuotes,
9828    /// ROWGROUPSIZE \[ AS \] size \[ MB | GB \]
9829    RowGroupSize(FileSize),
9830    /// STATUPDATE [ { ON | TRUE } | { OFF | FALSE } ]
9831    StatUpdate(Option<bool>),
9832    /// TIMEFORMAT \[ AS \] {'timeformat_string' | 'auto' | 'epochsecs' | 'epochmillisecs' }
9833    TimeFormat(Option<String>),
9834    /// TRUNCATECOLUMNS
9835    TruncateColumns,
9836    /// ZSTD
9837    Zstd,
9838    /// Redshift `CREDENTIALS 'auth-args'`
9839    /// <https://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-authorization.html>
9840    Credentials(String),
9841}
9842
9843impl fmt::Display for CopyLegacyOption {
9844    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9845        use CopyLegacyOption::*;
9846        match self {
9847            AcceptAnyDate => write!(f, "ACCEPTANYDATE"),
9848            AcceptInvChars(ch) => {
9849                write!(f, "ACCEPTINVCHARS")?;
9850                if let Some(ch) = ch {
9851                    write!(f, " '{}'", value::escape_single_quote_string(ch))?;
9852                }
9853                Ok(())
9854            }
9855            AddQuotes => write!(f, "ADDQUOTES"),
9856            AllowOverwrite => write!(f, "ALLOWOVERWRITE"),
9857            Binary => write!(f, "BINARY"),
9858            BlankAsNull => write!(f, "BLANKSASNULL"),
9859            Bzip2 => write!(f, "BZIP2"),
9860            CleanPath => write!(f, "CLEANPATH"),
9861            CompUpdate { preset, enabled } => {
9862                write!(f, "COMPUPDATE")?;
9863                if *preset {
9864                    write!(f, " PRESET")?;
9865                } else if let Some(enabled) = enabled {
9866                    write!(
9867                        f,
9868                        "{}",
9869                        match enabled {
9870                            true => " TRUE",
9871                            false => " FALSE",
9872                        }
9873                    )?;
9874                }
9875                Ok(())
9876            }
9877            Csv(opts) => {
9878                write!(f, "CSV")?;
9879                if !opts.is_empty() {
9880                    write!(f, " {}", display_separated(opts, " "))?;
9881                }
9882                Ok(())
9883            }
9884            DateFormat(fmt) => {
9885                write!(f, "DATEFORMAT")?;
9886                if let Some(fmt) = fmt {
9887                    write!(f, " '{}'", value::escape_single_quote_string(fmt))?;
9888                }
9889                Ok(())
9890            }
9891            Delimiter(char) => write!(f, "DELIMITER '{char}'"),
9892            EmptyAsNull => write!(f, "EMPTYASNULL"),
9893            Encrypted { auto } => write!(f, "ENCRYPTED{}", if *auto { " AUTO" } else { "" }),
9894            Escape => write!(f, "ESCAPE"),
9895            Extension(ext) => write!(f, "EXTENSION '{}'", value::escape_single_quote_string(ext)),
9896            FixedWidth(spec) => write!(
9897                f,
9898                "FIXEDWIDTH '{}'",
9899                value::escape_single_quote_string(spec)
9900            ),
9901            Gzip => write!(f, "GZIP"),
9902            Header => write!(f, "HEADER"),
9903            IamRole(role) => write!(f, "IAM_ROLE {role}"),
9904            IgnoreHeader(num_rows) => write!(f, "IGNOREHEADER {num_rows}"),
9905            Json(opt) => {
9906                write!(f, "JSON")?;
9907                if let Some(opt) = opt {
9908                    write!(f, " AS '{}'", value::escape_single_quote_string(opt))?;
9909                }
9910                Ok(())
9911            }
9912            Manifest { verbose } => write!(f, "MANIFEST{}", if *verbose { " VERBOSE" } else { "" }),
9913            MaxFileSize(file_size) => write!(f, "MAXFILESIZE {file_size}"),
9914            Null(string) => write!(f, "NULL '{}'", value::escape_single_quote_string(string)),
9915            Parallel(enabled) => {
9916                write!(
9917                    f,
9918                    "PARALLEL{}",
9919                    match enabled {
9920                        Some(true) => " TRUE",
9921                        Some(false) => " FALSE",
9922                        _ => "",
9923                    }
9924                )
9925            }
9926            Parquet => write!(f, "PARQUET"),
9927            PartitionBy(p) => write!(f, "{p}"),
9928            Region(region) => write!(f, "REGION '{}'", value::escape_single_quote_string(region)),
9929            RemoveQuotes => write!(f, "REMOVEQUOTES"),
9930            RowGroupSize(file_size) => write!(f, "ROWGROUPSIZE {file_size}"),
9931            StatUpdate(enabled) => {
9932                write!(
9933                    f,
9934                    "STATUPDATE{}",
9935                    match enabled {
9936                        Some(true) => " TRUE",
9937                        Some(false) => " FALSE",
9938                        _ => "",
9939                    }
9940                )
9941            }
9942            TimeFormat(fmt) => {
9943                write!(f, "TIMEFORMAT")?;
9944                if let Some(fmt) = fmt {
9945                    write!(f, " '{}'", value::escape_single_quote_string(fmt))?;
9946                }
9947                Ok(())
9948            }
9949            TruncateColumns => write!(f, "TRUNCATECOLUMNS"),
9950            Zstd => write!(f, "ZSTD"),
9951            Credentials(s) => write!(f, "CREDENTIALS '{}'", value::escape_single_quote_string(s)),
9952        }
9953    }
9954}
9955
9956/// ```sql
9957/// SIZE \[ MB | GB \]
9958/// ```
9959#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9960#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9961#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9962pub struct FileSize {
9963    /// Numeric size value.
9964    pub size: ValueWithSpan,
9965    /// Optional unit for the size (MB or GB).
9966    pub unit: Option<FileSizeUnit>,
9967}
9968
9969impl fmt::Display for FileSize {
9970    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9971        write!(f, "{}", self.size)?;
9972        if let Some(unit) = &self.unit {
9973            write!(f, " {unit}")?;
9974        }
9975        Ok(())
9976    }
9977}
9978
9979/// Units for `FileSize` (MB or GB).
9980#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9981#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9982#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9983pub enum FileSizeUnit {
9984    /// Megabytes.
9985    MB,
9986    /// Gigabytes.
9987    GB,
9988}
9989
9990impl fmt::Display for FileSizeUnit {
9991    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9992        match self {
9993            FileSizeUnit::MB => write!(f, "MB"),
9994            FileSizeUnit::GB => write!(f, "GB"),
9995        }
9996    }
9997}
9998
9999/// Specifies the partition keys for the unload operation
10000///
10001/// ```sql
10002/// PARTITION BY ( column_name [, ... ] ) [ INCLUDE ]
10003/// ```
10004#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10005#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10006#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10007pub struct UnloadPartitionBy {
10008    /// Columns used to partition the unload output.
10009    pub columns: Vec<Ident>,
10010    /// Whether to include the partition in the output.
10011    pub include: bool,
10012}
10013
10014impl fmt::Display for UnloadPartitionBy {
10015    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10016        write!(
10017            f,
10018            "PARTITION BY ({}){}",
10019            display_comma_separated(&self.columns),
10020            if self.include { " INCLUDE" } else { "" }
10021        )
10022    }
10023}
10024
10025/// An `IAM_ROLE` option in the AWS ecosystem
10026///
10027/// [Redshift COPY](https://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-authorization.html#copy-iam-role)
10028#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10029#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10030#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10031pub enum IamRoleKind {
10032    /// Default role
10033    Default,
10034    /// Specific role ARN, for example: `arn:aws:iam::123456789:role/role1`
10035    Arn(String),
10036}
10037
10038impl fmt::Display for IamRoleKind {
10039    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10040        match self {
10041            IamRoleKind::Default => write!(f, "DEFAULT"),
10042            IamRoleKind::Arn(arn) => write!(f, "'{arn}'"),
10043        }
10044    }
10045}
10046
10047/// A `CSV` option in `COPY` statement before PostgreSQL version 9.0.
10048///
10049/// <https://www.postgresql.org/docs/8.4/sql-copy.html>
10050#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10051#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10052#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10053pub enum CopyLegacyCsvOption {
10054    /// HEADER
10055    Header,
10056    /// QUOTE \[ AS \] 'quote_character'
10057    Quote(char),
10058    /// ESCAPE \[ AS \] 'escape_character'
10059    Escape(char),
10060    /// FORCE QUOTE { column_name [, ...] | * }
10061    ForceQuote(Vec<Ident>),
10062    /// FORCE NOT NULL column_name [, ...]
10063    ForceNotNull(Vec<Ident>),
10064}
10065
10066impl fmt::Display for CopyLegacyCsvOption {
10067    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10068        use CopyLegacyCsvOption::*;
10069        match self {
10070            Header => write!(f, "HEADER"),
10071            Quote(char) => write!(f, "QUOTE '{char}'"),
10072            Escape(char) => write!(f, "ESCAPE '{char}'"),
10073            ForceQuote(columns) => write!(f, "FORCE QUOTE {}", display_comma_separated(columns)),
10074            ForceNotNull(columns) => {
10075                write!(f, "FORCE NOT NULL {}", display_comma_separated(columns))
10076            }
10077        }
10078    }
10079}
10080
10081/// Objects that can be discarded with `DISCARD`.
10082#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10083#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10084#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10085pub enum DiscardObject {
10086    /// Discard all session state.
10087    ALL,
10088    /// Discard cached plans.
10089    PLANS,
10090    /// Discard sequence values.
10091    SEQUENCES,
10092    /// Discard temporary objects.
10093    TEMP,
10094}
10095
10096impl fmt::Display for DiscardObject {
10097    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10098        match self {
10099            DiscardObject::ALL => f.write_str("ALL"),
10100            DiscardObject::PLANS => f.write_str("PLANS"),
10101            DiscardObject::SEQUENCES => f.write_str("SEQUENCES"),
10102            DiscardObject::TEMP => f.write_str("TEMP"),
10103        }
10104    }
10105}
10106
10107/// Types of flush operations supported by `FLUSH`.
10108#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10109#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10110#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10111pub enum FlushType {
10112    /// Flush binary logs.
10113    BinaryLogs,
10114    /// Flush engine logs.
10115    EngineLogs,
10116    /// Flush error logs.
10117    ErrorLogs,
10118    /// Flush general logs.
10119    GeneralLogs,
10120    /// Flush hosts information.
10121    Hosts,
10122    /// Flush logs.
10123    Logs,
10124    /// Flush privileges.
10125    Privileges,
10126    /// Flush optimizer costs.
10127    OptimizerCosts,
10128    /// Flush relay logs.
10129    RelayLogs,
10130    /// Flush slow logs.
10131    SlowLogs,
10132    /// Flush status.
10133    Status,
10134    /// Flush user resources.
10135    UserResources,
10136    /// Flush table data.
10137    Tables,
10138}
10139
10140impl fmt::Display for FlushType {
10141    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10142        match self {
10143            FlushType::BinaryLogs => f.write_str("BINARY LOGS"),
10144            FlushType::EngineLogs => f.write_str("ENGINE LOGS"),
10145            FlushType::ErrorLogs => f.write_str("ERROR LOGS"),
10146            FlushType::GeneralLogs => f.write_str("GENERAL LOGS"),
10147            FlushType::Hosts => f.write_str("HOSTS"),
10148            FlushType::Logs => f.write_str("LOGS"),
10149            FlushType::Privileges => f.write_str("PRIVILEGES"),
10150            FlushType::OptimizerCosts => f.write_str("OPTIMIZER_COSTS"),
10151            FlushType::RelayLogs => f.write_str("RELAY LOGS"),
10152            FlushType::SlowLogs => f.write_str("SLOW LOGS"),
10153            FlushType::Status => f.write_str("STATUS"),
10154            FlushType::UserResources => f.write_str("USER_RESOURCES"),
10155            FlushType::Tables => f.write_str("TABLES"),
10156        }
10157    }
10158}
10159
10160/// Location modifier for flush commands.
10161#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10162#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10163#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10164pub enum FlushLocation {
10165    /// Do not write changes to the binary log.
10166    NoWriteToBinlog,
10167    /// Apply flush locally.
10168    Local,
10169}
10170
10171impl fmt::Display for FlushLocation {
10172    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10173        match self {
10174            FlushLocation::NoWriteToBinlog => f.write_str("NO_WRITE_TO_BINLOG"),
10175            FlushLocation::Local => f.write_str("LOCAL"),
10176        }
10177    }
10178}
10179
10180/// Optional context modifier for statements that can be or `LOCAL`, `GLOBAL`, or `SESSION`.
10181#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10182#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10183#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10184pub enum ContextModifier {
10185    /// `LOCAL` identifier, usually related to transactional states.
10186    Local,
10187    /// `SESSION` identifier
10188    Session,
10189    /// `GLOBAL` identifier
10190    Global,
10191}
10192
10193impl fmt::Display for ContextModifier {
10194    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10195        match self {
10196            Self::Local => {
10197                write!(f, "LOCAL ")
10198            }
10199            Self::Session => {
10200                write!(f, "SESSION ")
10201            }
10202            Self::Global => {
10203                write!(f, "GLOBAL ")
10204            }
10205        }
10206    }
10207}
10208
10209/// Function describe in DROP FUNCTION.
10210#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10211#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10212pub enum DropFunctionOption {
10213    /// `RESTRICT` option for DROP FUNCTION.
10214    Restrict,
10215    /// `CASCADE` option for DROP FUNCTION.
10216    Cascade,
10217}
10218
10219impl fmt::Display for DropFunctionOption {
10220    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10221        match self {
10222            DropFunctionOption::Restrict => write!(f, "RESTRICT "),
10223            DropFunctionOption::Cascade => write!(f, "CASCADE  "),
10224        }
10225    }
10226}
10227
10228/// Generic function description for DROP FUNCTION and CREATE TRIGGER.
10229#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10230#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10231#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10232pub struct FunctionDesc {
10233    /// The function name.
10234    pub name: ObjectName,
10235    /// Optional list of function arguments.
10236    pub args: Option<Vec<OperateFunctionArg>>,
10237}
10238
10239impl fmt::Display for FunctionDesc {
10240    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10241        write!(f, "{}", self.name)?;
10242        if let Some(args) = &self.args {
10243            write!(f, "({})", display_comma_separated(args))?;
10244        }
10245        Ok(())
10246    }
10247}
10248
10249/// Function argument in CREATE OR DROP FUNCTION.
10250#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10251#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10252#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10253pub struct OperateFunctionArg {
10254    /// Optional argument mode (`IN`, `OUT`, `INOUT`).
10255    pub mode: Option<ArgMode>,
10256    /// Optional argument identifier/name.
10257    pub name: Option<Ident>,
10258    /// The data type of the argument.
10259    pub data_type: DataType,
10260    /// Optional default expression for the argument.
10261    pub default_expr: Option<Expr>,
10262}
10263
10264impl OperateFunctionArg {
10265    /// Returns an unnamed argument.
10266    pub fn unnamed(data_type: DataType) -> Self {
10267        Self {
10268            mode: None,
10269            name: None,
10270            data_type,
10271            default_expr: None,
10272        }
10273    }
10274
10275    /// Returns an argument with name.
10276    pub fn with_name(name: &str, data_type: DataType) -> Self {
10277        Self {
10278            mode: None,
10279            name: Some(name.into()),
10280            data_type,
10281            default_expr: None,
10282        }
10283    }
10284}
10285
10286impl fmt::Display for OperateFunctionArg {
10287    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10288        if let Some(mode) = &self.mode {
10289            write!(f, "{mode} ")?;
10290        }
10291        if let Some(name) = &self.name {
10292            write!(f, "{name} ")?;
10293        }
10294        write!(f, "{}", self.data_type)?;
10295        if let Some(default_expr) = &self.default_expr {
10296            write!(f, " = {default_expr}")?;
10297        }
10298        Ok(())
10299    }
10300}
10301
10302/// The mode of an argument in CREATE FUNCTION.
10303#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10304#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10305#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10306pub enum ArgMode {
10307    /// `IN` mode.
10308    In,
10309    /// `OUT` mode.
10310    Out,
10311    /// `INOUT` mode.
10312    InOut,
10313    /// `VARIADIC` mode.
10314    Variadic,
10315}
10316
10317impl fmt::Display for ArgMode {
10318    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10319        match self {
10320            ArgMode::In => write!(f, "IN"),
10321            ArgMode::Out => write!(f, "OUT"),
10322            ArgMode::InOut => write!(f, "INOUT"),
10323            ArgMode::Variadic => write!(f, "VARIADIC"),
10324        }
10325    }
10326}
10327
10328/// These attributes inform the query optimizer about the behavior of the function.
10329#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10330#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10331#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10332pub enum FunctionBehavior {
10333    /// Function is immutable.
10334    Immutable,
10335    /// Function is stable.
10336    Stable,
10337    /// Function is volatile.
10338    Volatile,
10339}
10340
10341impl fmt::Display for FunctionBehavior {
10342    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10343        match self {
10344            FunctionBehavior::Immutable => write!(f, "IMMUTABLE"),
10345            FunctionBehavior::Stable => write!(f, "STABLE"),
10346            FunctionBehavior::Volatile => write!(f, "VOLATILE"),
10347        }
10348    }
10349}
10350
10351/// Security attribute for functions: SECURITY DEFINER or SECURITY INVOKER.
10352///
10353/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
10354#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10355#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10356#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10357pub enum FunctionSecurity {
10358    /// Execute the function with the privileges of the user who defined it.
10359    Definer,
10360    /// Execute the function with the privileges of the user who invokes it.
10361    Invoker,
10362}
10363
10364impl fmt::Display for FunctionSecurity {
10365    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10366        match self {
10367            FunctionSecurity::Definer => write!(f, "SECURITY DEFINER"),
10368            FunctionSecurity::Invoker => write!(f, "SECURITY INVOKER"),
10369        }
10370    }
10371}
10372
10373/// Value for a SET configuration parameter in a CREATE FUNCTION statement.
10374///
10375/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
10376#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10377#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10378#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10379pub enum FunctionSetValue {
10380    /// SET param = DEFAULT / SET param TO DEFAULT
10381    Default,
10382    /// SET param = value1, value2, ...
10383    Values(Vec<Expr>),
10384    /// SET param FROM CURRENT
10385    FromCurrent,
10386}
10387
10388/// A SET configuration_parameter clause in a CREATE FUNCTION statement.
10389///
10390/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
10391#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10392#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10393#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10394pub struct FunctionDefinitionSetParam {
10395    /// The name of the configuration parameter.
10396    pub name: ObjectName,
10397    /// The value to set for the parameter.
10398    pub value: FunctionSetValue,
10399}
10400
10401impl fmt::Display for FunctionDefinitionSetParam {
10402    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10403        write!(f, "SET {} ", self.name)?;
10404        match &self.value {
10405            FunctionSetValue::Default => write!(f, "= DEFAULT"),
10406            FunctionSetValue::Values(values) => {
10407                write!(f, "= {}", display_comma_separated(values))
10408            }
10409            FunctionSetValue::FromCurrent => write!(f, "FROM CURRENT"),
10410        }
10411    }
10412}
10413
10414/// These attributes describe the behavior of the function when called with a null argument.
10415#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10416#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10417#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10418pub enum FunctionCalledOnNull {
10419    /// Function is called even when inputs are null.
10420    CalledOnNullInput,
10421    /// Function returns null when any input is null.
10422    ReturnsNullOnNullInput,
10423    /// Function is strict about null inputs.
10424    Strict,
10425}
10426
10427impl fmt::Display for FunctionCalledOnNull {
10428    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10429        match self {
10430            FunctionCalledOnNull::CalledOnNullInput => write!(f, "CALLED ON NULL INPUT"),
10431            FunctionCalledOnNull::ReturnsNullOnNullInput => write!(f, "RETURNS NULL ON NULL INPUT"),
10432            FunctionCalledOnNull::Strict => write!(f, "STRICT"),
10433        }
10434    }
10435}
10436
10437/// If it is safe for PostgreSQL to call the function from multiple threads at once
10438#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10439#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10440#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10441pub enum FunctionParallel {
10442    /// The function is not safe to run in parallel.
10443    Unsafe,
10444    /// The function is restricted for parallel execution.
10445    Restricted,
10446    /// The function is safe to run in parallel.
10447    Safe,
10448}
10449
10450impl FunctionParallel {
10451    /// Returns the bare keyword for this parallel mode, without the `PARALLEL` prefix.
10452    pub fn as_str(&self) -> &'static str {
10453        match self {
10454            FunctionParallel::Unsafe => "UNSAFE",
10455            FunctionParallel::Restricted => "RESTRICTED",
10456            FunctionParallel::Safe => "SAFE",
10457        }
10458    }
10459}
10460
10461impl fmt::Display for FunctionParallel {
10462    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10463        write!(f, "PARALLEL {}", self.as_str())
10464    }
10465}
10466
10467/// [BigQuery] Determinism specifier used in a UDF definition.
10468///
10469/// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#syntax_11
10470#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10471#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10472#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10473pub enum FunctionDeterminismSpecifier {
10474    /// Function is deterministic.
10475    Deterministic,
10476    /// Function is not deterministic.
10477    NotDeterministic,
10478}
10479
10480impl fmt::Display for FunctionDeterminismSpecifier {
10481    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10482        match self {
10483            FunctionDeterminismSpecifier::Deterministic => {
10484                write!(f, "DETERMINISTIC")
10485            }
10486            FunctionDeterminismSpecifier::NotDeterministic => {
10487                write!(f, "NOT DETERMINISTIC")
10488            }
10489        }
10490    }
10491}
10492
10493/// Represent the expression body of a `CREATE FUNCTION` statement as well as
10494/// where within the statement, the body shows up.
10495///
10496/// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#syntax_11
10497/// [PostgreSQL]: https://www.postgresql.org/docs/15/sql-createfunction.html
10498/// [MsSql]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql
10499#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10500#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10501#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10502pub enum CreateFunctionBody {
10503    /// A function body expression using the 'AS' keyword and shows up
10504    /// before any `OPTIONS` clause.
10505    ///
10506    /// Example:
10507    /// ```sql
10508    /// CREATE FUNCTION myfunc(x FLOAT64, y FLOAT64) RETURNS FLOAT64
10509    /// AS (x * y)
10510    /// OPTIONS(description="desc");
10511    /// ```
10512    ///
10513    /// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#syntax_11
10514    /// [PostgreSQL]: https://www.postgresql.org/docs/current/sql-createfunction.html
10515    AsBeforeOptions {
10516        /// The primary expression.
10517        body: Expr,
10518        /// Link symbol if the primary expression contains the name of shared library file.
10519        ///
10520        /// Example:
10521        /// ```sql
10522        /// CREATE FUNCTION cas_in(input cstring) RETURNS cas
10523        /// AS 'MODULE_PATHNAME', 'cas_in_wrapper'
10524        /// ```
10525        /// [PostgreSQL]: https://www.postgresql.org/docs/current/sql-createfunction.html
10526        link_symbol: Option<Expr>,
10527    },
10528    /// A function body expression using the 'AS' keyword and shows up
10529    /// after any `OPTIONS` clause.
10530    ///
10531    /// Example:
10532    /// ```sql
10533    /// CREATE FUNCTION myfunc(x FLOAT64, y FLOAT64) RETURNS FLOAT64
10534    /// OPTIONS(description="desc")
10535    /// AS (x * y);
10536    /// ```
10537    ///
10538    /// [BigQuery]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#syntax_11
10539    AsAfterOptions(Expr),
10540    /// Function body with statements before the `RETURN` keyword.
10541    ///
10542    /// Example:
10543    /// ```sql
10544    /// CREATE FUNCTION my_scalar_udf(a INT, b INT)
10545    /// RETURNS INT
10546    /// AS
10547    /// BEGIN
10548    ///     DECLARE c INT;
10549    ///     SET c = a + b;
10550    ///     RETURN c;
10551    /// END
10552    /// ```
10553    ///
10554    /// [MsSql]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql
10555    AsBeginEnd(BeginEndStatements),
10556    /// Function body expression using the 'RETURN' keyword.
10557    ///
10558    /// Example:
10559    /// ```sql
10560    /// CREATE FUNCTION myfunc(a INTEGER, IN b INTEGER = 1) RETURNS INTEGER
10561    /// LANGUAGE SQL
10562    /// RETURN a + b;
10563    /// ```
10564    ///
10565    /// [PostgreSQL]: https://www.postgresql.org/docs/current/sql-createfunction.html
10566    Return(Expr),
10567    /// SQL-standard function body enclosed by `BEGIN ATOMIC` and `END`.
10568    ///
10569    /// [PostgreSQL]: https://www.postgresql.org/docs/current/sql-createfunction.html
10570    BeginAtomic(BeginEndStatements),
10571
10572    /// Function body expression using the 'AS RETURN' keywords
10573    ///
10574    /// Example:
10575    /// ```sql
10576    /// CREATE FUNCTION myfunc(a INT, b INT)
10577    /// RETURNS TABLE
10578    /// AS RETURN (SELECT a + b AS sum);
10579    /// ```
10580    ///
10581    /// [MsSql]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql
10582    AsReturnExpr(Expr),
10583
10584    /// Function body expression using the 'AS RETURN' keywords, with an un-parenthesized SELECT query
10585    ///
10586    /// Example:
10587    /// ```sql
10588    /// CREATE FUNCTION myfunc(a INT, b INT)
10589    /// RETURNS TABLE
10590    /// AS RETURN SELECT a + b AS sum;
10591    /// ```
10592    ///
10593    /// [MsSql]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql?view=sql-server-ver16#select_stmt
10594    AsReturnSelect(Select),
10595}
10596
10597/// Body of a `CREATE PROCEDURE` statement.
10598#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10599#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10600#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10601pub enum CreateProcedureBody {
10602    /// Statements after `AS`.
10603    As(ConditionalStatements),
10604    /// SQL-standard body enclosed by `BEGIN ATOMIC` and `END`.
10605    ///
10606    /// [PostgreSQL]: https://www.postgresql.org/docs/current/sql-createprocedure.html
10607    BeginAtomic(BeginEndStatements),
10608}
10609
10610#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10611#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10612#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10613/// `USING` clause options for `CREATE FUNCTION` (e.g., JAR, FILE, ARCHIVE).
10614pub enum CreateFunctionUsing {
10615    /// Use a JAR file located at the given URI.
10616    Jar(String),
10617    /// Use a file located at the given URI.
10618    File(String),
10619    /// Use an archive located at the given URI.
10620    Archive(String),
10621}
10622
10623impl fmt::Display for CreateFunctionUsing {
10624    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10625        write!(f, "USING ")?;
10626        match self {
10627            CreateFunctionUsing::Jar(uri) => write!(f, "JAR '{uri}'"),
10628            CreateFunctionUsing::File(uri) => write!(f, "FILE '{uri}'"),
10629            CreateFunctionUsing::Archive(uri) => write!(f, "ARCHIVE '{uri}'"),
10630        }
10631    }
10632}
10633
10634/// `NAME = <EXPR>` arguments for DuckDB macros
10635///
10636/// See [Create Macro - DuckDB](https://duckdb.org/docs/sql/statements/create_macro)
10637/// for more details
10638#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10639#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10640#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10641pub struct MacroArg {
10642    /// The argument name.
10643    pub name: Ident,
10644    /// Optional default expression for the argument.
10645    pub default_expr: Option<Expr>,
10646}
10647
10648impl MacroArg {
10649    /// Returns an argument with name.
10650    pub fn new(name: &str) -> Self {
10651        Self {
10652            name: name.into(),
10653            default_expr: None,
10654        }
10655    }
10656}
10657
10658impl fmt::Display for MacroArg {
10659    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10660        write!(f, "{}", self.name)?;
10661        if let Some(default_expr) = &self.default_expr {
10662            write!(f, " := {default_expr}")?;
10663        }
10664        Ok(())
10665    }
10666}
10667
10668#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10669#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10670#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10671/// Definition for a DuckDB macro: either an expression or a table-producing query.
10672pub enum MacroDefinition {
10673    /// The macro is defined as an expression.
10674    Expr(Expr),
10675    /// The macro is defined as a table (query).
10676    Table(Box<Query>),
10677}
10678
10679impl fmt::Display for MacroDefinition {
10680    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10681        match self {
10682            MacroDefinition::Expr(expr) => write!(f, "{expr}")?,
10683            MacroDefinition::Table(query) => write!(f, "{query}")?,
10684        }
10685        Ok(())
10686    }
10687}
10688
10689/// Schema possible naming variants ([1]).
10690///
10691/// [1]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#schema-definition
10692#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10693#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10694#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10695pub enum SchemaName {
10696    /// Only schema name specified: `<schema name>`.
10697    Simple(ObjectName),
10698    /// Only authorization identifier specified: `AUTHORIZATION <schema authorization identifier>`.
10699    UnnamedAuthorization(Ident),
10700    /// Both schema name and authorization identifier specified: `<schema name>  AUTHORIZATION <schema authorization identifier>`.
10701    NamedAuthorization(ObjectName, Ident),
10702}
10703
10704impl fmt::Display for SchemaName {
10705    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10706        match self {
10707            SchemaName::Simple(name) => {
10708                write!(f, "{name}")
10709            }
10710            SchemaName::UnnamedAuthorization(authorization) => {
10711                write!(f, "AUTHORIZATION {authorization}")
10712            }
10713            SchemaName::NamedAuthorization(name, authorization) => {
10714                write!(f, "{name} AUTHORIZATION {authorization}")
10715            }
10716        }
10717    }
10718}
10719
10720/// Fulltext search modifiers ([1]).
10721///
10722/// [1]: https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html#function_match
10723#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10724#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10725#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10726pub enum SearchModifier {
10727    /// `IN NATURAL LANGUAGE MODE`.
10728    InNaturalLanguageMode,
10729    /// `IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION`.
10730    InNaturalLanguageModeWithQueryExpansion,
10731    ///`IN BOOLEAN MODE`.
10732    InBooleanMode,
10733    ///`WITH QUERY EXPANSION`.
10734    WithQueryExpansion,
10735}
10736
10737impl fmt::Display for SearchModifier {
10738    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10739        match self {
10740            Self::InNaturalLanguageMode => {
10741                write!(f, "IN NATURAL LANGUAGE MODE")?;
10742            }
10743            Self::InNaturalLanguageModeWithQueryExpansion => {
10744                write!(f, "IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION")?;
10745            }
10746            Self::InBooleanMode => {
10747                write!(f, "IN BOOLEAN MODE")?;
10748            }
10749            Self::WithQueryExpansion => {
10750                write!(f, "WITH QUERY EXPANSION")?;
10751            }
10752        }
10753
10754        Ok(())
10755    }
10756}
10757
10758/// Represents a `LOCK TABLE` clause with optional alias and lock type.
10759#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10760#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10761#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10762pub struct LockTable {
10763    /// The table identifier to lock.
10764    pub table: Ident,
10765    /// Optional alias for the table.
10766    pub alias: Option<Ident>,
10767    /// The type of lock to apply to the table.
10768    pub lock_type: LockTableType,
10769}
10770
10771impl fmt::Display for LockTable {
10772    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10773        let Self {
10774            table: tbl_name,
10775            alias,
10776            lock_type,
10777        } = self;
10778
10779        write!(f, "{tbl_name} ")?;
10780        if let Some(alias) = alias {
10781            write!(f, "AS {alias} ")?;
10782        }
10783        write!(f, "{lock_type}")?;
10784        Ok(())
10785    }
10786}
10787
10788#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10789#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10790#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10791/// The type of lock used in `LOCK TABLE` statements.
10792pub enum LockTableType {
10793    /// Shared/read lock. If `local` is true, it's a local read lock.
10794    Read {
10795        /// Whether the read lock is local.
10796        local: bool,
10797    },
10798    /// Exclusive/write lock. If `low_priority` is true, the write is low priority.
10799    Write {
10800        /// Whether the write lock is low priority.
10801        low_priority: bool,
10802    },
10803}
10804
10805impl fmt::Display for LockTableType {
10806    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10807        match self {
10808            Self::Read { local } => {
10809                write!(f, "READ")?;
10810                if *local {
10811                    write!(f, " LOCAL")?;
10812                }
10813            }
10814            Self::Write { low_priority } => {
10815                if *low_priority {
10816                    write!(f, "LOW_PRIORITY ")?;
10817                }
10818                write!(f, "WRITE")?;
10819            }
10820        }
10821
10822        Ok(())
10823    }
10824}
10825
10826#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10827#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10828#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10829/// Hive-specific `SET LOCATION` helper used in some `LOAD DATA` statements.
10830pub struct HiveSetLocation {
10831    /// Whether the `SET` keyword was present.
10832    pub has_set: bool,
10833    /// The location identifier.
10834    pub location: Ident,
10835}
10836
10837impl fmt::Display for HiveSetLocation {
10838    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10839        if self.has_set {
10840            write!(f, "SET ")?;
10841        }
10842        write!(f, "LOCATION {}", self.location)
10843    }
10844}
10845
10846/// MySQL `ALTER TABLE` only  [FIRST | AFTER column_name]
10847#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10848#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10849#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10850/// MySQL `ALTER TABLE` column position specifier: `FIRST` or `AFTER <column>`.
10851pub enum MySQLColumnPosition {
10852    /// Place the column first in the table.
10853    First,
10854    /// Place the column after the specified identifier.
10855    After(Ident),
10856}
10857
10858impl Display for MySQLColumnPosition {
10859    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10860        match self {
10861            MySQLColumnPosition::First => write!(f, "FIRST"),
10862            MySQLColumnPosition::After(ident) => write!(f, "AFTER {ident}"),
10863        }
10864    }
10865}
10866
10867/// MySQL `CREATE VIEW` algorithm parameter: [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]
10868#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10869#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10870#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10871/// MySQL `CREATE VIEW` algorithm options.
10872pub enum CreateViewAlgorithm {
10873    /// `UNDEFINED` algorithm.
10874    Undefined,
10875    /// `MERGE` algorithm.
10876    Merge,
10877    /// `TEMPTABLE` algorithm.
10878    TempTable,
10879}
10880
10881impl Display for CreateViewAlgorithm {
10882    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10883        match self {
10884            CreateViewAlgorithm::Undefined => write!(f, "UNDEFINED"),
10885            CreateViewAlgorithm::Merge => write!(f, "MERGE"),
10886            CreateViewAlgorithm::TempTable => write!(f, "TEMPTABLE"),
10887        }
10888    }
10889}
10890/// MySQL `CREATE VIEW` security parameter: [SQL SECURITY { DEFINER | INVOKER }]
10891#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10892#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10893#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10894/// MySQL `CREATE VIEW` SQL SECURITY options.
10895pub enum CreateViewSecurity {
10896    /// The view runs with the privileges of the definer.
10897    Definer,
10898    /// The view runs with the privileges of the invoker.
10899    Invoker,
10900}
10901
10902impl Display for CreateViewSecurity {
10903    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10904        match self {
10905            CreateViewSecurity::Definer => write!(f, "DEFINER"),
10906            CreateViewSecurity::Invoker => write!(f, "INVOKER"),
10907        }
10908    }
10909}
10910
10911/// [MySQL] `CREATE VIEW` additional parameters
10912///
10913/// [MySQL]: https://dev.mysql.com/doc/refman/9.1/en/create-view.html
10914#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10915#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10916#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10917pub struct CreateViewParams {
10918    /// Optional view algorithm (e.g., MERGE, TEMPTABLE).
10919    pub algorithm: Option<CreateViewAlgorithm>,
10920    /// Optional definer (the security principal that will own the view).
10921    pub definer: Option<GranteeName>,
10922    /// Optional SQL SECURITY setting for the view.
10923    pub security: Option<CreateViewSecurity>,
10924}
10925
10926impl Display for CreateViewParams {
10927    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10928        let CreateViewParams {
10929            algorithm,
10930            definer,
10931            security,
10932        } = self;
10933        if let Some(algorithm) = algorithm {
10934            write!(f, "ALGORITHM = {algorithm} ")?;
10935        }
10936        if let Some(definers) = definer {
10937            write!(f, "DEFINER = {definers} ")?;
10938        }
10939        if let Some(security) = security {
10940            write!(f, "SQL SECURITY {security} ")?;
10941        }
10942        Ok(())
10943    }
10944}
10945
10946#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10947#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10948#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10949/// Key/Value, where the value is a (optionally named) list of identifiers
10950///
10951/// ```sql
10952/// UNION = (tbl_name[,tbl_name]...)
10953/// ENGINE = ReplicatedMergeTree('/table_name','{replica}', ver)
10954/// ENGINE = SummingMergeTree([columns])
10955/// ```
10956pub struct NamedParenthesizedList {
10957    /// The option key (identifier) for this named list.
10958    pub key: Ident,
10959    /// Optional secondary name associated with the key.
10960    pub name: Option<Ident>,
10961    /// The list of identifier values for the key.
10962    pub values: Vec<Ident>,
10963}
10964
10965/// Snowflake `WITH ROW ACCESS POLICY policy_name ON (identifier, ...)`
10966///
10967/// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
10968/// <https://docs.snowflake.com/en/user-guide/security-row-intro>
10969#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10970#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10971#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10972pub struct RowAccessPolicy {
10973    /// The fully-qualified policy object name.
10974    pub policy: ObjectName,
10975    /// Identifiers for the columns or objects the policy applies to.
10976    pub on: Vec<Ident>,
10977}
10978
10979impl RowAccessPolicy {
10980    /// Create a new `RowAccessPolicy` for the given `policy` and `on` identifiers.
10981    pub fn new(policy: ObjectName, on: Vec<Ident>) -> Self {
10982        Self { policy, on }
10983    }
10984}
10985
10986impl Display for RowAccessPolicy {
10987    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10988        write!(
10989            f,
10990            "WITH ROW ACCESS POLICY {} ON ({})",
10991            self.policy,
10992            display_comma_separated(self.on.as_slice())
10993        )
10994    }
10995}
10996
10997/// Snowflake `[ WITH ] STORAGE LIFECYCLE POLICY <policy_name> ON ( <col_name> [ , ... ] )`
10998///
10999/// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
11000#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11001#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11002#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11003pub struct StorageLifecyclePolicy {
11004    /// The fully-qualified policy object name.
11005    pub policy: ObjectName,
11006    /// Column names the policy applies to.
11007    pub on: Vec<Ident>,
11008}
11009
11010impl Display for StorageLifecyclePolicy {
11011    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11012        write!(
11013            f,
11014            "WITH STORAGE LIFECYCLE POLICY {} ON ({})",
11015            self.policy,
11016            display_comma_separated(self.on.as_slice())
11017        )
11018    }
11019}
11020
11021/// Snowflake `WITH TAG ( tag_name = '<tag_value>', ...)`
11022///
11023/// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
11024#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11025#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11026#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11027pub struct Tag {
11028    /// The tag key (can be qualified).
11029    pub key: ObjectName,
11030    /// The tag value as a string.
11031    pub value: String,
11032}
11033
11034impl Tag {
11035    /// Create a new `Tag` with the given key and value.
11036    pub fn new(key: ObjectName, value: String) -> Self {
11037        Self { key, value }
11038    }
11039}
11040
11041impl Display for Tag {
11042    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11043        write!(f, "{}='{}'", self.key, self.value)
11044    }
11045}
11046
11047/// Snowflake `WITH CONTACT ( purpose = contact [ , purpose = contact ...] )`
11048///
11049/// <https://docs.snowflake.com/en/sql-reference/sql/create-database>
11050#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11051#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11052#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11053pub struct ContactEntry {
11054    /// The purpose label for the contact entry.
11055    pub purpose: String,
11056    /// The contact information associated with the purpose.
11057    pub contact: String,
11058}
11059
11060impl Display for ContactEntry {
11061    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11062        write!(f, "{} = {}", self.purpose, self.contact)
11063    }
11064}
11065
11066/// Helper to indicate if a comment includes the `=` in the display form
11067#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11068#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11069#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11070pub enum CommentDef {
11071    /// Includes `=` when printing the comment, as `COMMENT = 'comment'`
11072    /// Does not include `=` when printing the comment, as `COMMENT 'comment'`
11073    WithEq(String),
11074    /// Comment variant that omits the `=` when displayed.
11075    WithoutEq(String),
11076}
11077
11078impl Display for CommentDef {
11079    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11080        match self {
11081            CommentDef::WithEq(comment) | CommentDef::WithoutEq(comment) => write!(f, "{comment}"),
11082        }
11083    }
11084}
11085
11086/// Helper to indicate if a collection should be wrapped by a symbol in the display form
11087///
11088/// [`Display`] is implemented for every [`Vec<T>`] where `T: Display`.
11089/// The string output is a comma separated list for the vec items
11090///
11091/// # Examples
11092/// ```
11093/// # use sqlparser::ast::WrappedCollection;
11094/// let items = WrappedCollection::Parentheses(vec!["one", "two", "three"]);
11095/// assert_eq!("(one, two, three)", items.to_string());
11096///
11097/// let items = WrappedCollection::NoWrapping(vec!["one", "two", "three"]);
11098/// assert_eq!("one, two, three", items.to_string());
11099/// ```
11100#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11101#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11102#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11103pub enum WrappedCollection<T> {
11104    /// Print the collection without wrapping symbols, as `item, item, item`
11105    NoWrapping(T),
11106    /// Wraps the collection in Parentheses, as `(item, item, item)`
11107    Parentheses(T),
11108}
11109
11110impl<T> Display for WrappedCollection<Vec<T>>
11111where
11112    T: Display,
11113{
11114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11115        match self {
11116            WrappedCollection::NoWrapping(inner) => {
11117                write!(f, "{}", display_comma_separated(inner.as_slice()))
11118            }
11119            WrappedCollection::Parentheses(inner) => {
11120                write!(f, "({})", display_comma_separated(inner.as_slice()))
11121            }
11122        }
11123    }
11124}
11125
11126/// Represents a single PostgreSQL utility option.
11127///
11128/// A utility option is a key-value pair where the key is an identifier (IDENT) and the value
11129/// can be one of the following:
11130/// - A number with an optional sign (`+` or `-`). Example: `+10`, `-10.2`, `3`
11131/// - A non-keyword string. Example: `option1`, `'option2'`, `"option3"`
11132/// - keyword: `TRUE`, `FALSE`, `ON` (`off` is also accept).
11133/// - Empty. Example: `ANALYZE` (identifier only)
11134///
11135/// Utility options are used in various PostgreSQL DDL statements, including statements such as
11136/// `CLUSTER`, `EXPLAIN`, `VACUUM`, and `REINDEX`. These statements format options as `( option [, ...] )`.
11137///
11138/// [CLUSTER](https://www.postgresql.org/docs/current/sql-cluster.html)
11139/// [EXPLAIN](https://www.postgresql.org/docs/current/sql-explain.html)
11140/// [VACUUM](https://www.postgresql.org/docs/current/sql-vacuum.html)
11141/// [REINDEX](https://www.postgresql.org/docs/current/sql-reindex.html)
11142///
11143/// For example, the `EXPLAIN` AND `VACUUM` statements with options might look like this:
11144/// ```sql
11145/// EXPLAIN (ANALYZE, VERBOSE TRUE, FORMAT TEXT) SELECT * FROM my_table;
11146///
11147/// VACUUM (VERBOSE, ANALYZE ON, PARALLEL 10) my_table;
11148/// ```
11149#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11150#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11151#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11152pub struct UtilityOption {
11153    /// The option name (identifier).
11154    pub name: Ident,
11155    /// Optional argument for the option (number, string, keyword, etc.).
11156    pub arg: Option<Expr>,
11157}
11158
11159impl Display for UtilityOption {
11160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11161        if let Some(ref arg) = self.arg {
11162            write!(f, "{} {}", self.name, arg)
11163        } else {
11164            write!(f, "{}", self.name)
11165        }
11166    }
11167}
11168
11169/// Represents the different options available for `SHOW`
11170/// statements to filter the results. Example from Snowflake:
11171/// <https://docs.snowflake.com/en/sql-reference/sql/show-tables>
11172#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11173#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11174#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11175pub struct ShowStatementOptions {
11176    /// Optional scope to show in (for example: TABLE, SCHEMA).
11177    pub show_in: Option<ShowStatementIn>,
11178    /// Optional `STARTS WITH` filter value.
11179    pub starts_with: Option<ValueWithSpan>,
11180    /// Optional `LIMIT` expression.
11181    pub limit: Option<Expr>,
11182    /// Optional `FROM` value used with `LIMIT`.
11183    pub limit_from: Option<ValueWithSpan>,
11184    /// Optional filter position (infix or suffix) for `LIKE`/`FILTER`.
11185    pub filter_position: Option<ShowStatementFilterPosition>,
11186}
11187
11188impl Display for ShowStatementOptions {
11189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11190        let (like_in_infix, like_in_suffix) = match &self.filter_position {
11191            Some(ShowStatementFilterPosition::Infix(filter)) => {
11192                (format!(" {filter}"), "".to_string())
11193            }
11194            Some(ShowStatementFilterPosition::Suffix(filter)) => {
11195                ("".to_string(), format!(" {filter}"))
11196            }
11197            None => ("".to_string(), "".to_string()),
11198        };
11199        write!(
11200            f,
11201            "{like_in_infix}{show_in}{starts_with}{limit}{from}{like_in_suffix}",
11202            show_in = match &self.show_in {
11203                Some(i) => format!(" {i}"),
11204                None => String::new(),
11205            },
11206            starts_with = match &self.starts_with {
11207                Some(s) => format!(" STARTS WITH {s}"),
11208                None => String::new(),
11209            },
11210            limit = match &self.limit {
11211                Some(l) => format!(" LIMIT {l}"),
11212                None => String::new(),
11213            },
11214            from = match &self.limit_from {
11215                Some(f) => format!(" FROM {f}"),
11216                None => String::new(),
11217            }
11218        )?;
11219        Ok(())
11220    }
11221}
11222
11223#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11224#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11225#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11226/// Where a `SHOW` filter appears relative to the main clause.
11227pub enum ShowStatementFilterPosition {
11228    /// Put the filter in an infix position (e.g. `SHOW COLUMNS LIKE '%name%' IN TABLE tbl`).
11229    Infix(ShowStatementFilter), // For example: SHOW COLUMNS LIKE '%name%' IN TABLE tbl
11230    /// Put the filter in a suffix position (e.g. `SHOW COLUMNS IN tbl LIKE '%name%'`).
11231    Suffix(ShowStatementFilter), // For example: SHOW COLUMNS IN tbl LIKE '%name%'
11232}
11233
11234#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11235#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11236#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11237/// Parent object types usable with `SHOW ... IN <parent>` clauses.
11238pub enum ShowStatementInParentType {
11239    /// ACCOUNT parent type for SHOW statements.
11240    Account,
11241    /// DATABASE parent type for SHOW statements.
11242    Database,
11243    /// SCHEMA parent type for SHOW statements.
11244    Schema,
11245    /// TABLE parent type for SHOW statements.
11246    Table,
11247    /// VIEW parent type for SHOW statements.
11248    View,
11249}
11250
11251impl fmt::Display for ShowStatementInParentType {
11252    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11253        match self {
11254            ShowStatementInParentType::Account => write!(f, "ACCOUNT"),
11255            ShowStatementInParentType::Database => write!(f, "DATABASE"),
11256            ShowStatementInParentType::Schema => write!(f, "SCHEMA"),
11257            ShowStatementInParentType::Table => write!(f, "TABLE"),
11258            ShowStatementInParentType::View => write!(f, "VIEW"),
11259        }
11260    }
11261}
11262
11263#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11264#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11265#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11266/// Represents a `SHOW ... IN` clause with optional parent qualifier and name.
11267pub struct ShowStatementIn {
11268    /// The clause that specifies what to show (e.g. COLUMNS, TABLES).
11269    pub clause: ShowStatementInClause,
11270    /// Optional parent type qualifier (ACCOUNT/DATABASE/...).
11271    pub parent_type: Option<ShowStatementInParentType>,
11272    /// Optional parent object name for the SHOW clause.
11273    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
11274    pub parent_name: Option<ObjectName>,
11275}
11276
11277impl fmt::Display for ShowStatementIn {
11278    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11279        write!(f, "{}", self.clause)?;
11280        if let Some(parent_type) = &self.parent_type {
11281            write!(f, " {parent_type}")?;
11282        }
11283        if let Some(parent_name) = &self.parent_name {
11284            write!(f, " {parent_name}")?;
11285        }
11286        Ok(())
11287    }
11288}
11289
11290/// A Show Charset statement
11291#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11292#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11293#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11294pub struct ShowCharset {
11295    /// The statement can be written as `SHOW CHARSET` or `SHOW CHARACTER SET`
11296    /// true means CHARSET was used and false means CHARACTER SET was used
11297    pub is_shorthand: bool,
11298    /// Optional `LIKE`/`WHERE`-style filter for the statement.
11299    pub filter: Option<ShowStatementFilter>,
11300}
11301
11302impl fmt::Display for ShowCharset {
11303    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11304        write!(f, "SHOW")?;
11305        if self.is_shorthand {
11306            write!(f, " CHARSET")?;
11307        } else {
11308            write!(f, " CHARACTER SET")?;
11309        }
11310        if let Some(filter) = &self.filter {
11311            write!(f, " {filter}")?;
11312        }
11313        Ok(())
11314    }
11315}
11316
11317#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11318#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11319#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11320/// Options for a `SHOW OBJECTS` statement.
11321pub struct ShowObjects {
11322    /// Whether to show terse output.
11323    pub terse: bool,
11324    /// Additional options controlling the SHOW output.
11325    pub show_options: ShowStatementOptions,
11326}
11327
11328/// MSSQL's json null clause
11329///
11330/// ```plaintext
11331/// <json_null_clause> ::=
11332///       NULL ON NULL
11333///     | ABSENT ON NULL
11334/// ```
11335///
11336/// <https://learn.microsoft.com/en-us/sql/t-sql/functions/json-object-transact-sql?view=sql-server-ver16#json_null_clause>
11337#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11338#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11339#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11340pub enum JsonNullClause {
11341    /// `NULL ON NULL` behavior for JSON functions.
11342    NullOnNull,
11343    /// `ABSENT ON NULL` behavior for JSON functions.
11344    AbsentOnNull,
11345}
11346
11347impl Display for JsonNullClause {
11348    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11349        match self {
11350            JsonNullClause::NullOnNull => write!(f, "NULL ON NULL"),
11351            JsonNullClause::AbsentOnNull => write!(f, "ABSENT ON NULL"),
11352        }
11353    }
11354}
11355
11356/// PostgreSQL JSON function RETURNING clause
11357///
11358/// Example:
11359/// ```sql
11360/// JSON_OBJECT('a': 1 RETURNING jsonb)
11361/// ```
11362#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11363#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11364#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11365pub struct JsonReturningClause {
11366    /// The data type to return from the JSON function (e.g. JSON/JSONB).
11367    pub data_type: DataType,
11368}
11369
11370impl Display for JsonReturningClause {
11371    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11372        write!(f, "RETURNING {}", self.data_type)
11373    }
11374}
11375
11376/// rename object definition
11377#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11378#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11379#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11380pub struct RenameTable {
11381    /// The current name of the object to rename.
11382    pub old_name: ObjectName,
11383    /// The new name for the object.
11384    pub new_name: ObjectName,
11385}
11386
11387impl fmt::Display for RenameTable {
11388    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11389        write!(f, "{} TO {}", self.old_name, self.new_name)?;
11390        Ok(())
11391    }
11392}
11393
11394/// Represents the referenced table in an `INSERT INTO` statement
11395#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11396#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11397#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11398pub enum TableObject {
11399    /// Table specified by name.
11400    /// Example:
11401    /// ```sql
11402    /// INSERT INTO my_table
11403    /// ```
11404    TableName(#[cfg_attr(feature = "visitor", visit(with = "visit_relation"))] ObjectName),
11405
11406    /// Table specified as a function.
11407    /// Example:
11408    /// ```sql
11409    /// INSERT INTO TABLE FUNCTION remote('localhost', default.simple_table)
11410    /// ```
11411    /// [Clickhouse](https://clickhouse.com/docs/en/sql-reference/table-functions)
11412    TableFunction(Function),
11413
11414    /// Table specified through a sub-query
11415    /// Example:
11416    /// ```sql
11417    /// INSERT INTO
11418    /// (SELECT employee_id, last_name, email, hire_date, job_id,  salary, commission_pct FROM employees)
11419    /// VALUES (207, 'Gregory', 'pgregory@example.com', sysdate, 'PU_CLERK', 1.2E3, NULL);
11420    /// ```
11421    /// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/INSERT.html#GUID-903F8043-0254-4EE9-ACC1-CB8AC0AF3423__I2126242)
11422    TableQuery(Box<Query>),
11423}
11424
11425impl fmt::Display for TableObject {
11426    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11427        match self {
11428            Self::TableName(table_name) => write!(f, "{table_name}"),
11429            Self::TableFunction(func) => write!(f, "FUNCTION {func}"),
11430            Self::TableQuery(table_query) => write!(f, "({table_query})"),
11431        }
11432    }
11433}
11434
11435/// Represents a SET SESSION AUTHORIZATION statement
11436#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11437#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11438#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11439pub struct SetSessionAuthorizationParam {
11440    /// The scope for the `SET SESSION AUTHORIZATION` (e.g., GLOBAL/SESSION).
11441    pub scope: ContextModifier,
11442    /// The specific authorization parameter kind.
11443    pub kind: SetSessionAuthorizationParamKind,
11444}
11445
11446impl fmt::Display for SetSessionAuthorizationParam {
11447    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11448        write!(f, "{}", self.kind)
11449    }
11450}
11451
11452/// Represents the parameter kind for SET SESSION AUTHORIZATION
11453#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11454#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11455#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11456pub enum SetSessionAuthorizationParamKind {
11457    /// Default authorization
11458    Default,
11459
11460    /// User name
11461    User(Ident),
11462}
11463
11464impl fmt::Display for SetSessionAuthorizationParamKind {
11465    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11466        match self {
11467            SetSessionAuthorizationParamKind::Default => write!(f, "DEFAULT"),
11468            SetSessionAuthorizationParamKind::User(name) => write!(f, "{}", name),
11469        }
11470    }
11471}
11472
11473#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11474#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11475#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11476/// Kind of session parameter being set by `SET SESSION`.
11477pub enum SetSessionParamKind {
11478    /// Generic session parameter (name/value pair).
11479    Generic(SetSessionParamGeneric),
11480    /// Identity insert related parameter.
11481    IdentityInsert(SetSessionParamIdentityInsert),
11482    /// Offsets-related parameter.
11483    Offsets(SetSessionParamOffsets),
11484    /// Statistics-related parameter.
11485    Statistics(SetSessionParamStatistics),
11486}
11487
11488impl fmt::Display for SetSessionParamKind {
11489    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11490        match self {
11491            SetSessionParamKind::Generic(x) => write!(f, "{x}"),
11492            SetSessionParamKind::IdentityInsert(x) => write!(f, "{x}"),
11493            SetSessionParamKind::Offsets(x) => write!(f, "{x}"),
11494            SetSessionParamKind::Statistics(x) => write!(f, "{x}"),
11495        }
11496    }
11497}
11498
11499#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11500#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11501#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11502/// Generic `SET SESSION` parameter represented as name(s) and value.
11503pub struct SetSessionParamGeneric {
11504    /// Names of the session parameters being set.
11505    pub names: Vec<String>,
11506    /// The value to assign to the parameter(s).
11507    pub value: String,
11508}
11509
11510impl fmt::Display for SetSessionParamGeneric {
11511    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11512        write!(f, "{} {}", display_comma_separated(&self.names), self.value)
11513    }
11514}
11515
11516#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11517#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11518#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11519/// `IDENTITY_INSERT` session parameter for a specific object.
11520pub struct SetSessionParamIdentityInsert {
11521    /// Object name targeted by `IDENTITY_INSERT`.
11522    pub obj: ObjectName,
11523    /// Value (ON/OFF) for the identity insert setting.
11524    pub value: SessionParamValue,
11525}
11526
11527impl fmt::Display for SetSessionParamIdentityInsert {
11528    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11529        write!(f, "IDENTITY_INSERT {} {}", self.obj, self.value)
11530    }
11531}
11532
11533#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11534#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11535#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11536/// Offsets-related session parameter with keywords and a value.
11537pub struct SetSessionParamOffsets {
11538    /// Keywords specifying which offsets to modify.
11539    pub keywords: Vec<String>,
11540    /// Value (ON/OFF) for the offsets setting.
11541    pub value: SessionParamValue,
11542}
11543
11544impl fmt::Display for SetSessionParamOffsets {
11545    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11546        write!(
11547            f,
11548            "OFFSETS {} {}",
11549            display_comma_separated(&self.keywords),
11550            self.value
11551        )
11552    }
11553}
11554
11555#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11556#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11557#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11558/// Statistics-related session parameter specifying topic and value.
11559pub struct SetSessionParamStatistics {
11560    /// Statistics topic to set (IO/PROFILE/TIME/XML).
11561    pub topic: SessionParamStatsTopic,
11562    /// Value (ON/OFF) for the statistics topic.
11563    pub value: SessionParamValue,
11564}
11565
11566impl fmt::Display for SetSessionParamStatistics {
11567    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11568        write!(f, "STATISTICS {} {}", self.topic, self.value)
11569    }
11570}
11571
11572#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11573#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11574#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11575/// Topics available for session statistics configuration.
11576pub enum SessionParamStatsTopic {
11577    /// Input/output statistics.
11578    IO,
11579    /// Profile statistics.
11580    Profile,
11581    /// Time statistics.
11582    Time,
11583    /// XML-related statistics.
11584    Xml,
11585}
11586
11587impl fmt::Display for SessionParamStatsTopic {
11588    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11589        match self {
11590            SessionParamStatsTopic::IO => write!(f, "IO"),
11591            SessionParamStatsTopic::Profile => write!(f, "PROFILE"),
11592            SessionParamStatsTopic::Time => write!(f, "TIME"),
11593            SessionParamStatsTopic::Xml => write!(f, "XML"),
11594        }
11595    }
11596}
11597
11598#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11599#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11600#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11601/// Value for a session boolean-like parameter (ON/OFF).
11602pub enum SessionParamValue {
11603    /// Session parameter enabled.
11604    On,
11605    /// Session parameter disabled.
11606    Off,
11607}
11608
11609impl fmt::Display for SessionParamValue {
11610    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11611        match self {
11612            SessionParamValue::On => write!(f, "ON"),
11613            SessionParamValue::Off => write!(f, "OFF"),
11614        }
11615    }
11616}
11617
11618/// Snowflake StorageSerializationPolicy for Iceberg Tables
11619/// ```sql
11620/// [ STORAGE_SERIALIZATION_POLICY = { COMPATIBLE | OPTIMIZED } ]
11621/// ```
11622///
11623/// <https://docs.snowflake.com/en/sql-reference/sql/create-iceberg-table>
11624#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11625#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11626#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11627pub enum StorageSerializationPolicy {
11628    /// Use compatible serialization mode.
11629    Compatible,
11630    /// Use optimized serialization mode.
11631    Optimized,
11632}
11633
11634impl Display for StorageSerializationPolicy {
11635    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11636        match self {
11637            StorageSerializationPolicy::Compatible => write!(f, "COMPATIBLE"),
11638            StorageSerializationPolicy::Optimized => write!(f, "OPTIMIZED"),
11639        }
11640    }
11641}
11642
11643/// Snowflake CatalogSyncNamespaceMode
11644/// ```sql
11645/// [ CATALOG_SYNC_NAMESPACE_MODE = { NEST | FLATTEN } ]
11646/// ```
11647///
11648/// <https://docs.snowflake.com/en/sql-reference/sql/create-database>
11649#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11650#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11651#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11652pub enum CatalogSyncNamespaceMode {
11653    /// Nest namespaces when syncing catalog.
11654    Nest,
11655    /// Flatten namespaces when syncing catalog.
11656    Flatten,
11657}
11658
11659impl Display for CatalogSyncNamespaceMode {
11660    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11661        match self {
11662            CatalogSyncNamespaceMode::Nest => write!(f, "NEST"),
11663            CatalogSyncNamespaceMode::Flatten => write!(f, "FLATTEN"),
11664        }
11665    }
11666}
11667
11668/// Variants of the Snowflake `COPY INTO` statement
11669#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11670#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11671#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11672pub enum CopyIntoSnowflakeKind {
11673    /// Loads data from files to a table
11674    /// See: <https://docs.snowflake.com/en/sql-reference/sql/copy-into-table>
11675    Table,
11676    /// Unloads data from a table or query to external files
11677    /// See: <https://docs.snowflake.com/en/sql-reference/sql/copy-into-location>
11678    Location,
11679}
11680
11681#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11682#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11683#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11684/// `PRINT` statement for producing debug/output messages.
11685pub struct PrintStatement {
11686    /// The expression producing the message to print.
11687    pub message: Box<Expr>,
11688}
11689
11690impl fmt::Display for PrintStatement {
11691    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11692        write!(f, "PRINT {}", self.message)
11693    }
11694}
11695
11696/// The type of `WAITFOR` statement (MSSQL).
11697///
11698/// See: <https://learn.microsoft.com/en-us/sql/t-sql/language-elements/waitfor-transact-sql>
11699#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11700#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11701#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11702pub enum WaitForType {
11703    /// `WAITFOR DELAY 'time_to_pass'`
11704    Delay,
11705    /// `WAITFOR TIME 'time_to_execute'`
11706    Time,
11707}
11708
11709impl fmt::Display for WaitForType {
11710    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11711        match self {
11712            WaitForType::Delay => write!(f, "DELAY"),
11713            WaitForType::Time => write!(f, "TIME"),
11714        }
11715    }
11716}
11717
11718/// MSSQL `WAITFOR` statement.
11719///
11720/// See: <https://learn.microsoft.com/en-us/sql/t-sql/language-elements/waitfor-transact-sql>
11721#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11722#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11723#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11724pub struct WaitForStatement {
11725    /// `DELAY` or `TIME`.
11726    pub wait_type: WaitForType,
11727    /// The time expression.
11728    pub expr: Expr,
11729}
11730
11731impl fmt::Display for WaitForStatement {
11732    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11733        write!(f, "WAITFOR {} {}", self.wait_type, self.expr)
11734    }
11735}
11736
11737/// Represents a `Return` statement.
11738///
11739/// [MsSql triggers](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql)
11740/// [MsSql functions](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql)
11741#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11742#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11743#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11744pub struct ReturnStatement {
11745    /// Optional return value expression.
11746    pub value: Option<ReturnStatementValue>,
11747}
11748
11749impl fmt::Display for ReturnStatement {
11750    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11751        match &self.value {
11752            Some(ReturnStatementValue::Expr(expr)) => write!(f, "RETURN {expr}"),
11753            None => write!(f, "RETURN"),
11754        }
11755    }
11756}
11757
11758/// Variants of a `RETURN` statement
11759#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11760#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11761#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11762pub enum ReturnStatementValue {
11763    /// Return an expression from a function or trigger.
11764    Expr(Expr),
11765}
11766
11767/// Represents an `OPEN` statement.
11768#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11769#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11770#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11771pub struct OpenStatement {
11772    /// Cursor name
11773    pub cursor_name: Ident,
11774}
11775
11776impl fmt::Display for OpenStatement {
11777    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11778        write!(f, "OPEN {}", self.cursor_name)
11779    }
11780}
11781
11782/// Specifies Include / Exclude NULL within UNPIVOT command.
11783/// For example
11784/// `UNPIVOT (column1 FOR new_column IN (col3, col4, col5, col6))`
11785#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11786#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11787#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11788pub enum NullInclusion {
11789    /// Include NULL values in the UNPIVOT output.
11790    IncludeNulls,
11791    /// Exclude NULL values from the UNPIVOT output.
11792    ExcludeNulls,
11793}
11794
11795impl fmt::Display for NullInclusion {
11796    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11797        match self {
11798            NullInclusion::IncludeNulls => write!(f, "INCLUDE NULLS"),
11799            NullInclusion::ExcludeNulls => write!(f, "EXCLUDE NULLS"),
11800        }
11801    }
11802}
11803
11804/// Checks membership of a value in a JSON array
11805///
11806/// Syntax:
11807/// ```sql
11808/// <value> MEMBER OF(<array>)
11809/// ```
11810/// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/json-search-functions.html#operator_member-of)
11811#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11812#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11813#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11814pub struct MemberOf {
11815    /// The value to check for membership.
11816    pub value: Box<Expr>,
11817    /// The JSON array expression to check against.
11818    pub array: Box<Expr>,
11819}
11820
11821impl fmt::Display for MemberOf {
11822    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11823        write!(f, "{} MEMBER OF({})", self.value, self.array)
11824    }
11825}
11826
11827#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11828#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11829#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11830/// Represents an `EXPORT DATA` statement.
11831pub struct ExportData {
11832    /// Options for the export operation.
11833    pub options: Vec<SqlOption>,
11834    /// The query producing the data to export.
11835    pub query: Box<Query>,
11836    /// Optional named connection to use for export.
11837    pub connection: Option<ObjectName>,
11838}
11839
11840impl fmt::Display for ExportData {
11841    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11842        if let Some(connection) = &self.connection {
11843            write!(
11844                f,
11845                "EXPORT DATA WITH CONNECTION {connection} OPTIONS({}) AS {}",
11846                display_comma_separated(&self.options),
11847                self.query
11848            )
11849        } else {
11850            write!(
11851                f,
11852                "EXPORT DATA OPTIONS({}) AS {}",
11853                display_comma_separated(&self.options),
11854                self.query
11855            )
11856        }
11857    }
11858}
11859/// Creates a user
11860///
11861/// Syntax:
11862/// ```sql
11863/// CREATE [OR REPLACE] USER [IF NOT EXISTS] <name> [OPTIONS]
11864/// ```
11865///
11866/// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/create-user)
11867#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11868#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11869#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11870pub struct CreateUser {
11871    /// Replace existing user if present.
11872    pub or_replace: bool,
11873    /// Only create the user if it does not already exist.
11874    pub if_not_exists: bool,
11875    /// The name of the user to create.
11876    pub name: Ident,
11877    /// Key/value options for user creation.
11878    pub options: KeyValueOptions,
11879    /// Whether tags are specified using `WITH TAG`.
11880    pub with_tags: bool,
11881    /// Tags for the user.
11882    pub tags: KeyValueOptions,
11883}
11884
11885impl fmt::Display for CreateUser {
11886    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11887        write!(f, "CREATE")?;
11888        if self.or_replace {
11889            write!(f, " OR REPLACE")?;
11890        }
11891        write!(f, " USER")?;
11892        if self.if_not_exists {
11893            write!(f, " IF NOT EXISTS")?;
11894        }
11895        write!(f, " {}", self.name)?;
11896        if !self.options.options.is_empty() {
11897            write!(f, " {}", self.options)?;
11898        }
11899        if !self.tags.options.is_empty() {
11900            if self.with_tags {
11901                write!(f, " WITH")?;
11902            }
11903            write!(f, " TAG ({})", self.tags)?;
11904        }
11905        Ok(())
11906    }
11907}
11908
11909/// ```sql
11910/// CREATE [ OR REPLACE ] WAREHOUSE [ IF NOT EXISTS ] <name>
11911///   [ [ WITH ] <property> = <value> [ ... ] ]
11912/// ```
11913/// Snowflake-specific statement to create a virtual warehouse.
11914///
11915/// See <https://docs.snowflake.com/en/sql-reference/sql/create-warehouse>
11916#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11917#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11918#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11919pub struct CreateWarehouse {
11920    /// `OR REPLACE` flag.
11921    pub or_replace: bool,
11922    /// `IF NOT EXISTS` flag.
11923    pub if_not_exists: bool,
11924    /// Warehouse name.
11925    pub name: ObjectName,
11926    /// Warehouse properties and parameters (e.g. `WAREHOUSE_SIZE = 'XSMALL'`).
11927    pub options: KeyValueOptions,
11928}
11929
11930impl fmt::Display for CreateWarehouse {
11931    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11932        write!(f, "CREATE")?;
11933        if self.or_replace {
11934            write!(f, " OR REPLACE")?;
11935        }
11936        write!(f, " WAREHOUSE")?;
11937        if self.if_not_exists {
11938            write!(f, " IF NOT EXISTS")?;
11939        }
11940        write!(f, " {}", self.name)?;
11941        if !self.options.options.is_empty() {
11942            write!(f, " {}", self.options)?;
11943        }
11944        Ok(())
11945    }
11946}
11947
11948/// Modifies the properties of a user
11949///
11950/// [Snowflake Syntax:](https://docs.snowflake.com/en/sql-reference/sql/alter-user)
11951/// ```sql
11952/// ALTER USER [ IF EXISTS ] [ <name> ] [ OPTIONS ]
11953/// ```
11954///
11955/// [PostgreSQL Syntax:](https://www.postgresql.org/docs/current/sql-alteruser.html)
11956/// ```sql
11957/// ALTER USER <role_specification> [ WITH ] option [ ... ]
11958/// ```
11959#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11960#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11961#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11962pub struct AlterUser {
11963    /// Whether to only alter the user if it exists.
11964    pub if_exists: bool,
11965    /// The name of the user to alter.
11966    pub name: Ident,
11967    /// Optional new name for the user (Snowflake-specific).
11968    /// See: <https://docs.snowflake.com/en/sql-reference/sql/alter-user#syntax>
11969    pub rename_to: Option<Ident>,
11970    /// Reset the user's password.
11971    pub reset_password: bool,
11972    /// Abort all running queries for the user.
11973    pub abort_all_queries: bool,
11974    /// Optionally add a delegated role authorization.
11975    pub add_role_delegation: Option<AlterUserAddRoleDelegation>,
11976    /// Optionally remove a delegated role authorization.
11977    pub remove_role_delegation: Option<AlterUserRemoveRoleDelegation>,
11978    /// Enroll the user in MFA.
11979    pub enroll_mfa: bool,
11980    /// Set the default MFA method for the user.
11981    pub set_default_mfa_method: Option<MfaMethodKind>,
11982    /// Remove the user's default MFA method.
11983    pub remove_mfa_method: Option<MfaMethodKind>,
11984    /// Modify an MFA method for the user.
11985    pub modify_mfa_method: Option<AlterUserModifyMfaMethod>,
11986    /// Add an MFA OTP method with optional count.
11987    pub add_mfa_method_otp: Option<AlterUserAddMfaMethodOtp>,
11988    /// Set a user policy.
11989    pub set_policy: Option<AlterUserSetPolicy>,
11990    /// Unset a user policy.
11991    pub unset_policy: Option<UserPolicyKind>,
11992    /// Key/value tag options to set on the user.
11993    pub set_tag: KeyValueOptions,
11994    /// Tags to unset on the user.
11995    pub unset_tag: Vec<String>,
11996    /// Key/value properties to set on the user.
11997    pub set_props: KeyValueOptions,
11998    /// Properties to unset on the user.
11999    pub unset_props: Vec<String>,
12000    /// The following options are PostgreSQL-specific: <https://www.postgresql.org/docs/current/sql-alteruser.html>
12001    pub password: Option<AlterUserPassword>,
12002}
12003
12004/// ```sql
12005/// ALTER USER [ IF EXISTS ] [ <name> ] ADD DELEGATED AUTHORIZATION OF ROLE <role_name> TO SECURITY INTEGRATION <integration_name>
12006/// ```
12007#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12008#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12009#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12010pub struct AlterUserAddRoleDelegation {
12011    /// Role name to delegate.
12012    pub role: Ident,
12013    /// Security integration receiving the delegation.
12014    pub integration: Ident,
12015}
12016
12017/// ```sql
12018/// ALTER USER [ IF EXISTS ] [ <name> ] REMOVE DELEGATED { AUTHORIZATION OF ROLE <role_name> | AUTHORIZATIONS } FROM SECURITY INTEGRATION <integration_name>
12019/// ```
12020#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12021#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12022#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12023pub struct AlterUserRemoveRoleDelegation {
12024    /// Optional role name to remove delegation for.
12025    pub role: Option<Ident>,
12026    /// Security integration from which to remove delegation.
12027    pub integration: Ident,
12028}
12029
12030/// ```sql
12031/// ADD MFA METHOD OTP [ COUNT = number ]
12032/// ```
12033#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12034#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12035#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12036pub struct AlterUserAddMfaMethodOtp {
12037    /// Optional OTP count parameter.
12038    pub count: Option<ValueWithSpan>,
12039}
12040
12041/// ```sql
12042/// ALTER USER [ IF EXISTS ] [ <name> ] MODIFY MFA METHOD <mfa_method> SET COMMENT = '<string>'
12043/// ```
12044#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12045#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12046#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12047pub struct AlterUserModifyMfaMethod {
12048    /// The MFA method being modified.
12049    pub method: MfaMethodKind,
12050    /// The new comment for the MFA method.
12051    pub comment: String,
12052}
12053
12054/// Types of MFA methods
12055#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12056#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12057#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12058pub enum MfaMethodKind {
12059    /// PassKey (hardware or platform passkey) MFA method.
12060    PassKey,
12061    /// Time-based One-Time Password (TOTP) MFA method.
12062    Totp,
12063    /// Duo Security MFA method.
12064    Duo,
12065}
12066
12067impl fmt::Display for MfaMethodKind {
12068    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12069        match self {
12070            MfaMethodKind::PassKey => write!(f, "PASSKEY"),
12071            MfaMethodKind::Totp => write!(f, "TOTP"),
12072            MfaMethodKind::Duo => write!(f, "DUO"),
12073        }
12074    }
12075}
12076
12077/// ```sql
12078/// ALTER USER [ IF EXISTS ] [ <name> ] SET { AUTHENTICATION | PASSWORD | SESSION } POLICY <policy_name>
12079/// ```
12080#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12081#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12082#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12083pub struct AlterUserSetPolicy {
12084    /// The kind of user policy being set (authentication/password/session).
12085    pub policy_kind: UserPolicyKind,
12086    /// The identifier of the policy to apply.
12087    pub policy: Ident,
12088}
12089
12090/// Types of user-based policies
12091#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12092#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12093#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12094pub enum UserPolicyKind {
12095    /// Authentication policy.
12096    Authentication,
12097    /// Password policy.
12098    Password,
12099    /// Session policy.
12100    Session,
12101}
12102
12103impl fmt::Display for UserPolicyKind {
12104    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12105        match self {
12106            UserPolicyKind::Authentication => write!(f, "AUTHENTICATION"),
12107            UserPolicyKind::Password => write!(f, "PASSWORD"),
12108            UserPolicyKind::Session => write!(f, "SESSION"),
12109        }
12110    }
12111}
12112
12113impl fmt::Display for AlterUser {
12114    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12115        write!(f, "ALTER")?;
12116        write!(f, " USER")?;
12117        if self.if_exists {
12118            write!(f, " IF EXISTS")?;
12119        }
12120        write!(f, " {}", self.name)?;
12121        if let Some(new_name) = &self.rename_to {
12122            write!(f, " RENAME TO {new_name}")?;
12123        }
12124        if self.reset_password {
12125            write!(f, " RESET PASSWORD")?;
12126        }
12127        if self.abort_all_queries {
12128            write!(f, " ABORT ALL QUERIES")?;
12129        }
12130        if let Some(role_delegation) = &self.add_role_delegation {
12131            let role = &role_delegation.role;
12132            let integration = &role_delegation.integration;
12133            write!(
12134                f,
12135                " ADD DELEGATED AUTHORIZATION OF ROLE {role} TO SECURITY INTEGRATION {integration}"
12136            )?;
12137        }
12138        if let Some(role_delegation) = &self.remove_role_delegation {
12139            write!(f, " REMOVE DELEGATED")?;
12140            match &role_delegation.role {
12141                Some(role) => write!(f, " AUTHORIZATION OF ROLE {role}")?,
12142                None => write!(f, " AUTHORIZATIONS")?,
12143            }
12144            let integration = &role_delegation.integration;
12145            write!(f, " FROM SECURITY INTEGRATION {integration}")?;
12146        }
12147        if self.enroll_mfa {
12148            write!(f, " ENROLL MFA")?;
12149        }
12150        if let Some(method) = &self.set_default_mfa_method {
12151            write!(f, " SET DEFAULT_MFA_METHOD {method}")?
12152        }
12153        if let Some(method) = &self.remove_mfa_method {
12154            write!(f, " REMOVE MFA METHOD {method}")?;
12155        }
12156        if let Some(modify) = &self.modify_mfa_method {
12157            let method = &modify.method;
12158            let comment = &modify.comment;
12159            write!(
12160                f,
12161                " MODIFY MFA METHOD {method} SET COMMENT '{}'",
12162                value::escape_single_quote_string(comment)
12163            )?;
12164        }
12165        if let Some(add_mfa_method_otp) = &self.add_mfa_method_otp {
12166            write!(f, " ADD MFA METHOD OTP")?;
12167            if let Some(count) = &add_mfa_method_otp.count {
12168                write!(f, " COUNT = {count}")?;
12169            }
12170        }
12171        if let Some(policy) = &self.set_policy {
12172            let policy_kind = &policy.policy_kind;
12173            let name = &policy.policy;
12174            write!(f, " SET {policy_kind} POLICY {name}")?;
12175        }
12176        if let Some(policy_kind) = &self.unset_policy {
12177            write!(f, " UNSET {policy_kind} POLICY")?;
12178        }
12179        if !self.set_tag.options.is_empty() {
12180            write!(f, " SET TAG {}", self.set_tag)?;
12181        }
12182        if !self.unset_tag.is_empty() {
12183            write!(f, " UNSET TAG {}", display_comma_separated(&self.unset_tag))?;
12184        }
12185        let has_props = !self.set_props.options.is_empty();
12186        if has_props {
12187            write!(f, " SET")?;
12188            write!(f, " {}", self.set_props)?;
12189        }
12190        if !self.unset_props.is_empty() {
12191            write!(f, " UNSET {}", display_comma_separated(&self.unset_props))?;
12192        }
12193        if let Some(password) = &self.password {
12194            write!(f, " {}", password)?;
12195        }
12196        Ok(())
12197    }
12198}
12199
12200/// ```sql
12201/// ALTER USER <role_specification> [ WITH ] PASSWORD { 'password' | NULL }``
12202/// ```
12203#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12204#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12205#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12206pub struct AlterUserPassword {
12207    /// Whether the password is encrypted.
12208    pub encrypted: bool,
12209    /// The password string, or `None` for `NULL`.
12210    pub password: Option<String>,
12211}
12212
12213impl Display for AlterUserPassword {
12214    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12215        if self.encrypted {
12216            write!(f, "ENCRYPTED ")?;
12217        }
12218        write!(f, "PASSWORD")?;
12219        match &self.password {
12220            None => write!(f, " NULL")?,
12221            Some(password) => write!(f, " '{}'", value::escape_single_quote_string(password))?,
12222        }
12223        Ok(())
12224    }
12225}
12226
12227/// Specifies how to create a new table based on an existing table's schema.
12228/// '''sql
12229/// CREATE TABLE new LIKE old ...
12230/// '''
12231#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12232#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12233#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12234pub enum CreateTableLikeKind {
12235    /// '''sql
12236    /// CREATE TABLE new (LIKE old ...)
12237    /// '''
12238    /// [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html)
12239    Parenthesized(CreateTableLike),
12240    /// '''sql
12241    /// CREATE TABLE new LIKE old ...
12242    /// '''
12243    /// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/create-table#label-create-table-like)
12244    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_table_like)
12245    Plain(CreateTableLike),
12246}
12247
12248#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12249#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12250#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12251/// Controls whether defaults are included when creating a table FROM/LILE another.
12252pub enum CreateTableLikeDefaults {
12253    /// Include default values from the source table.
12254    Including,
12255    /// Exclude default values from the source table.
12256    Excluding,
12257}
12258
12259impl fmt::Display for CreateTableLikeDefaults {
12260    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12261        match self {
12262            CreateTableLikeDefaults::Including => write!(f, "INCLUDING DEFAULTS"),
12263            CreateTableLikeDefaults::Excluding => write!(f, "EXCLUDING DEFAULTS"),
12264        }
12265    }
12266}
12267
12268#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12269#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12270#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12271/// Represents the `LIKE` clause of a `CREATE TABLE` statement.
12272pub struct CreateTableLike {
12273    /// The source table name to copy the schema from.
12274    pub name: ObjectName,
12275    /// Optional behavior controlling whether defaults are copied.
12276    pub defaults: Option<CreateTableLikeDefaults>,
12277}
12278
12279impl fmt::Display for CreateTableLike {
12280    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12281        write!(f, "LIKE {}", self.name)?;
12282        if let Some(defaults) = &self.defaults {
12283            write!(f, " {defaults}")?;
12284        }
12285        Ok(())
12286    }
12287}
12288
12289/// Specifies the refresh mode for the dynamic table.
12290///
12291/// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/create-dynamic-table)
12292#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12293#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12294#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12295pub enum RefreshModeKind {
12296    /// Automatic refresh mode (`AUTO`).
12297    Auto,
12298    /// Full refresh mode (`FULL`).
12299    Full,
12300    /// Incremental refresh mode (`INCREMENTAL`).
12301    Incremental,
12302}
12303
12304impl fmt::Display for RefreshModeKind {
12305    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12306        match self {
12307            RefreshModeKind::Auto => write!(f, "AUTO"),
12308            RefreshModeKind::Full => write!(f, "FULL"),
12309            RefreshModeKind::Incremental => write!(f, "INCREMENTAL"),
12310        }
12311    }
12312}
12313
12314/// Specifies the behavior of the initial refresh of the dynamic table.
12315///
12316/// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/create-dynamic-table)
12317#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12318#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12319#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12320pub enum InitializeKind {
12321    /// Initialize on creation (`ON CREATE`).
12322    OnCreate,
12323    /// Initialize on schedule (`ON SCHEDULE`).
12324    OnSchedule,
12325}
12326
12327impl fmt::Display for InitializeKind {
12328    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12329        match self {
12330            InitializeKind::OnCreate => write!(f, "ON_CREATE"),
12331            InitializeKind::OnSchedule => write!(f, "ON_SCHEDULE"),
12332        }
12333    }
12334}
12335
12336/// Re-sorts rows and reclaims space in either a specified table or all tables in the current database
12337///
12338/// '''sql
12339/// VACUUM [ FULL | SORT ONLY | DELETE ONLY | REINDEX | RECLUSTER ] [ \[ table_name \] [ TO threshold PERCENT ] \[ BOOST \] ]
12340/// '''
12341/// [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_VACUUM_command.html)
12342#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12343#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12344#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12345pub struct VacuumStatement {
12346    /// Whether `FULL` was specified.
12347    pub full: bool,
12348    /// Whether `SORT ONLY` was specified.
12349    pub sort_only: bool,
12350    /// Whether `DELETE ONLY` was specified.
12351    pub delete_only: bool,
12352    /// Whether `REINDEX` was specified.
12353    pub reindex: bool,
12354    /// Whether `RECLUSTER` was specified.
12355    pub recluster: bool,
12356    /// Optional table to run `VACUUM` on.
12357    pub table_name: Option<ObjectName>,
12358    /// Optional threshold value (percent) for `TO threshold PERCENT`.
12359    pub threshold: Option<ValueWithSpan>,
12360    /// Whether `BOOST` was specified.
12361    pub boost: bool,
12362}
12363
12364impl fmt::Display for VacuumStatement {
12365    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12366        write!(
12367            f,
12368            "VACUUM{}{}{}{}{}",
12369            if self.full { " FULL" } else { "" },
12370            if self.sort_only { " SORT ONLY" } else { "" },
12371            if self.delete_only { " DELETE ONLY" } else { "" },
12372            if self.reindex { " REINDEX" } else { "" },
12373            if self.recluster { " RECLUSTER" } else { "" },
12374        )?;
12375        if let Some(table_name) = &self.table_name {
12376            write!(f, " {table_name}")?;
12377        }
12378        if let Some(threshold) = &self.threshold {
12379            write!(f, " TO {threshold} PERCENT")?;
12380        }
12381        if self.boost {
12382            write!(f, " BOOST")?;
12383        }
12384        Ok(())
12385    }
12386}
12387
12388/// Variants of the RESET statement
12389#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12390#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12391#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12392pub enum Reset {
12393    /// Resets all session parameters to their default values.
12394    ALL,
12395
12396    /// Resets session authorization to the session user.
12397    SessionAuthorization,
12398
12399    /// Resets a specific session parameter to its default value.
12400    ConfigurationParameter(ObjectName),
12401}
12402
12403/// Resets a session parameter to its default value.
12404/// ```sql
12405/// RESET { ALL | SESSION AUTHORIZATION | <configuration_parameter> }
12406/// ```
12407#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12408#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12409#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12410pub struct ResetStatement {
12411    /// The reset action to perform (either `ALL` or a specific configuration parameter).
12412    pub reset: Reset,
12413}
12414
12415/// `REFRESH MATERIALIZED VIEW [ CONCURRENTLY ] name [ WITH [ NO ] DATA ]`
12416///
12417/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-refreshmaterializedview.html)
12418#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12419#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12420#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12421pub struct RefreshMaterializedView {
12422    /// Whether `CONCURRENTLY` was specified.
12423    pub concurrently: bool,
12424    /// Name of the materialized view.
12425    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
12426    pub name: ObjectName,
12427    /// `Some(true)` for `WITH DATA`, `Some(false)` for `WITH NO DATA`.
12428    pub with_data: Option<bool>,
12429}
12430
12431impl fmt::Display for RefreshMaterializedView {
12432    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12433        f.write_str("REFRESH MATERIALIZED VIEW ")?;
12434        if self.concurrently {
12435            f.write_str("CONCURRENTLY ")?;
12436        }
12437        write!(f, "{}", self.name)?;
12438        match self.with_data {
12439            Some(true) => f.write_str(" WITH DATA"),
12440            Some(false) => f.write_str(" WITH NO DATA"),
12441            None => Ok(()),
12442        }
12443    }
12444}
12445
12446/// Query optimizer hints are optionally supported comments after the
12447/// `SELECT`, `INSERT`, `UPDATE`, `REPLACE`, `MERGE`, and `DELETE` keywords in
12448/// the corresponding statements.
12449///
12450/// See [Select::optimizer_hints]
12451#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12452#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12453#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12454pub struct OptimizerHint {
12455    /// An optional prefix between the comment marker and `+`.
12456    ///
12457    /// Standard optimizer hints like `/*+ ... */` have an empty prefix,
12458    /// while system-specific hints like `/*abc+ ... */` have `prefix = "abc"`.
12459    /// The prefix is any sequence of ASCII alphanumeric characters
12460    /// immediately before the `+` marker.
12461    pub prefix: String,
12462    /// the raw text of the optimizer hint without its markers
12463    pub text: String,
12464    /// the style of the comment which `text` was extracted from,
12465    /// e.g. `/*+...*/` or `--+...`
12466    ///
12467    /// Not all dialects support all styles, though.
12468    pub style: OptimizerHintStyle,
12469}
12470
12471/// The commentary style of an [optimizer hint](OptimizerHint)
12472#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12473#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12474#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12475pub enum OptimizerHintStyle {
12476    /// A hint corresponding to a single line comment,
12477    /// e.g. `--+ LEADING(v.e v.d t)`
12478    SingleLine {
12479        /// the comment prefix, e.g. `--`
12480        prefix: String,
12481    },
12482    /// A hint corresponding to a multi line comment,
12483    /// e.g. `/*+ LEADING(v.e v.d t) */`
12484    MultiLine,
12485}
12486
12487impl fmt::Display for OptimizerHint {
12488    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
12489        match &self.style {
12490            OptimizerHintStyle::SingleLine { prefix } => {
12491                f.write_str(prefix)?;
12492                f.write_str(&self.prefix)?;
12493                f.write_str("+")?;
12494                f.write_str(&self.text)?;
12495                f.write_str("\n")
12496            }
12497            OptimizerHintStyle::MultiLine => {
12498                f.write_str("/*")?;
12499                f.write_str(&self.prefix)?;
12500                f.write_str("+")?;
12501                f.write_str(&self.text)?;
12502                f.write_str("*/")
12503            }
12504        }
12505    }
12506}
12507
12508impl fmt::Display for ResetStatement {
12509    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12510        match &self.reset {
12511            Reset::ALL => write!(f, "RESET ALL"),
12512            Reset::SessionAuthorization => write!(f, "RESET SESSION AUTHORIZATION"),
12513            Reset::ConfigurationParameter(param) => write!(f, "RESET {}", param),
12514        }
12515    }
12516}
12517
12518impl From<Set> for Statement {
12519    fn from(s: Set) -> Self {
12520        Self::Set(s)
12521    }
12522}
12523
12524impl From<Query> for Statement {
12525    fn from(q: Query) -> Self {
12526        Box::new(q).into()
12527    }
12528}
12529
12530impl From<Box<Query>> for Statement {
12531    fn from(q: Box<Query>) -> Self {
12532        Self::Query(q)
12533    }
12534}
12535
12536impl From<Insert> for Statement {
12537    fn from(i: Insert) -> Self {
12538        Self::Insert(i)
12539    }
12540}
12541
12542impl From<Update> for Statement {
12543    fn from(u: Update) -> Self {
12544        Self::Update(u)
12545    }
12546}
12547
12548impl From<CreateView> for Statement {
12549    fn from(cv: CreateView) -> Self {
12550        Self::CreateView(cv)
12551    }
12552}
12553
12554impl From<CreateRole> for Statement {
12555    fn from(cr: CreateRole) -> Self {
12556        Self::CreateRole(cr)
12557    }
12558}
12559
12560impl From<AlterTable> for Statement {
12561    fn from(at: AlterTable) -> Self {
12562        Self::AlterTable(at)
12563    }
12564}
12565
12566impl From<DropFunction> for Statement {
12567    fn from(df: DropFunction) -> Self {
12568        Self::DropFunction(df)
12569    }
12570}
12571
12572impl From<CreateExtension> for Statement {
12573    fn from(ce: CreateExtension) -> Self {
12574        Self::CreateExtension(ce)
12575    }
12576}
12577
12578impl From<CreateCollation> for Statement {
12579    fn from(c: CreateCollation) -> Self {
12580        Self::CreateCollation(c)
12581    }
12582}
12583
12584impl From<DropExtension> for Statement {
12585    fn from(de: DropExtension) -> Self {
12586        Self::DropExtension(de)
12587    }
12588}
12589
12590impl From<CaseStatement> for Statement {
12591    fn from(c: CaseStatement) -> Self {
12592        Self::Case(c)
12593    }
12594}
12595
12596impl From<IfStatement> for Statement {
12597    fn from(i: IfStatement) -> Self {
12598        Self::If(i)
12599    }
12600}
12601
12602impl From<WhileStatement> for Statement {
12603    fn from(w: WhileStatement) -> Self {
12604        Self::While(w)
12605    }
12606}
12607
12608impl From<RaiseStatement> for Statement {
12609    fn from(r: RaiseStatement) -> Self {
12610        Self::Raise(r)
12611    }
12612}
12613
12614impl From<ThrowStatement> for Statement {
12615    fn from(t: ThrowStatement) -> Self {
12616        Self::Throw(t)
12617    }
12618}
12619
12620impl From<Function> for Statement {
12621    fn from(f: Function) -> Self {
12622        Self::Call(f)
12623    }
12624}
12625
12626impl From<OpenStatement> for Statement {
12627    fn from(o: OpenStatement) -> Self {
12628        Self::Open(o)
12629    }
12630}
12631
12632impl From<Delete> for Statement {
12633    fn from(d: Delete) -> Self {
12634        Self::Delete(d)
12635    }
12636}
12637
12638impl From<CreateTable> for Statement {
12639    fn from(c: CreateTable) -> Self {
12640        Self::CreateTable(c)
12641    }
12642}
12643
12644impl From<CreateIndex> for Statement {
12645    fn from(c: CreateIndex) -> Self {
12646        Self::CreateIndex(c)
12647    }
12648}
12649
12650impl From<CreateServerStatement> for Statement {
12651    fn from(c: CreateServerStatement) -> Self {
12652        Self::CreateServer(c)
12653    }
12654}
12655
12656impl From<CreateConnector> for Statement {
12657    fn from(c: CreateConnector) -> Self {
12658        Self::CreateConnector(c)
12659    }
12660}
12661
12662impl From<CreateOperator> for Statement {
12663    fn from(c: CreateOperator) -> Self {
12664        Self::CreateOperator(c)
12665    }
12666}
12667
12668impl From<CreateOperatorFamily> for Statement {
12669    fn from(c: CreateOperatorFamily) -> Self {
12670        Self::CreateOperatorFamily(c)
12671    }
12672}
12673
12674impl From<CreateOperatorClass> for Statement {
12675    fn from(c: CreateOperatorClass) -> Self {
12676        Self::CreateOperatorClass(c)
12677    }
12678}
12679
12680impl From<CreateTextSearch> for Statement {
12681    fn from(c: CreateTextSearch) -> Self {
12682        Self::CreateTextSearch(c)
12683    }
12684}
12685
12686impl From<AlterSchema> for Statement {
12687    fn from(a: AlterSchema) -> Self {
12688        Self::AlterSchema(a)
12689    }
12690}
12691
12692impl From<AlterFunction> for Statement {
12693    fn from(a: AlterFunction) -> Self {
12694        Self::AlterFunction(a)
12695    }
12696}
12697
12698impl From<AlterType> for Statement {
12699    fn from(a: AlterType) -> Self {
12700        Self::AlterType(a)
12701    }
12702}
12703
12704impl From<AlterCollation> for Statement {
12705    fn from(a: AlterCollation) -> Self {
12706        Self::AlterCollation(a)
12707    }
12708}
12709
12710impl From<AlterView> for Statement {
12711    fn from(a: AlterView) -> Self {
12712        Self::AlterView(a)
12713    }
12714}
12715
12716impl From<AlterOperator> for Statement {
12717    fn from(a: AlterOperator) -> Self {
12718        Self::AlterOperator(a)
12719    }
12720}
12721
12722impl From<AlterOperatorFamily> for Statement {
12723    fn from(a: AlterOperatorFamily) -> Self {
12724        Self::AlterOperatorFamily(a)
12725    }
12726}
12727
12728impl From<AlterOperatorClass> for Statement {
12729    fn from(a: AlterOperatorClass) -> Self {
12730        Self::AlterOperatorClass(a)
12731    }
12732}
12733
12734impl From<AlterTextSearch> for Statement {
12735    fn from(a: AlterTextSearch) -> Self {
12736        Self::AlterTextSearch(a)
12737    }
12738}
12739
12740impl From<Merge> for Statement {
12741    fn from(m: Merge) -> Self {
12742        Self::Merge(m)
12743    }
12744}
12745
12746impl From<AlterUser> for Statement {
12747    fn from(a: AlterUser) -> Self {
12748        Self::AlterUser(a)
12749    }
12750}
12751
12752impl From<DropDomain> for Statement {
12753    fn from(d: DropDomain) -> Self {
12754        Self::DropDomain(d)
12755    }
12756}
12757
12758impl From<ShowCharset> for Statement {
12759    fn from(s: ShowCharset) -> Self {
12760        Self::ShowCharset(s)
12761    }
12762}
12763
12764impl From<ShowObjects> for Statement {
12765    fn from(s: ShowObjects) -> Self {
12766        Self::ShowObjects(s)
12767    }
12768}
12769
12770impl From<Use> for Statement {
12771    fn from(u: Use) -> Self {
12772        Self::Use(u)
12773    }
12774}
12775
12776impl From<CreateFunction> for Statement {
12777    fn from(c: CreateFunction) -> Self {
12778        Self::CreateFunction(c)
12779    }
12780}
12781
12782impl From<CreateTrigger> for Statement {
12783    fn from(c: CreateTrigger) -> Self {
12784        Self::CreateTrigger(c)
12785    }
12786}
12787
12788impl From<DropTrigger> for Statement {
12789    fn from(d: DropTrigger) -> Self {
12790        Self::DropTrigger(d)
12791    }
12792}
12793
12794impl From<DropOperator> for Statement {
12795    fn from(d: DropOperator) -> Self {
12796        Self::DropOperator(d)
12797    }
12798}
12799
12800impl From<DropOperatorFamily> for Statement {
12801    fn from(d: DropOperatorFamily) -> Self {
12802        Self::DropOperatorFamily(d)
12803    }
12804}
12805
12806impl From<DropOperatorClass> for Statement {
12807    fn from(d: DropOperatorClass) -> Self {
12808        Self::DropOperatorClass(d)
12809    }
12810}
12811
12812impl From<DenyStatement> for Statement {
12813    fn from(d: DenyStatement) -> Self {
12814        Self::Deny(d)
12815    }
12816}
12817
12818impl From<CreateDomain> for Statement {
12819    fn from(c: CreateDomain) -> Self {
12820        Self::CreateDomain(c)
12821    }
12822}
12823
12824impl From<RenameTable> for Statement {
12825    fn from(r: RenameTable) -> Self {
12826        vec![r].into()
12827    }
12828}
12829
12830impl From<Vec<RenameTable>> for Statement {
12831    fn from(r: Vec<RenameTable>) -> Self {
12832        Self::RenameTable(r)
12833    }
12834}
12835
12836impl From<PrintStatement> for Statement {
12837    fn from(p: PrintStatement) -> Self {
12838        Self::Print(p)
12839    }
12840}
12841
12842impl From<ReturnStatement> for Statement {
12843    fn from(r: ReturnStatement) -> Self {
12844        Self::Return(r)
12845    }
12846}
12847
12848impl From<ExportData> for Statement {
12849    fn from(e: ExportData) -> Self {
12850        Self::ExportData(e)
12851    }
12852}
12853
12854impl From<CreateUser> for Statement {
12855    fn from(c: CreateUser) -> Self {
12856        Self::CreateUser(c)
12857    }
12858}
12859
12860impl From<CreateWarehouse> for Statement {
12861    fn from(c: CreateWarehouse) -> Self {
12862        Self::CreateWarehouse(c)
12863    }
12864}
12865
12866impl From<VacuumStatement> for Statement {
12867    fn from(v: VacuumStatement) -> Self {
12868        Self::Vacuum(v)
12869    }
12870}
12871
12872impl From<ResetStatement> for Statement {
12873    fn from(r: ResetStatement) -> Self {
12874        Self::Reset(r)
12875    }
12876}
12877
12878impl From<RefreshMaterializedView> for Statement {
12879    fn from(r: RefreshMaterializedView) -> Self {
12880        Self::RefreshMaterializedView(r)
12881    }
12882}
12883
12884#[cfg(test)]
12885mod tests {
12886    use crate::tokenizer::Location;
12887
12888    use super::*;
12889
12890    #[test]
12891    fn test_window_frame_default() {
12892        let window_frame = WindowFrame::default();
12893        assert_eq!(WindowFrameBound::Preceding(None), window_frame.start_bound);
12894    }
12895
12896    #[test]
12897    fn test_grouping_sets_display() {
12898        // a and b in different group
12899        let grouping_sets = Expr::GroupingSets(vec![
12900            vec![Expr::Identifier(Ident::new("a"))],
12901            vec![Expr::Identifier(Ident::new("b"))],
12902        ]);
12903        assert_eq!("GROUPING SETS ((a), (b))", format!("{grouping_sets}"));
12904
12905        // a and b in the same group
12906        let grouping_sets = Expr::GroupingSets(vec![vec![
12907            Expr::Identifier(Ident::new("a")),
12908            Expr::Identifier(Ident::new("b")),
12909        ]]);
12910        assert_eq!("GROUPING SETS ((a, b))", format!("{grouping_sets}"));
12911
12912        // (a, b) and (c, d) in different group
12913        let grouping_sets = Expr::GroupingSets(vec![
12914            vec![
12915                Expr::Identifier(Ident::new("a")),
12916                Expr::Identifier(Ident::new("b")),
12917            ],
12918            vec![
12919                Expr::Identifier(Ident::new("c")),
12920                Expr::Identifier(Ident::new("d")),
12921            ],
12922        ]);
12923        assert_eq!("GROUPING SETS ((a, b), (c, d))", format!("{grouping_sets}"));
12924    }
12925
12926    #[test]
12927    fn test_rollup_display() {
12928        let rollup = Expr::Rollup(vec![vec![Expr::Identifier(Ident::new("a"))]]);
12929        assert_eq!("ROLLUP (a)", format!("{rollup}"));
12930
12931        let rollup = Expr::Rollup(vec![vec![
12932            Expr::Identifier(Ident::new("a")),
12933            Expr::Identifier(Ident::new("b")),
12934        ]]);
12935        assert_eq!("ROLLUP ((a, b))", format!("{rollup}"));
12936
12937        let rollup = Expr::Rollup(vec![
12938            vec![Expr::Identifier(Ident::new("a"))],
12939            vec![Expr::Identifier(Ident::new("b"))],
12940        ]);
12941        assert_eq!("ROLLUP (a, b)", format!("{rollup}"));
12942
12943        let rollup = Expr::Rollup(vec![
12944            vec![Expr::Identifier(Ident::new("a"))],
12945            vec![
12946                Expr::Identifier(Ident::new("b")),
12947                Expr::Identifier(Ident::new("c")),
12948            ],
12949            vec![Expr::Identifier(Ident::new("d"))],
12950        ]);
12951        assert_eq!("ROLLUP (a, (b, c), d)", format!("{rollup}"));
12952    }
12953
12954    #[test]
12955    fn test_cube_display() {
12956        let cube = Expr::Cube(vec![vec![Expr::Identifier(Ident::new("a"))]]);
12957        assert_eq!("CUBE (a)", format!("{cube}"));
12958
12959        let cube = Expr::Cube(vec![vec![
12960            Expr::Identifier(Ident::new("a")),
12961            Expr::Identifier(Ident::new("b")),
12962        ]]);
12963        assert_eq!("CUBE ((a, b))", format!("{cube}"));
12964
12965        let cube = Expr::Cube(vec![
12966            vec![Expr::Identifier(Ident::new("a"))],
12967            vec![Expr::Identifier(Ident::new("b"))],
12968        ]);
12969        assert_eq!("CUBE (a, b)", format!("{cube}"));
12970
12971        let cube = Expr::Cube(vec![
12972            vec![Expr::Identifier(Ident::new("a"))],
12973            vec![
12974                Expr::Identifier(Ident::new("b")),
12975                Expr::Identifier(Ident::new("c")),
12976            ],
12977            vec![Expr::Identifier(Ident::new("d"))],
12978        ]);
12979        assert_eq!("CUBE (a, (b, c), d)", format!("{cube}"));
12980    }
12981
12982    #[test]
12983    fn test_interval_display() {
12984        let interval = Expr::Interval(Interval {
12985            value: Box::new(Expr::Value(
12986                Value::SingleQuotedString(String::from("123:45.67")).with_empty_span(),
12987            )),
12988            leading_field: Some(DateTimeField::Minute),
12989            leading_precision: Some(10),
12990            last_field: Some(DateTimeField::Second),
12991            fractional_seconds_precision: Some(9),
12992        });
12993        assert_eq!(
12994            "INTERVAL '123:45.67' MINUTE (10) TO SECOND (9)",
12995            format!("{interval}"),
12996        );
12997
12998        let interval = Expr::Interval(Interval {
12999            value: Box::new(Expr::Value(
13000                Value::SingleQuotedString(String::from("5")).with_empty_span(),
13001            )),
13002            leading_field: Some(DateTimeField::Second),
13003            leading_precision: Some(1),
13004            last_field: None,
13005            fractional_seconds_precision: Some(3),
13006        });
13007        assert_eq!("INTERVAL '5' SECOND (1, 3)", format!("{interval}"));
13008    }
13009
13010    #[test]
13011    fn test_one_or_many_with_parens_deref() {
13012        use core::ops::Index;
13013
13014        let one = OneOrManyWithParens::One("a");
13015
13016        assert_eq!(one.deref(), &["a"]);
13017        assert_eq!(<OneOrManyWithParens<_> as Deref>::deref(&one), &["a"]);
13018
13019        assert_eq!(one[0], "a");
13020        assert_eq!(one.index(0), &"a");
13021        assert_eq!(
13022            <<OneOrManyWithParens<_> as Deref>::Target as Index<usize>>::index(&one, 0),
13023            &"a"
13024        );
13025
13026        assert_eq!(one.len(), 1);
13027        assert_eq!(<OneOrManyWithParens<_> as Deref>::Target::len(&one), 1);
13028
13029        let many1 = OneOrManyWithParens::Many(vec!["b"]);
13030
13031        assert_eq!(many1.deref(), &["b"]);
13032        assert_eq!(<OneOrManyWithParens<_> as Deref>::deref(&many1), &["b"]);
13033
13034        assert_eq!(many1[0], "b");
13035        assert_eq!(many1.index(0), &"b");
13036        assert_eq!(
13037            <<OneOrManyWithParens<_> as Deref>::Target as Index<usize>>::index(&many1, 0),
13038            &"b"
13039        );
13040
13041        assert_eq!(many1.len(), 1);
13042        assert_eq!(<OneOrManyWithParens<_> as Deref>::Target::len(&many1), 1);
13043
13044        let many2 = OneOrManyWithParens::Many(vec!["c", "d"]);
13045
13046        assert_eq!(many2.deref(), &["c", "d"]);
13047        assert_eq!(
13048            <OneOrManyWithParens<_> as Deref>::deref(&many2),
13049            &["c", "d"]
13050        );
13051
13052        assert_eq!(many2[0], "c");
13053        assert_eq!(many2.index(0), &"c");
13054        assert_eq!(
13055            <<OneOrManyWithParens<_> as Deref>::Target as Index<usize>>::index(&many2, 0),
13056            &"c"
13057        );
13058
13059        assert_eq!(many2[1], "d");
13060        assert_eq!(many2.index(1), &"d");
13061        assert_eq!(
13062            <<OneOrManyWithParens<_> as Deref>::Target as Index<usize>>::index(&many2, 1),
13063            &"d"
13064        );
13065
13066        assert_eq!(many2.len(), 2);
13067        assert_eq!(<OneOrManyWithParens<_> as Deref>::Target::len(&many2), 2);
13068    }
13069
13070    #[test]
13071    fn test_one_or_many_with_parens_as_ref() {
13072        let one = OneOrManyWithParens::One("a");
13073
13074        assert_eq!(one.as_ref(), &["a"]);
13075        assert_eq!(<OneOrManyWithParens<_> as AsRef<_>>::as_ref(&one), &["a"]);
13076
13077        let many1 = OneOrManyWithParens::Many(vec!["b"]);
13078
13079        assert_eq!(many1.as_ref(), &["b"]);
13080        assert_eq!(<OneOrManyWithParens<_> as AsRef<_>>::as_ref(&many1), &["b"]);
13081
13082        let many2 = OneOrManyWithParens::Many(vec!["c", "d"]);
13083
13084        assert_eq!(many2.as_ref(), &["c", "d"]);
13085        assert_eq!(
13086            <OneOrManyWithParens<_> as AsRef<_>>::as_ref(&many2),
13087            &["c", "d"]
13088        );
13089    }
13090
13091    #[test]
13092    fn test_one_or_many_with_parens_ref_into_iter() {
13093        let one = OneOrManyWithParens::One("a");
13094
13095        assert_eq!(Vec::from_iter(&one), vec![&"a"]);
13096
13097        let many1 = OneOrManyWithParens::Many(vec!["b"]);
13098
13099        assert_eq!(Vec::from_iter(&many1), vec![&"b"]);
13100
13101        let many2 = OneOrManyWithParens::Many(vec!["c", "d"]);
13102
13103        assert_eq!(Vec::from_iter(&many2), vec![&"c", &"d"]);
13104    }
13105
13106    #[test]
13107    fn test_one_or_many_with_parens_value_into_iter() {
13108        use core::iter::once;
13109
13110        //tests that our iterator implemented methods behaves exactly as it's inner iterator, at every step up to n calls to next/next_back
13111        fn test_steps<I>(ours: OneOrManyWithParens<usize>, inner: I, n: usize)
13112        where
13113            I: IntoIterator<Item = usize, IntoIter: DoubleEndedIterator + Clone> + Clone,
13114        {
13115            fn checks<I>(ours: OneOrManyWithParensIntoIter<usize>, inner: I)
13116            where
13117                I: Iterator<Item = usize> + Clone + DoubleEndedIterator,
13118            {
13119                assert_eq!(ours.size_hint(), inner.size_hint());
13120                assert_eq!(ours.clone().count(), inner.clone().count());
13121
13122                assert_eq!(
13123                    ours.clone().fold(1, |a, v| a + v),
13124                    inner.clone().fold(1, |a, v| a + v)
13125                );
13126
13127                assert_eq!(Vec::from_iter(ours.clone()), Vec::from_iter(inner.clone()));
13128                assert_eq!(
13129                    Vec::from_iter(ours.clone().rev()),
13130                    Vec::from_iter(inner.clone().rev())
13131                );
13132            }
13133
13134            let mut ours_next = ours.clone().into_iter();
13135            let mut inner_next = inner.clone().into_iter();
13136
13137            for _ in 0..n {
13138                checks(ours_next.clone(), inner_next.clone());
13139
13140                assert_eq!(ours_next.next(), inner_next.next());
13141            }
13142
13143            let mut ours_next_back = ours.clone().into_iter();
13144            let mut inner_next_back = inner.clone().into_iter();
13145
13146            for _ in 0..n {
13147                checks(ours_next_back.clone(), inner_next_back.clone());
13148
13149                assert_eq!(ours_next_back.next_back(), inner_next_back.next_back());
13150            }
13151
13152            let mut ours_mixed = ours.clone().into_iter();
13153            let mut inner_mixed = inner.clone().into_iter();
13154
13155            for i in 0..n {
13156                checks(ours_mixed.clone(), inner_mixed.clone());
13157
13158                if i % 2 == 0 {
13159                    assert_eq!(ours_mixed.next_back(), inner_mixed.next_back());
13160                } else {
13161                    assert_eq!(ours_mixed.next(), inner_mixed.next());
13162                }
13163            }
13164
13165            let mut ours_mixed2 = ours.into_iter();
13166            let mut inner_mixed2 = inner.into_iter();
13167
13168            for i in 0..n {
13169                checks(ours_mixed2.clone(), inner_mixed2.clone());
13170
13171                if i % 2 == 0 {
13172                    assert_eq!(ours_mixed2.next(), inner_mixed2.next());
13173                } else {
13174                    assert_eq!(ours_mixed2.next_back(), inner_mixed2.next_back());
13175                }
13176            }
13177        }
13178
13179        test_steps(OneOrManyWithParens::One(1), once(1), 3);
13180        test_steps(OneOrManyWithParens::Many(vec![2]), vec![2], 3);
13181        test_steps(OneOrManyWithParens::Many(vec![3, 4]), vec![3, 4], 4);
13182    }
13183
13184    // Tests that the position in the code of an `Ident` does not affect its
13185    // ordering.
13186    #[test]
13187    fn test_ident_ord() {
13188        let mut a = Ident::with_span(Span::new(Location::new(1, 1), Location::new(1, 1)), "a");
13189        let mut b = Ident::with_span(Span::new(Location::new(2, 2), Location::new(2, 2)), "b");
13190
13191        assert!(a < b);
13192        std::mem::swap(&mut a.span, &mut b.span);
13193        assert!(a < b);
13194    }
13195}