Skip to main content

sqlparser/ast/
ddl.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//! AST types specific to CREATE/ALTER variants of [`Statement`](crate::ast::Statement)
19//! (commonly referred to as Data Definition Language, or DDL)
20
21#[cfg(not(feature = "std"))]
22use alloc::{
23    boxed::Box,
24    format,
25    string::{String, ToString},
26    vec,
27    vec::Vec,
28};
29use core::fmt::{self, Display, Write};
30
31#[cfg(feature = "serde")]
32use serde::{Deserialize, Serialize};
33
34#[cfg(feature = "visitor")]
35use sqlparser_derive::{Visit, VisitMut};
36
37use crate::ast::value::escape_single_quote_string;
38use crate::ast::{
39    display_comma_separated, display_separated,
40    table_constraints::{
41        CheckConstraint, ForeignKeyConstraint, PrimaryKeyConstraint, TableConstraint,
42        UniqueConstraint,
43    },
44    ArgMode, AttachedToken, CommentDef, ConditionalStatements, CreateFunctionBody,
45    CreateFunctionUsing, CreateTableLikeKind, CreateTableOptions, CreateViewParams, DataType, Expr,
46    FileFormat, FunctionBehavior, FunctionCalledOnNull, FunctionDefinitionSetParam, FunctionDesc,
47    FunctionDeterminismSpecifier, FunctionParallel, FunctionSecurity, HiveDistributionStyle,
48    HiveFormat, HiveIOFormat, HiveRowFormat, HiveSetLocation, Ident, InitializeKind,
49    MySQLColumnPosition, ObjectName, OnCommit, OneOrManyWithParens, OperateFunctionArg,
50    OrderByExpr, ProjectionSelect, Query, RefreshModeKind, ResetConfig, RowAccessPolicy,
51    SequenceOptions, Spanned, SqlOption, StorageLifecyclePolicy, StorageSerializationPolicy,
52    TableVersion, Tag, TriggerEvent, TriggerExecBody, TriggerObject, TriggerPeriod,
53    TriggerReferencing, Value, ValueWithSpan, WrappedCollection,
54};
55use crate::display_utils::{DisplayCommaSeparated, Indent, NewLine, SpaceOrNewline};
56use crate::keywords::Keyword;
57use crate::tokenizer::{Span, Token};
58
59/// Index column type.
60#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
61#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
62#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
63pub struct IndexColumn {
64    /// The indexed column expression.
65    pub column: OrderByExpr,
66    /// Optional operator class (index operator name).
67    pub operator_class: Option<ObjectName>,
68}
69
70impl From<Ident> for IndexColumn {
71    fn from(c: Ident) -> Self {
72        Self {
73            column: OrderByExpr::from(c),
74            operator_class: None,
75        }
76    }
77}
78
79impl<'a> From<&'a str> for IndexColumn {
80    fn from(c: &'a str) -> Self {
81        let ident = Ident::new(c);
82        ident.into()
83    }
84}
85
86impl fmt::Display for IndexColumn {
87    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
88        write!(f, "{}", self.column)?;
89        if let Some(operator_class) = &self.operator_class {
90            write!(f, " {operator_class}")?;
91        }
92        Ok(())
93    }
94}
95
96/// ALTER TABLE operation REPLICA IDENTITY values
97/// See [Postgres ALTER TABLE docs](https://www.postgresql.org/docs/current/sql-altertable.html)
98#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
99#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
100#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
101pub enum ReplicaIdentity {
102    /// No replica identity (`REPLICA IDENTITY NOTHING`).
103    Nothing,
104    /// Full replica identity (`REPLICA IDENTITY FULL`).
105    Full,
106    /// Default replica identity (`REPLICA IDENTITY DEFAULT`).
107    Default,
108    /// Use the given index as replica identity (`REPLICA IDENTITY USING INDEX`).
109    Index(Ident),
110}
111
112impl fmt::Display for ReplicaIdentity {
113    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
114        match self {
115            ReplicaIdentity::Nothing => f.write_str("NOTHING"),
116            ReplicaIdentity::Full => f.write_str("FULL"),
117            ReplicaIdentity::Default => f.write_str("DEFAULT"),
118            ReplicaIdentity::Index(idx) => write!(f, "USING INDEX {idx}"),
119        }
120    }
121}
122
123/// An `ALTER TABLE` (`Statement::AlterTable`) operation
124#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
125#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
126#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
127pub enum AlterTableOperation {
128    /// `ADD <table_constraint> [NOT VALID]`
129    AddConstraint {
130        /// The table constraint to add.
131        constraint: TableConstraint,
132        /// Whether the constraint should be marked `NOT VALID`.
133        not_valid: bool,
134    },
135    /// `ADD [COLUMN] [IF NOT EXISTS] <column_def>`
136    AddColumn {
137        /// `[COLUMN]`.
138        column_keyword: bool,
139        /// `[IF NOT EXISTS]`
140        if_not_exists: bool,
141        /// <column_def>.
142        column_def: ColumnDef,
143        /// MySQL `ALTER TABLE` only  [FIRST | AFTER column_name]
144        column_position: Option<MySQLColumnPosition>,
145    },
146    /// `ADD PROJECTION [IF NOT EXISTS] name ( SELECT <COLUMN LIST EXPR> [GROUP BY] [ORDER BY])`
147    ///
148    /// Note: this is a ClickHouse-specific operation.
149    /// Please refer to [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/projection#add-projection)
150    AddProjection {
151        /// Whether `IF NOT EXISTS` was specified.
152        if_not_exists: bool,
153        /// Name of the projection to add.
154        name: Ident,
155        /// The projection's select clause.
156        select: ProjectionSelect,
157    },
158    /// `DROP PROJECTION [IF EXISTS] name`
159    ///
160    /// Note: this is a ClickHouse-specific operation.
161    /// Please refer to [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/projection#drop-projection)
162    DropProjection {
163        /// Whether `IF EXISTS` was specified.
164        if_exists: bool,
165        /// Name of the projection to drop.
166        name: Ident,
167    },
168    /// `MATERIALIZE PROJECTION [IF EXISTS] name [IN PARTITION partition_name]`
169    ///
170    ///  Note: this is a ClickHouse-specific operation.
171    /// Please refer to [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/projection#materialize-projection)
172    MaterializeProjection {
173        /// Whether `IF EXISTS` was specified.
174        if_exists: bool,
175        /// Name of the projection to materialize.
176        name: Ident,
177        /// Optional partition name to operate on.
178        partition: Option<Ident>,
179    },
180    /// `CLEAR PROJECTION [IF EXISTS] name [IN PARTITION partition_name]`
181    ///
182    /// Note: this is a ClickHouse-specific operation.
183    /// Please refer to [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/projection#clear-projection)
184    ClearProjection {
185        /// Whether `IF EXISTS` was specified.
186        if_exists: bool,
187        /// Name of the projection to clear.
188        name: Ident,
189        /// Optional partition name to operate on.
190        partition: Option<Ident>,
191    },
192    /// `DISABLE ROW LEVEL SECURITY`
193    ///
194    /// Note: this is a PostgreSQL-specific operation.
195    /// Please refer to [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-altertable.html)
196    DisableRowLevelSecurity,
197    /// `DISABLE RULE rewrite_rule_name`
198    ///
199    /// Note: this is a PostgreSQL-specific operation.
200    DisableRule {
201        /// Name of the rule to disable.
202        name: Ident,
203    },
204    /// `DISABLE TRIGGER [ trigger_name | ALL | USER ]`
205    ///
206    /// Note: this is a PostgreSQL-specific operation.
207    DisableTrigger {
208        /// Name of the trigger to disable (or ALL/USER).
209        name: Ident,
210    },
211    /// `DROP CONSTRAINT [ IF EXISTS ] <name>`
212    DropConstraint {
213        /// `IF EXISTS` flag for dropping the constraint.
214        if_exists: bool,
215        /// Name of the constraint to drop.
216        name: Ident,
217        /// Optional drop behavior (`CASCADE`/`RESTRICT`).
218        drop_behavior: Option<DropBehavior>,
219    },
220    /// `DROP [ COLUMN ] [ IF EXISTS ] <column_name> [ , <column_name>, ... ] [ CASCADE ]`
221    DropColumn {
222        /// Whether the `COLUMN` keyword was present.
223        has_column_keyword: bool,
224        /// Names of columns to drop.
225        column_names: Vec<Ident>,
226        /// Whether `IF EXISTS` was specified for the columns.
227        if_exists: bool,
228        /// Optional drop behavior for the column removal.
229        drop_behavior: Option<DropBehavior>,
230    },
231    /// `ATTACH PART|PARTITION <partition_expr>`
232    /// Note: this is a ClickHouse-specific operation, please refer to
233    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/partition#attach-partitionpart)
234    AttachPartition {
235        // PART is not a short form of PARTITION, it's a separate keyword
236        // which represents a physical file on disk and partition is a logical entity.
237        /// Partition expression to attach.
238        partition: Partition,
239    },
240    /// `DETACH PART|PARTITION <partition_expr>`
241    /// Note: this is a ClickHouse-specific operation, please refer to
242    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/partition#detach-partitionpart)
243    DetachPartition {
244        // See `AttachPartition` for more details
245        /// Partition expression to detach.
246        partition: Partition,
247    },
248    /// `FREEZE PARTITION <partition_expr>`
249    /// Note: this is a ClickHouse-specific operation, please refer to
250    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/partition#freeze-partition)
251    FreezePartition {
252        /// Partition to freeze.
253        partition: Partition,
254        /// Optional name for the freeze operation.
255        with_name: Option<Ident>,
256    },
257    /// `UNFREEZE PARTITION <partition_expr>`
258    /// Note: this is a ClickHouse-specific operation, please refer to
259    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/partition#unfreeze-partition)
260    UnfreezePartition {
261        /// Partition to unfreeze.
262        partition: Partition,
263        /// Optional name associated with the unfreeze operation.
264        with_name: Option<Ident>,
265    },
266    /// `DROP PRIMARY KEY`
267    ///
268    /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/alter-table.html)
269    /// [Snowflake](https://docs.snowflake.com/en/sql-reference/constraints-drop)
270    DropPrimaryKey {
271        /// Optional drop behavior for the primary key (`CASCADE`/`RESTRICT`).
272        drop_behavior: Option<DropBehavior>,
273    },
274    /// `DROP FOREIGN KEY <fk_symbol>`
275    ///
276    /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/alter-table.html)
277    /// [Snowflake](https://docs.snowflake.com/en/sql-reference/constraints-drop)
278    DropForeignKey {
279        /// Foreign key symbol/name to drop.
280        name: Ident,
281        /// Optional drop behavior for the foreign key.
282        drop_behavior: Option<DropBehavior>,
283    },
284    /// `DROP INDEX <index_name>`
285    ///
286    /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/alter-table.html
287    DropIndex {
288        /// Name of the index to drop.
289        name: Ident,
290    },
291    /// `ENABLE ALWAYS RULE rewrite_rule_name`
292    ///
293    /// Note: this is a PostgreSQL-specific operation.
294    EnableAlwaysRule {
295        /// Name of the rule to enable.
296        name: Ident,
297    },
298    /// `ENABLE ALWAYS TRIGGER trigger_name`
299    ///
300    /// Note: this is a PostgreSQL-specific operation.
301    EnableAlwaysTrigger {
302        /// Name of the trigger to enable.
303        name: Ident,
304    },
305    /// `ENABLE REPLICA RULE rewrite_rule_name`
306    ///
307    /// Note: this is a PostgreSQL-specific operation.
308    EnableReplicaRule {
309        /// Name of the replica rule to enable.
310        name: Ident,
311    },
312    /// `ENABLE REPLICA TRIGGER trigger_name`
313    ///
314    /// Note: this is a PostgreSQL-specific operation.
315    EnableReplicaTrigger {
316        /// Name of the replica trigger to enable.
317        name: Ident,
318    },
319    /// `ENABLE ROW LEVEL SECURITY`
320    ///
321    /// Note: this is a PostgreSQL-specific operation.
322    /// Please refer to [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-altertable.html)
323    EnableRowLevelSecurity,
324    /// `FORCE ROW LEVEL SECURITY`
325    ///
326    /// Note: this is a PostgreSQL-specific operation.
327    /// Please refer to [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-altertable.html)
328    ForceRowLevelSecurity,
329    /// `NO FORCE ROW LEVEL SECURITY`
330    ///
331    /// Note: this is a PostgreSQL-specific operation.
332    /// Please refer to [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-altertable.html)
333    NoForceRowLevelSecurity,
334    /// `ENABLE RULE rewrite_rule_name`
335    ///
336    /// Note: this is a PostgreSQL-specific operation.
337    EnableRule {
338        /// Name of the rule to enable.
339        name: Ident,
340    },
341    /// `ENABLE TRIGGER [ trigger_name | ALL | USER ]`
342    ///
343    /// Note: this is a PostgreSQL-specific operation.
344    EnableTrigger {
345        /// Name of the trigger to enable (or ALL/USER).
346        name: Ident,
347    },
348    /// `RENAME TO PARTITION (partition=val)`
349    RenamePartitions {
350        /// Old partition expressions to be renamed.
351        old_partitions: Vec<Expr>,
352        /// New partition expressions corresponding to the old ones.
353        new_partitions: Vec<Expr>,
354    },
355    /// REPLICA IDENTITY { DEFAULT | USING INDEX index_name | FULL | NOTHING }
356    ///
357    /// Note: this is a PostgreSQL-specific operation.
358    /// Please refer to [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-altertable.html)
359    ReplicaIdentity {
360        /// Replica identity setting to apply.
361        identity: ReplicaIdentity,
362    },
363    /// Add Partitions
364    AddPartitions {
365        /// Whether `IF NOT EXISTS` was present when adding partitions.
366        if_not_exists: bool,
367        /// New partitions to add.
368        new_partitions: Vec<Partition>,
369    },
370    /// `DROP PARTITIONS ...` / drop partitions from the table.
371    DropPartitions {
372        /// Partitions to drop (expressions).
373        partitions: Vec<Expr>,
374        /// Whether `IF EXISTS` was specified for dropping partitions.
375        if_exists: bool,
376    },
377    /// `RENAME [ COLUMN ] <old_column_name> TO <new_column_name>`
378    RenameColumn {
379        /// Existing column name to rename.
380        old_column_name: Ident,
381        /// New column name.
382        new_column_name: Ident,
383    },
384    /// `RENAME TO <table_name>`
385    RenameTable {
386        /// The new table name or renaming kind.
387        table_name: RenameTableNameKind,
388    },
389    // CHANGE [ COLUMN ] <old_name> <new_name> <data_type> [ <options> ]
390    /// Change an existing column's name, type, and options.
391    ChangeColumn {
392        /// Old column name.
393        old_name: Ident,
394        /// New column name.
395        new_name: Ident,
396        /// New data type for the column.
397        data_type: DataType,
398        /// Column options to apply after the change.
399        options: Vec<ColumnOption>,
400        /// MySQL-specific column position (`FIRST`/`AFTER`).
401        column_position: Option<MySQLColumnPosition>,
402    },
403    // CHANGE [ COLUMN ] <col_name> <data_type> [ <options> ]
404    /// Modify an existing column's type and options.
405    ModifyColumn {
406        /// Column name to modify.
407        col_name: Ident,
408        /// New data type for the column.
409        data_type: DataType,
410        /// Column options to set.
411        options: Vec<ColumnOption>,
412        /// MySQL-specific column position (`FIRST`/`AFTER`).
413        column_position: Option<MySQLColumnPosition>,
414    },
415    /// `RENAME CONSTRAINT <old_constraint_name> TO <new_constraint_name>`
416    ///
417    /// Note: this is a PostgreSQL-specific operation.
418    /// Rename a constraint on the table.
419    RenameConstraint {
420        /// Existing constraint name.
421        old_name: Ident,
422        /// New constraint name.
423        new_name: Ident,
424    },
425    /// `ALTER [ COLUMN ]`
426    /// Alter a specific column with the provided operation.
427    AlterColumn {
428        /// The column to alter.
429        column_name: Ident,
430        /// Operation to apply to the column.
431        op: AlterColumnOperation,
432    },
433    /// 'SWAP WITH <table_name>'
434    ///
435    /// Note: this is Snowflake specific <https://docs.snowflake.com/en/sql-reference/sql/alter-table>
436    SwapWith {
437        /// Table name to swap with.
438        table_name: ObjectName,
439    },
440    /// 'SET TBLPROPERTIES ( { property_key [ = ] property_val } [, ...] )'
441    SetTblProperties {
442        /// Table properties specified as SQL options.
443        table_properties: Vec<SqlOption>,
444    },
445    /// `OWNER TO { <new_owner> | CURRENT_ROLE | CURRENT_USER | SESSION_USER }`
446    ///
447    /// Note: this is PostgreSQL-specific <https://www.postgresql.org/docs/current/sql-altertable.html>
448    OwnerTo {
449        /// The new owner to assign to the table.
450        new_owner: Owner,
451    },
452    /// Snowflake table clustering options
453    /// <https://docs.snowflake.com/en/sql-reference/sql/alter-table#clustering-actions-clusteringaction>
454    ClusterBy {
455        /// Expressions used for clustering the table.
456        exprs: Vec<Expr>,
457    },
458    /// Remove the clustering key from the table.
459    DropClusteringKey,
460    /// Redshift `ALTER SORTKEY (column_list)`
461    /// <https://docs.aws.amazon.com/redshift/latest/dg/r_ALTER_TABLE.html>
462    AlterSortKey {
463        /// Column references in the sort key.
464        columns: Vec<Expr>,
465    },
466    /// Suspend background reclustering operations.
467    SuspendRecluster,
468    /// Resume background reclustering operations.
469    ResumeRecluster,
470    /// `REFRESH [ '<subpath>' ]`
471    ///
472    /// Note: this is Snowflake specific for dynamic/external tables
473    /// <https://docs.snowflake.com/en/sql-reference/sql/alter-dynamic-table>
474    /// <https://docs.snowflake.com/en/sql-reference/sql/alter-external-table>
475    Refresh {
476        /// Optional subpath for external table refresh
477        subpath: Option<String>,
478    },
479    /// `SUSPEND`
480    ///
481    /// Note: this is Snowflake specific for dynamic tables <https://docs.snowflake.com/en/sql-reference/sql/alter-table>
482    Suspend,
483    /// `RESUME`
484    ///
485    /// Note: this is Snowflake specific for dynamic tables <https://docs.snowflake.com/en/sql-reference/sql/alter-table>
486    Resume,
487    /// `ALGORITHM [=] { DEFAULT | INSTANT | INPLACE | COPY }`
488    ///
489    /// [MySQL]-specific table alter algorithm.
490    ///
491    /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/alter-table.html
492    Algorithm {
493        /// Whether the `=` sign was used (`ALGORITHM = ...`).
494        equals: bool,
495        /// The algorithm to use for the alter operation (MySQL-specific).
496        algorithm: AlterTableAlgorithm,
497    },
498
499    /// `LOCK [=] { DEFAULT | NONE | SHARED | EXCLUSIVE }`
500    ///
501    /// [MySQL]-specific table alter lock.
502    ///
503    /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/alter-table.html
504    Lock {
505        /// Whether the `=` sign was used (`LOCK = ...`).
506        equals: bool,
507        /// The locking behavior to apply (MySQL-specific).
508        lock: AlterTableLock,
509    },
510    /// `AUTO_INCREMENT [=] <value>`
511    ///
512    /// [MySQL]-specific table option for raising current auto increment value.
513    ///
514    /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/alter-table.html
515    AutoIncrement {
516        /// Whether the `=` sign was used (`AUTO_INCREMENT = ...`).
517        equals: bool,
518        /// Value to set for the auto-increment counter.
519        value: ValueWithSpan,
520    },
521    /// `VALIDATE CONSTRAINT <name>`
522    ValidateConstraint {
523        /// Name of the constraint to validate.
524        name: Ident,
525    },
526    /// Arbitrary parenthesized `SET` options.
527    ///
528    /// Example:
529    /// ```sql
530    /// SET (scale_factor = 0.01, threshold = 500)`
531    /// ```
532    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-altertable.html)
533    SetOptionsParens {
534        /// Parenthesized options supplied to `SET (...)`.
535        options: Vec<SqlOption>,
536    },
537}
538
539/// An `ALTER Policy` (`Statement::AlterPolicy`) operation
540///
541/// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-altertable.html)
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 enum AlterPolicyOperation {
546    /// Rename the policy to `new_name`.
547    Rename {
548        /// The new identifier for the policy.
549        new_name: Ident,
550    },
551    /// Apply/modify policy properties.
552    Apply {
553        /// Optional list of owners the policy applies to.
554        to: Option<Vec<Owner>>,
555        /// Optional `USING` expression for the policy.
556        using: Option<Expr>,
557        /// Optional `WITH CHECK` expression for the policy.
558        with_check: Option<Expr>,
559    },
560}
561
562impl fmt::Display for AlterPolicyOperation {
563    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
564        match self {
565            AlterPolicyOperation::Rename { new_name } => {
566                write!(f, " RENAME TO {new_name}")
567            }
568            AlterPolicyOperation::Apply {
569                to,
570                using,
571                with_check,
572            } => {
573                if let Some(to) = to {
574                    write!(f, " TO {}", display_comma_separated(to))?;
575                }
576                if let Some(using) = using {
577                    write!(f, " USING ({using})")?;
578                }
579                if let Some(with_check) = with_check {
580                    write!(f, " WITH CHECK ({with_check})")?;
581                }
582                Ok(())
583            }
584        }
585    }
586}
587
588/// [MySQL] `ALTER TABLE` algorithm.
589///
590/// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/alter-table.html
591#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
592#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
593#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
594/// Algorithm option for `ALTER TABLE` operations (MySQL-specific).
595pub enum AlterTableAlgorithm {
596    /// Default algorithm selection.
597    Default,
598    /// `INSTANT` algorithm.
599    Instant,
600    /// `INPLACE` algorithm.
601    Inplace,
602    /// `COPY` algorithm.
603    Copy,
604}
605
606impl fmt::Display for AlterTableAlgorithm {
607    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
608        f.write_str(match self {
609            Self::Default => "DEFAULT",
610            Self::Instant => "INSTANT",
611            Self::Inplace => "INPLACE",
612            Self::Copy => "COPY",
613        })
614    }
615}
616
617/// [MySQL] `ALTER TABLE` lock.
618///
619/// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/alter-table.html
620#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
621#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
622#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
623/// Locking behavior for `ALTER TABLE` (MySQL-specific).
624pub enum AlterTableLock {
625    /// `DEFAULT` lock behavior.
626    Default,
627    /// `NONE` lock.
628    None,
629    /// `SHARED` lock.
630    Shared,
631    /// `EXCLUSIVE` lock.
632    Exclusive,
633}
634
635impl fmt::Display for AlterTableLock {
636    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
637        f.write_str(match self {
638            Self::Default => "DEFAULT",
639            Self::None => "NONE",
640            Self::Shared => "SHARED",
641            Self::Exclusive => "EXCLUSIVE",
642        })
643    }
644}
645
646#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
647#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
648#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
649/// New owner specification for `ALTER TABLE ... OWNER TO ...`
650pub enum Owner {
651    /// A specific user/role identifier.
652    Ident(Ident),
653    /// `CURRENT_ROLE` keyword.
654    CurrentRole,
655    /// `CURRENT_USER` keyword.
656    CurrentUser,
657    /// `SESSION_USER` keyword.
658    SessionUser,
659}
660
661impl fmt::Display for Owner {
662    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
663        match self {
664            Owner::Ident(ident) => write!(f, "{ident}"),
665            Owner::CurrentRole => write!(f, "CURRENT_ROLE"),
666            Owner::CurrentUser => write!(f, "CURRENT_USER"),
667            Owner::SessionUser => write!(f, "SESSION_USER"),
668        }
669    }
670}
671
672#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
673#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
674#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
675/// New connector owner specification for `ALTER CONNECTOR ... OWNER TO ...`
676pub enum AlterConnectorOwner {
677    /// `USER <ident>` connector owner.
678    User(Ident),
679    /// `ROLE <ident>` connector owner.
680    Role(Ident),
681}
682
683impl fmt::Display for AlterConnectorOwner {
684    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
685        match self {
686            AlterConnectorOwner::User(ident) => write!(f, "USER {ident}"),
687            AlterConnectorOwner::Role(ident) => write!(f, "ROLE {ident}"),
688        }
689    }
690}
691
692#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
693#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
694#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
695/// Alterations that can be applied to an index.
696pub enum AlterIndexOperation {
697    /// Rename the index to `index_name`.
698    RenameIndex {
699        /// The new name for the index.
700        index_name: ObjectName,
701    },
702}
703
704impl fmt::Display for AlterTableOperation {
705    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
706        match self {
707            AlterTableOperation::AddPartitions {
708                if_not_exists,
709                new_partitions,
710            } => write!(
711                f,
712                "ADD{ine} {}",
713                display_separated(new_partitions, " "),
714                ine = if *if_not_exists { " IF NOT EXISTS" } else { "" }
715            ),
716            AlterTableOperation::AddConstraint {
717                not_valid,
718                constraint,
719            } => {
720                write!(f, "ADD {constraint}")?;
721                if *not_valid {
722                    write!(f, " NOT VALID")?;
723                }
724                Ok(())
725            }
726            AlterTableOperation::AddColumn {
727                column_keyword,
728                if_not_exists,
729                column_def,
730                column_position,
731            } => {
732                write!(f, "ADD")?;
733                if *column_keyword {
734                    write!(f, " COLUMN")?;
735                }
736                if *if_not_exists {
737                    write!(f, " IF NOT EXISTS")?;
738                }
739                write!(f, " {column_def}")?;
740
741                if let Some(position) = column_position {
742                    write!(f, " {position}")?;
743                }
744
745                Ok(())
746            }
747            AlterTableOperation::AddProjection {
748                if_not_exists,
749                name,
750                select: query,
751            } => {
752                write!(f, "ADD PROJECTION")?;
753                if *if_not_exists {
754                    write!(f, " IF NOT EXISTS")?;
755                }
756                write!(f, " {name} ({query})")
757            }
758            AlterTableOperation::Algorithm { equals, algorithm } => {
759                write!(
760                    f,
761                    "ALGORITHM {}{}",
762                    if *equals { "= " } else { "" },
763                    algorithm
764                )
765            }
766            AlterTableOperation::DropProjection { if_exists, name } => {
767                write!(f, "DROP PROJECTION")?;
768                if *if_exists {
769                    write!(f, " IF EXISTS")?;
770                }
771                write!(f, " {name}")
772            }
773            AlterTableOperation::MaterializeProjection {
774                if_exists,
775                name,
776                partition,
777            } => {
778                write!(f, "MATERIALIZE PROJECTION")?;
779                if *if_exists {
780                    write!(f, " IF EXISTS")?;
781                }
782                write!(f, " {name}")?;
783                if let Some(partition) = partition {
784                    write!(f, " IN PARTITION {partition}")?;
785                }
786                Ok(())
787            }
788            AlterTableOperation::ClearProjection {
789                if_exists,
790                name,
791                partition,
792            } => {
793                write!(f, "CLEAR PROJECTION")?;
794                if *if_exists {
795                    write!(f, " IF EXISTS")?;
796                }
797                write!(f, " {name}")?;
798                if let Some(partition) = partition {
799                    write!(f, " IN PARTITION {partition}")?;
800                }
801                Ok(())
802            }
803            AlterTableOperation::AlterColumn { column_name, op } => {
804                write!(f, "ALTER COLUMN {column_name} {op}")
805            }
806            AlterTableOperation::DisableRowLevelSecurity => {
807                write!(f, "DISABLE ROW LEVEL SECURITY")
808            }
809            AlterTableOperation::DisableRule { name } => {
810                write!(f, "DISABLE RULE {name}")
811            }
812            AlterTableOperation::DisableTrigger { name } => {
813                write!(f, "DISABLE TRIGGER {name}")
814            }
815            AlterTableOperation::DropPartitions {
816                partitions,
817                if_exists,
818            } => write!(
819                f,
820                "DROP{ie} PARTITION ({})",
821                display_comma_separated(partitions),
822                ie = if *if_exists { " IF EXISTS" } else { "" }
823            ),
824            AlterTableOperation::DropConstraint {
825                if_exists,
826                name,
827                drop_behavior,
828            } => {
829                write!(
830                    f,
831                    "DROP CONSTRAINT {}{}",
832                    if *if_exists { "IF EXISTS " } else { "" },
833                    name
834                )?;
835                if let Some(drop_behavior) = drop_behavior {
836                    write!(f, " {drop_behavior}")?;
837                }
838                Ok(())
839            }
840            AlterTableOperation::DropPrimaryKey { drop_behavior } => {
841                write!(f, "DROP PRIMARY KEY")?;
842                if let Some(drop_behavior) = drop_behavior {
843                    write!(f, " {drop_behavior}")?;
844                }
845                Ok(())
846            }
847            AlterTableOperation::DropForeignKey {
848                name,
849                drop_behavior,
850            } => {
851                write!(f, "DROP FOREIGN KEY {name}")?;
852                if let Some(drop_behavior) = drop_behavior {
853                    write!(f, " {drop_behavior}")?;
854                }
855                Ok(())
856            }
857            AlterTableOperation::DropIndex { name } => write!(f, "DROP INDEX {name}"),
858            AlterTableOperation::DropColumn {
859                has_column_keyword,
860                column_names: column_name,
861                if_exists,
862                drop_behavior,
863            } => {
864                write!(
865                    f,
866                    "DROP {}{}{}",
867                    if *has_column_keyword { "COLUMN " } else { "" },
868                    if *if_exists { "IF EXISTS " } else { "" },
869                    display_comma_separated(column_name),
870                )?;
871                if let Some(drop_behavior) = drop_behavior {
872                    write!(f, " {drop_behavior}")?;
873                }
874                Ok(())
875            }
876            AlterTableOperation::AttachPartition { partition } => {
877                write!(f, "ATTACH {partition}")
878            }
879            AlterTableOperation::DetachPartition { partition } => {
880                write!(f, "DETACH {partition}")
881            }
882            AlterTableOperation::EnableAlwaysRule { name } => {
883                write!(f, "ENABLE ALWAYS RULE {name}")
884            }
885            AlterTableOperation::EnableAlwaysTrigger { name } => {
886                write!(f, "ENABLE ALWAYS TRIGGER {name}")
887            }
888            AlterTableOperation::EnableReplicaRule { name } => {
889                write!(f, "ENABLE REPLICA RULE {name}")
890            }
891            AlterTableOperation::EnableReplicaTrigger { name } => {
892                write!(f, "ENABLE REPLICA TRIGGER {name}")
893            }
894            AlterTableOperation::EnableRowLevelSecurity => {
895                write!(f, "ENABLE ROW LEVEL SECURITY")
896            }
897            AlterTableOperation::ForceRowLevelSecurity => {
898                write!(f, "FORCE ROW LEVEL SECURITY")
899            }
900            AlterTableOperation::NoForceRowLevelSecurity => {
901                write!(f, "NO FORCE ROW LEVEL SECURITY")
902            }
903            AlterTableOperation::EnableRule { name } => {
904                write!(f, "ENABLE RULE {name}")
905            }
906            AlterTableOperation::EnableTrigger { name } => {
907                write!(f, "ENABLE TRIGGER {name}")
908            }
909            AlterTableOperation::RenamePartitions {
910                old_partitions,
911                new_partitions,
912            } => write!(
913                f,
914                "PARTITION ({}) RENAME TO PARTITION ({})",
915                display_comma_separated(old_partitions),
916                display_comma_separated(new_partitions)
917            ),
918            AlterTableOperation::RenameColumn {
919                old_column_name,
920                new_column_name,
921            } => write!(f, "RENAME COLUMN {old_column_name} TO {new_column_name}"),
922            AlterTableOperation::RenameTable { table_name } => {
923                write!(f, "RENAME {table_name}")
924            }
925            AlterTableOperation::ChangeColumn {
926                old_name,
927                new_name,
928                data_type,
929                options,
930                column_position,
931            } => {
932                write!(f, "CHANGE COLUMN {old_name} {new_name} {data_type}")?;
933                if !options.is_empty() {
934                    write!(f, " {}", display_separated(options, " "))?;
935                }
936                if let Some(position) = column_position {
937                    write!(f, " {position}")?;
938                }
939
940                Ok(())
941            }
942            AlterTableOperation::ModifyColumn {
943                col_name,
944                data_type,
945                options,
946                column_position,
947            } => {
948                write!(f, "MODIFY COLUMN {col_name} {data_type}")?;
949                if !options.is_empty() {
950                    write!(f, " {}", display_separated(options, " "))?;
951                }
952                if let Some(position) = column_position {
953                    write!(f, " {position}")?;
954                }
955
956                Ok(())
957            }
958            AlterTableOperation::RenameConstraint { old_name, new_name } => {
959                write!(f, "RENAME CONSTRAINT {old_name} TO {new_name}")
960            }
961            AlterTableOperation::SwapWith { table_name } => {
962                write!(f, "SWAP WITH {table_name}")
963            }
964            AlterTableOperation::OwnerTo { new_owner } => {
965                write!(f, "OWNER TO {new_owner}")
966            }
967            AlterTableOperation::SetTblProperties { table_properties } => {
968                write!(
969                    f,
970                    "SET TBLPROPERTIES({})",
971                    display_comma_separated(table_properties)
972                )
973            }
974            AlterTableOperation::FreezePartition {
975                partition,
976                with_name,
977            } => {
978                write!(f, "FREEZE {partition}")?;
979                if let Some(name) = with_name {
980                    write!(f, " WITH NAME {name}")?;
981                }
982                Ok(())
983            }
984            AlterTableOperation::UnfreezePartition {
985                partition,
986                with_name,
987            } => {
988                write!(f, "UNFREEZE {partition}")?;
989                if let Some(name) = with_name {
990                    write!(f, " WITH NAME {name}")?;
991                }
992                Ok(())
993            }
994            AlterTableOperation::ClusterBy { exprs } => {
995                write!(f, "CLUSTER BY ({})", display_comma_separated(exprs))?;
996                Ok(())
997            }
998            AlterTableOperation::DropClusteringKey => {
999                write!(f, "DROP CLUSTERING KEY")?;
1000                Ok(())
1001            }
1002            AlterTableOperation::AlterSortKey { columns } => {
1003                write!(f, "ALTER SORTKEY({})", display_comma_separated(columns))?;
1004                Ok(())
1005            }
1006            AlterTableOperation::SuspendRecluster => {
1007                write!(f, "SUSPEND RECLUSTER")?;
1008                Ok(())
1009            }
1010            AlterTableOperation::ResumeRecluster => {
1011                write!(f, "RESUME RECLUSTER")?;
1012                Ok(())
1013            }
1014            AlterTableOperation::Refresh { subpath } => {
1015                write!(f, "REFRESH")?;
1016                if let Some(path) = subpath {
1017                    write!(f, " '{path}'")?;
1018                }
1019                Ok(())
1020            }
1021            AlterTableOperation::Suspend => {
1022                write!(f, "SUSPEND")
1023            }
1024            AlterTableOperation::Resume => {
1025                write!(f, "RESUME")
1026            }
1027            AlterTableOperation::AutoIncrement { equals, value } => {
1028                write!(
1029                    f,
1030                    "AUTO_INCREMENT {}{}",
1031                    if *equals { "= " } else { "" },
1032                    value
1033                )
1034            }
1035            AlterTableOperation::Lock { equals, lock } => {
1036                write!(f, "LOCK {}{}", if *equals { "= " } else { "" }, lock)
1037            }
1038            AlterTableOperation::ReplicaIdentity { identity } => {
1039                write!(f, "REPLICA IDENTITY {identity}")
1040            }
1041            AlterTableOperation::ValidateConstraint { name } => {
1042                write!(f, "VALIDATE CONSTRAINT {name}")
1043            }
1044            AlterTableOperation::SetOptionsParens { options } => {
1045                write!(f, "SET ({})", display_comma_separated(options))
1046            }
1047        }
1048    }
1049}
1050
1051impl fmt::Display for AlterIndexOperation {
1052    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1053        match self {
1054            AlterIndexOperation::RenameIndex { index_name } => {
1055                write!(f, "RENAME TO {index_name}")
1056            }
1057        }
1058    }
1059}
1060
1061/// An `ALTER TYPE` statement (`Statement::AlterType`)
1062#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1063#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1064#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1065pub struct AlterType {
1066    /// Name of the type being altered (may be schema-qualified).
1067    pub name: ObjectName,
1068    /// The specific alteration operation to perform.
1069    pub operation: AlterTypeOperation,
1070}
1071
1072/// An [AlterType] operation
1073#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1074#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1075#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1076pub enum AlterTypeOperation {
1077    /// Rename the type.
1078    Rename(AlterTypeRename),
1079    /// Add a new value to the type (for enum-like types).
1080    AddValue(AlterTypeAddValue),
1081    /// Rename an existing value of the type.
1082    RenameValue(AlterTypeRenameValue),
1083}
1084
1085/// See [AlterTypeOperation::Rename]
1086#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1087#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1088#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1089pub struct AlterTypeRename {
1090    /// The new name for the type.
1091    pub new_name: Ident,
1092}
1093
1094/// See [AlterTypeOperation::AddValue]
1095#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1096#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1097#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1098pub struct AlterTypeAddValue {
1099    /// If true, do not error when the value already exists (`IF NOT EXISTS`).
1100    pub if_not_exists: bool,
1101    /// The identifier for the new value to add.
1102    pub value: Ident,
1103    /// Optional relative position for the new value (`BEFORE` / `AFTER`).
1104    pub position: Option<AlterTypeAddValuePosition>,
1105}
1106
1107/// See [AlterTypeAddValue]
1108#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1109#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1110#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1111pub enum AlterTypeAddValuePosition {
1112    /// Place the new value before the given neighbor value.
1113    Before(Ident),
1114    /// Place the new value after the given neighbor value.
1115    After(Ident),
1116}
1117
1118/// See [AlterTypeOperation::RenameValue]
1119#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1120#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1121#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1122pub struct AlterTypeRenameValue {
1123    /// Existing value identifier to rename.
1124    pub from: Ident,
1125    /// New identifier for the value.
1126    pub to: Ident,
1127}
1128
1129impl fmt::Display for AlterTypeOperation {
1130    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1131        match self {
1132            Self::Rename(AlterTypeRename { new_name }) => {
1133                write!(f, "RENAME TO {new_name}")
1134            }
1135            Self::AddValue(AlterTypeAddValue {
1136                if_not_exists,
1137                value,
1138                position,
1139            }) => {
1140                write!(f, "ADD VALUE")?;
1141                if *if_not_exists {
1142                    write!(f, " IF NOT EXISTS")?;
1143                }
1144                write!(f, " {value}")?;
1145                match position {
1146                    Some(AlterTypeAddValuePosition::Before(neighbor_value)) => {
1147                        write!(f, " BEFORE {neighbor_value}")?;
1148                    }
1149                    Some(AlterTypeAddValuePosition::After(neighbor_value)) => {
1150                        write!(f, " AFTER {neighbor_value}")?;
1151                    }
1152                    None => {}
1153                };
1154                Ok(())
1155            }
1156            Self::RenameValue(AlterTypeRenameValue { from, to }) => {
1157                write!(f, "RENAME VALUE {from} TO {to}")
1158            }
1159        }
1160    }
1161}
1162
1163/// `ALTER OPERATOR` statement
1164/// See <https://www.postgresql.org/docs/current/sql-alteroperator.html>
1165#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1166#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1167#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1168pub struct AlterOperator {
1169    /// Operator name (can be schema-qualified)
1170    pub name: ObjectName,
1171    /// Left operand type (`None` if no left operand)
1172    pub left_type: Option<DataType>,
1173    /// Right operand type
1174    pub right_type: DataType,
1175    /// The operation to perform
1176    pub operation: AlterOperatorOperation,
1177}
1178
1179/// An [AlterOperator] operation
1180#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1181#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1182#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1183pub enum AlterOperatorOperation {
1184    /// `OWNER TO { new_owner | CURRENT_ROLE | CURRENT_USER | SESSION_USER }`
1185    OwnerTo(Owner),
1186    /// `SET SCHEMA new_schema`
1187    /// Set the operator's schema name.
1188    SetSchema {
1189        /// New schema name for the operator
1190        schema_name: ObjectName,
1191    },
1192    /// `SET ( options )`
1193    Set {
1194        /// List of operator options to set
1195        options: Vec<OperatorOption>,
1196    },
1197}
1198
1199/// Option for `ALTER OPERATOR SET` operation
1200#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1201#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1202#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1203pub enum OperatorOption {
1204    /// `RESTRICT = { res_proc | NONE }`
1205    Restrict(Option<ObjectName>),
1206    /// `JOIN = { join_proc | NONE }`
1207    Join(Option<ObjectName>),
1208    /// `COMMUTATOR = com_op`
1209    Commutator(ObjectName),
1210    /// `NEGATOR = neg_op`
1211    Negator(ObjectName),
1212    /// `HASHES`
1213    Hashes,
1214    /// `MERGES`
1215    Merges,
1216}
1217
1218impl fmt::Display for AlterOperator {
1219    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1220        write!(f, "ALTER OPERATOR {} (", self.name)?;
1221        if let Some(left_type) = &self.left_type {
1222            write!(f, "{}", left_type)?;
1223        } else {
1224            write!(f, "NONE")?;
1225        }
1226        write!(f, ", {}) {}", self.right_type, self.operation)
1227    }
1228}
1229
1230impl fmt::Display for AlterOperatorOperation {
1231    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1232        match self {
1233            Self::OwnerTo(owner) => write!(f, "OWNER TO {}", owner),
1234            Self::SetSchema { schema_name } => write!(f, "SET SCHEMA {}", schema_name),
1235            Self::Set { options } => {
1236                write!(f, "SET (")?;
1237                for (i, option) in options.iter().enumerate() {
1238                    if i > 0 {
1239                        write!(f, ", ")?;
1240                    }
1241                    write!(f, "{}", option)?;
1242                }
1243                write!(f, ")")
1244            }
1245        }
1246    }
1247}
1248
1249impl fmt::Display for OperatorOption {
1250    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1251        match self {
1252            Self::Restrict(Some(proc_name)) => write!(f, "RESTRICT = {}", proc_name),
1253            Self::Restrict(None) => write!(f, "RESTRICT = NONE"),
1254            Self::Join(Some(proc_name)) => write!(f, "JOIN = {}", proc_name),
1255            Self::Join(None) => write!(f, "JOIN = NONE"),
1256            Self::Commutator(op_name) => write!(f, "COMMUTATOR = {}", op_name),
1257            Self::Negator(op_name) => write!(f, "NEGATOR = {}", op_name),
1258            Self::Hashes => write!(f, "HASHES"),
1259            Self::Merges => write!(f, "MERGES"),
1260        }
1261    }
1262}
1263
1264/// An `ALTER COLUMN` (`Statement::AlterTable`) operation
1265#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1266#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1267#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1268pub enum AlterColumnOperation {
1269    /// `SET NOT NULL`
1270    SetNotNull,
1271    /// `DROP NOT NULL`
1272    DropNotNull,
1273    /// `SET DEFAULT <expr>`
1274    /// Set the column default value.
1275    SetDefault {
1276        /// Expression representing the new default value.
1277        value: Expr,
1278    },
1279    /// `DROP DEFAULT`
1280    DropDefault,
1281    /// `[SET DATA] TYPE <data_type> [USING <expr>]`
1282    SetDataType {
1283        /// Target data type for the column.
1284        data_type: DataType,
1285        /// PostgreSQL-specific `USING <expr>` expression for conversion.
1286        using: Option<Expr>,
1287        /// Set to true if the statement includes the `SET DATA TYPE` keywords.
1288        had_set: bool,
1289    },
1290
1291    /// `ADD GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( sequence_options ) ]`
1292    ///
1293    /// Note: this is a PostgreSQL-specific operation.
1294    AddGenerated {
1295        /// Optional `GENERATED AS` specifier (e.g. `ALWAYS` or `BY DEFAULT`).
1296        generated_as: Option<GeneratedAs>,
1297        /// Optional sequence options for identity generation.
1298        sequence_options: Option<Vec<SequenceOptions>>,
1299    },
1300}
1301
1302impl fmt::Display for AlterColumnOperation {
1303    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1304        match self {
1305            AlterColumnOperation::SetNotNull => write!(f, "SET NOT NULL",),
1306            AlterColumnOperation::DropNotNull => write!(f, "DROP NOT NULL",),
1307            AlterColumnOperation::SetDefault { value } => {
1308                write!(f, "SET DEFAULT {value}")
1309            }
1310            AlterColumnOperation::DropDefault => {
1311                write!(f, "DROP DEFAULT")
1312            }
1313            AlterColumnOperation::SetDataType {
1314                data_type,
1315                using,
1316                had_set,
1317            } => {
1318                if *had_set {
1319                    write!(f, "SET DATA ")?;
1320                }
1321                write!(f, "TYPE {data_type}")?;
1322                if let Some(expr) = using {
1323                    write!(f, " USING {expr}")?;
1324                }
1325                Ok(())
1326            }
1327            AlterColumnOperation::AddGenerated {
1328                generated_as,
1329                sequence_options,
1330            } => {
1331                let generated_as = match generated_as {
1332                    Some(GeneratedAs::Always) => " ALWAYS",
1333                    Some(GeneratedAs::ByDefault) => " BY DEFAULT",
1334                    _ => "",
1335                };
1336
1337                write!(f, "ADD GENERATED{generated_as} AS IDENTITY",)?;
1338                if let Some(options) = sequence_options {
1339                    write!(f, " (")?;
1340
1341                    for sequence_option in options {
1342                        write!(f, "{sequence_option}")?;
1343                    }
1344
1345                    write!(f, " )")?;
1346                }
1347                Ok(())
1348            }
1349        }
1350    }
1351}
1352
1353/// Representation whether a definition can can contains the KEY or INDEX keywords with the same
1354/// meaning.
1355///
1356/// This enum initially is directed to `FULLTEXT`,`SPATIAL`, and `UNIQUE` indexes on create table
1357/// statements of `MySQL` [(1)].
1358///
1359/// [1]: https://dev.mysql.com/doc/refman/8.0/en/create-table.html
1360#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1361#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1362#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1363pub enum KeyOrIndexDisplay {
1364    /// Nothing to display
1365    None,
1366    /// Display the KEY keyword
1367    Key,
1368    /// Display the INDEX keyword
1369    Index,
1370}
1371
1372impl KeyOrIndexDisplay {
1373    /// Check if this is the `None` variant.
1374    pub fn is_none(self) -> bool {
1375        matches!(self, Self::None)
1376    }
1377}
1378
1379impl fmt::Display for KeyOrIndexDisplay {
1380    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1381        let left_space = matches!(f.align(), Some(fmt::Alignment::Right));
1382
1383        if left_space && !self.is_none() {
1384            f.write_char(' ')?
1385        }
1386
1387        match self {
1388            KeyOrIndexDisplay::None => {
1389                write!(f, "")
1390            }
1391            KeyOrIndexDisplay::Key => {
1392                write!(f, "KEY")
1393            }
1394            KeyOrIndexDisplay::Index => {
1395                write!(f, "INDEX")
1396            }
1397        }
1398    }
1399}
1400
1401/// Indexing method used by that index.
1402///
1403/// This structure isn't present on ANSI, but is found at least in [`MySQL` CREATE TABLE][1],
1404/// [`MySQL` CREATE INDEX][2], and [Postgresql CREATE INDEX][3] statements.
1405///
1406/// [1]: https://dev.mysql.com/doc/refman/8.0/en/create-table.html
1407/// [2]: https://dev.mysql.com/doc/refman/8.0/en/create-index.html
1408/// [3]: https://www.postgresql.org/docs/14/sql-createindex.html
1409#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1410#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1411#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1412pub enum IndexType {
1413    /// B-Tree index (commonly default for many databases).
1414    BTree,
1415    /// Hash index.
1416    Hash,
1417    /// Generalized Inverted Index (GIN).
1418    GIN,
1419    /// Generalized Search Tree (GiST) index.
1420    GiST,
1421    /// Space-partitioned GiST (SPGiST) index.
1422    SPGiST,
1423    /// Block Range Index (BRIN).
1424    BRIN,
1425    /// Bloom filter based index.
1426    Bloom,
1427    /// Users may define their own index types, which would
1428    /// not be covered by the above variants.
1429    Custom(Ident),
1430}
1431
1432impl fmt::Display for IndexType {
1433    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1434        match self {
1435            Self::BTree => write!(f, "BTREE"),
1436            Self::Hash => write!(f, "HASH"),
1437            Self::GIN => write!(f, "GIN"),
1438            Self::GiST => write!(f, "GIST"),
1439            Self::SPGiST => write!(f, "SPGIST"),
1440            Self::BRIN => write!(f, "BRIN"),
1441            Self::Bloom => write!(f, "BLOOM"),
1442            Self::Custom(name) => write!(f, "{name}"),
1443        }
1444    }
1445}
1446
1447/// MySQL index option, used in [`CREATE TABLE`], [`CREATE INDEX`], and [`ALTER TABLE`].
1448///
1449/// [`CREATE TABLE`]: https://dev.mysql.com/doc/refman/8.4/en/create-table.html
1450/// [`CREATE INDEX`]: https://dev.mysql.com/doc/refman/8.4/en/create-index.html
1451/// [`ALTER TABLE`]: https://dev.mysql.com/doc/refman/8.4/en/alter-table.html
1452#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1453#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1454#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1455pub enum IndexOption {
1456    /// `USING { BTREE | HASH }`: Index type to use for the index.
1457    ///
1458    /// Note that we permissively parse non-MySQL index types, like `GIN`.
1459    Using(IndexType),
1460    /// `COMMENT 'string'`: Specifies a comment for the index.
1461    Comment(String),
1462}
1463
1464impl fmt::Display for IndexOption {
1465    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1466        match self {
1467            Self::Using(index_type) => write!(f, "USING {index_type}"),
1468            Self::Comment(s) => write!(f, "COMMENT '{s}'"),
1469        }
1470    }
1471}
1472
1473/// [PostgreSQL] unique index nulls handling option: `[ NULLS [ NOT ] DISTINCT ]`
1474///
1475/// [PostgreSQL]: https://www.postgresql.org/docs/17/sql-altertable.html
1476#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1477#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1478#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1479pub enum NullsDistinctOption {
1480    /// Not specified
1481    None,
1482    /// NULLS DISTINCT
1483    Distinct,
1484    /// NULLS NOT DISTINCT
1485    NotDistinct,
1486}
1487
1488impl fmt::Display for NullsDistinctOption {
1489    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1490        match self {
1491            Self::None => Ok(()),
1492            Self::Distinct => write!(f, " NULLS DISTINCT"),
1493            Self::NotDistinct => write!(f, " NULLS NOT DISTINCT"),
1494        }
1495    }
1496}
1497
1498#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1499#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1500#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1501/// A parameter of a stored procedure or function declaration.
1502pub struct ProcedureParam {
1503    /// Parameter name.
1504    pub name: Ident,
1505    /// Parameter data type.
1506    pub data_type: DataType,
1507    /// Optional mode (`IN`, `OUT`, `INOUT`, etc.).
1508    pub mode: Option<ArgMode>,
1509    /// Optional default expression for the parameter.
1510    pub default: Option<Expr>,
1511}
1512
1513impl fmt::Display for ProcedureParam {
1514    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1515        if let Some(mode) = &self.mode {
1516            if let Some(default) = &self.default {
1517                write!(f, "{mode} {} {} = {}", self.name, self.data_type, default)
1518            } else {
1519                write!(f, "{mode} {} {}", self.name, self.data_type)
1520            }
1521        } else if let Some(default) = &self.default {
1522            write!(f, "{} {} = {}", self.name, self.data_type, default)
1523        } else {
1524            write!(f, "{} {}", self.name, self.data_type)
1525        }
1526    }
1527}
1528
1529/// SQL column definition
1530#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1531#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1532#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1533pub struct ColumnDef {
1534    /// Column name.
1535    pub name: Ident,
1536    /// Column data type.
1537    pub data_type: DataType,
1538    /// Column options (defaults, constraints, generated, etc.).
1539    pub options: Vec<ColumnOptionDef>,
1540}
1541
1542impl fmt::Display for ColumnDef {
1543    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1544        if self.data_type == DataType::Unspecified {
1545            write!(f, "{}", self.name)?;
1546        } else {
1547            write!(f, "{} {}", self.name, self.data_type)?;
1548        }
1549        for option in &self.options {
1550            write!(f, " {option}")?;
1551        }
1552        Ok(())
1553    }
1554}
1555
1556/// Column definition specified in a `CREATE VIEW` statement.
1557///
1558/// Syntax
1559/// ```markdown
1560/// <name> [data_type][OPTIONS(option, ...)]
1561///
1562/// option: <name> = <value>
1563/// ```
1564///
1565/// Examples:
1566/// ```sql
1567/// name
1568/// age OPTIONS(description = "age column", tag = "prod")
1569/// amount COMMENT 'The total amount for the order line'
1570/// created_at DateTime64
1571/// ```
1572#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1573#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1574#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1575pub struct ViewColumnDef {
1576    /// Column identifier.
1577    pub name: Ident,
1578    /// Optional data type for the column.
1579    pub data_type: Option<DataType>,
1580    /// Optional column options (defaults, comments, etc.).
1581    pub options: Option<ColumnOptions>,
1582}
1583
1584#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1585#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1586#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1587/// Representation of how multiple `ColumnOption`s are grouped for a column.
1588pub enum ColumnOptions {
1589    /// Options separated by comma: `OPTIONS(a, b, c)`.
1590    CommaSeparated(Vec<ColumnOption>),
1591    /// Options separated by spaces: `OPTION_A OPTION_B`.
1592    SpaceSeparated(Vec<ColumnOption>),
1593}
1594
1595impl ColumnOptions {
1596    /// Get the column options as a slice.
1597    pub fn as_slice(&self) -> &[ColumnOption] {
1598        match self {
1599            ColumnOptions::CommaSeparated(options) => options.as_slice(),
1600            ColumnOptions::SpaceSeparated(options) => options.as_slice(),
1601        }
1602    }
1603}
1604
1605impl fmt::Display for ViewColumnDef {
1606    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1607        write!(f, "{}", self.name)?;
1608        if let Some(data_type) = self.data_type.as_ref() {
1609            write!(f, " {data_type}")?;
1610        }
1611        if let Some(options) = self.options.as_ref() {
1612            match options {
1613                ColumnOptions::CommaSeparated(column_options) => {
1614                    write!(f, " {}", display_comma_separated(column_options.as_slice()))?;
1615                }
1616                ColumnOptions::SpaceSeparated(column_options) => {
1617                    write!(f, " {}", display_separated(column_options.as_slice(), " "))?
1618                }
1619            }
1620        }
1621        Ok(())
1622    }
1623}
1624
1625/// An optionally-named `ColumnOption`: `[ CONSTRAINT <name> ] <column-option>`.
1626///
1627/// Note that implementations are substantially more permissive than the ANSI
1628/// specification on what order column options can be presented in, and whether
1629/// they are allowed to be named. The specification distinguishes between
1630/// constraints (NOT NULL, UNIQUE, PRIMARY KEY, and CHECK), which can be named
1631/// and can appear in any order, and other options (DEFAULT, GENERATED), which
1632/// cannot be named and must appear in a fixed order. `PostgreSQL`, however,
1633/// allows preceding any option with `CONSTRAINT <name>`, even those that are
1634/// not really constraints, like NULL and DEFAULT. MSSQL is less permissive,
1635/// allowing DEFAULT, UNIQUE, PRIMARY KEY and CHECK to be named, but not NULL or
1636/// NOT NULL constraints (the last of which is in violation of the spec).
1637///
1638/// For maximum flexibility, we don't distinguish between constraint and
1639/// non-constraint options, lumping them all together under the umbrella of
1640/// "column options," and we allow any column option to be named.
1641#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1642#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1643#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1644pub struct ColumnOptionDef {
1645    /// Optional name of the constraint.
1646    pub name: Option<Ident>,
1647    /// The actual column option (e.g. `NOT NULL`, `DEFAULT`, `GENERATED`, ...).
1648    pub option: ColumnOption,
1649}
1650
1651impl fmt::Display for ColumnOptionDef {
1652    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1653        write!(f, "{}{}", display_constraint_name(&self.name), self.option)
1654    }
1655}
1656
1657/// Identity is a column option for defining an identity or autoincrement column in a `CREATE TABLE` statement.
1658/// Syntax
1659/// ```sql
1660/// { IDENTITY | AUTOINCREMENT } [ (seed , increment) | START num INCREMENT num ] [ ORDER | NOORDER ]
1661/// ```
1662/// [MS SQL Server]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property
1663/// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1664#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1665#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1666#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1667pub enum IdentityPropertyKind {
1668    /// An identity property declared via the `AUTOINCREMENT` key word
1669    /// Example:
1670    /// ```sql
1671    ///  AUTOINCREMENT(100, 1) NOORDER
1672    ///  AUTOINCREMENT START 100 INCREMENT 1 ORDER
1673    /// ```
1674    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1675    Autoincrement(IdentityProperty),
1676    /// An identity property declared via the `IDENTITY` key word
1677    /// Example, [MS SQL Server] or [Snowflake]:
1678    /// ```sql
1679    ///  IDENTITY(100, 1)
1680    /// ```
1681    /// [Snowflake]
1682    /// ```sql
1683    ///  IDENTITY(100, 1) ORDER
1684    ///  IDENTITY START 100 INCREMENT 1 NOORDER
1685    /// ```
1686    /// [MS SQL Server]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property
1687    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1688    Identity(IdentityProperty),
1689}
1690
1691impl fmt::Display for IdentityPropertyKind {
1692    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1693        let (command, property) = match self {
1694            IdentityPropertyKind::Identity(property) => ("IDENTITY", property),
1695            IdentityPropertyKind::Autoincrement(property) => ("AUTOINCREMENT", property),
1696        };
1697        write!(f, "{command}")?;
1698        if let Some(parameters) = &property.parameters {
1699            write!(f, "{parameters}")?;
1700        }
1701        if let Some(order) = &property.order {
1702            write!(f, "{order}")?;
1703        }
1704        Ok(())
1705    }
1706}
1707
1708/// Properties for the `IDENTITY` / `AUTOINCREMENT` column option.
1709#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1710#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1711#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1712pub struct IdentityProperty {
1713    /// Optional parameters specifying seed/increment for the identity column.
1714    pub parameters: Option<IdentityPropertyFormatKind>,
1715    /// Optional ordering specifier (`ORDER` / `NOORDER`).
1716    pub order: Option<IdentityPropertyOrder>,
1717}
1718
1719/// A format of parameters of identity column.
1720///
1721/// It is [Snowflake] specific.
1722/// Syntax
1723/// ```sql
1724/// (seed , increment) | START num INCREMENT num
1725/// ```
1726/// [MS SQL Server] uses one way of representing these parameters.
1727/// Syntax
1728/// ```sql
1729/// (seed , increment)
1730/// ```
1731/// [MS SQL Server]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property
1732/// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1733#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1734#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1735#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1736pub enum IdentityPropertyFormatKind {
1737    /// A parameters of identity column declared like parameters of function call
1738    /// Example:
1739    /// ```sql
1740    ///  (100, 1)
1741    /// ```
1742    /// [MS SQL Server]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property
1743    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1744    FunctionCall(IdentityParameters),
1745    /// A parameters of identity column declared with keywords `START` and `INCREMENT`
1746    /// Example:
1747    /// ```sql
1748    ///  START 100 INCREMENT 1
1749    /// ```
1750    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1751    StartAndIncrement(IdentityParameters),
1752}
1753
1754impl fmt::Display for IdentityPropertyFormatKind {
1755    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1756        match self {
1757            IdentityPropertyFormatKind::FunctionCall(parameters) => {
1758                write!(f, "({}, {})", parameters.seed, parameters.increment)
1759            }
1760            IdentityPropertyFormatKind::StartAndIncrement(parameters) => {
1761                write!(
1762                    f,
1763                    " START {} INCREMENT {}",
1764                    parameters.seed, parameters.increment
1765                )
1766            }
1767        }
1768    }
1769}
1770/// Parameters specifying seed and increment for identity columns.
1771#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1772#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1773#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1774pub struct IdentityParameters {
1775    /// The initial seed expression for the identity column.
1776    pub seed: Expr,
1777    /// The increment expression for the identity column.
1778    pub increment: Expr,
1779}
1780
1781/// The identity column option specifies how values are generated for the auto-incremented column, either in increasing or decreasing order.
1782/// Syntax
1783/// ```sql
1784/// ORDER | NOORDER
1785/// ```
1786/// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1787#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1788#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1789#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1790pub enum IdentityPropertyOrder {
1791    /// `ORDER` - preserve ordering for generated values (where supported).
1792    Order,
1793    /// `NOORDER` - do not enforce ordering for generated values.
1794    NoOrder,
1795}
1796
1797impl fmt::Display for IdentityPropertyOrder {
1798    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1799        match self {
1800            IdentityPropertyOrder::Order => write!(f, " ORDER"),
1801            IdentityPropertyOrder::NoOrder => write!(f, " NOORDER"),
1802        }
1803    }
1804}
1805
1806/// Column policy that identify a security policy of access to a column.
1807/// Syntax
1808/// ```sql
1809/// [ WITH ] MASKING POLICY <policy_name> [ USING ( <col_name> , <cond_col1> , ... ) ]
1810/// [ WITH ] PROJECTION POLICY <policy_name>
1811/// ```
1812/// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1813#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1814#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1815#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1816pub enum ColumnPolicy {
1817    /// `MASKING POLICY (<property>)`
1818    MaskingPolicy(ColumnPolicyProperty),
1819    /// `PROJECTION POLICY (<property>)`
1820    ProjectionPolicy(ColumnPolicyProperty),
1821}
1822
1823impl fmt::Display for ColumnPolicy {
1824    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1825        let (command, property) = match self {
1826            ColumnPolicy::MaskingPolicy(property) => ("MASKING POLICY", property),
1827            ColumnPolicy::ProjectionPolicy(property) => ("PROJECTION POLICY", property),
1828        };
1829        if property.with {
1830            write!(f, "WITH ")?;
1831        }
1832        write!(f, "{command} {}", property.policy_name)?;
1833        if let Some(using_columns) = &property.using_columns {
1834            write!(f, " USING ({})", display_comma_separated(using_columns))?;
1835        }
1836        Ok(())
1837    }
1838}
1839
1840#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1841#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1842#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1843/// Properties describing a column policy (masking or projection).
1844pub struct ColumnPolicyProperty {
1845    /// This flag indicates that the column policy option is declared using the `WITH` prefix.
1846    /// Example
1847    /// ```sql
1848    /// WITH PROJECTION POLICY sample_policy
1849    /// ```
1850    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1851    pub with: bool,
1852    /// The name of the policy to apply to the column.
1853    pub policy_name: ObjectName,
1854    /// Optional list of column identifiers referenced by the policy.
1855    pub using_columns: Option<Vec<Ident>>,
1856}
1857
1858/// Tags option of column
1859/// Syntax
1860/// ```sql
1861/// [ WITH ] TAG ( <tag_name> = '<tag_value>' [ , <tag_name> = '<tag_value>' , ... ] )
1862/// ```
1863/// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1864#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1865#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1866#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1867pub struct TagsColumnOption {
1868    /// This flag indicates that the tags option is declared using the `WITH` prefix.
1869    /// Example:
1870    /// ```sql
1871    /// WITH TAG (A = 'Tag A')
1872    /// ```
1873    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1874    pub with: bool,
1875    /// List of tags to attach to the column.
1876    pub tags: Vec<Tag>,
1877}
1878
1879impl fmt::Display for TagsColumnOption {
1880    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1881        if self.with {
1882            write!(f, "WITH ")?;
1883        }
1884        write!(f, "TAG ({})", display_comma_separated(&self.tags))?;
1885        Ok(())
1886    }
1887}
1888
1889/// `ColumnOption`s are modifiers that follow a column definition in a `CREATE
1890/// TABLE` statement.
1891#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1892#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1893#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1894pub enum ColumnOption {
1895    /// `NULL`
1896    Null,
1897    /// `NOT NULL`
1898    NotNull,
1899    /// `DEFAULT <restricted-expr>`
1900    Default(Expr),
1901
1902    /// `MATERIALIZE <expr>`
1903    /// Syntax: `b INT MATERIALIZE (a + 1)`
1904    ///
1905    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/create/table#default_values)
1906    Materialized(Expr),
1907    /// `EPHEMERAL [<expr>]`
1908    ///
1909    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/create/table#default_values)
1910    Ephemeral(Option<Expr>),
1911    /// `ALIAS <expr>`
1912    ///
1913    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/create/table#default_values)
1914    Alias(Expr),
1915
1916    /// `PRIMARY KEY [<constraint_characteristics>]`
1917    PrimaryKey(PrimaryKeyConstraint),
1918    /// `UNIQUE [<constraint_characteristics>]`
1919    Unique(UniqueConstraint),
1920    /// A referential integrity constraint (`REFERENCES <foreign_table> (<referred_columns>)
1921    /// [ MATCH { FULL | PARTIAL | SIMPLE } ]
1922    /// { [ON DELETE <referential_action>] [ON UPDATE <referential_action>] |
1923    ///   [ON UPDATE <referential_action>] [ON DELETE <referential_action>]
1924    /// }
1925    /// [<constraint_characteristics>]
1926    /// `).
1927    ForeignKey(ForeignKeyConstraint),
1928    /// `CHECK (<expr>)`
1929    Check(CheckConstraint),
1930    /// Dialect-specific options, such as:
1931    /// - MySQL's `AUTO_INCREMENT` or SQLite's `AUTOINCREMENT`
1932    /// - ...
1933    DialectSpecific(Vec<Token>),
1934    /// `CHARACTER SET <name>` column option
1935    CharacterSet(ObjectName),
1936    /// `COLLATE <name>` column option
1937    Collation(ObjectName),
1938    /// `COMMENT '<text>'` column option
1939    Comment(String),
1940    /// `ON UPDATE <expr>` column option
1941    OnUpdate(Expr),
1942    /// `Generated`s are modifiers that follow a column definition in a `CREATE
1943    /// TABLE` statement.
1944    Generated {
1945        /// How the column is generated (e.g. `GENERATED ALWAYS`, `BY DEFAULT`, or expression-stored).
1946        generated_as: GeneratedAs,
1947        /// Sequence/identity options when generation is backed by a sequence.
1948        sequence_options: Option<Vec<SequenceOptions>>,
1949        /// Optional expression used to generate the column value.
1950        generation_expr: Option<Expr>,
1951        /// Mode of the generated expression (`VIRTUAL` or `STORED`) when `generation_expr` is present.
1952        generation_expr_mode: Option<GeneratedExpressionMode>,
1953        /// false if 'GENERATED ALWAYS' is skipped (option starts with AS)
1954        generated_keyword: bool,
1955    },
1956    /// BigQuery specific: Explicit column options in a view [1] or table [2]
1957    /// Syntax
1958    /// ```sql
1959    /// OPTIONS(description="field desc")
1960    /// ```
1961    /// [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#view_column_option_list
1962    /// [2]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#column_option_list
1963    Options(Vec<SqlOption>),
1964    /// Creates an identity or an autoincrement column in a table.
1965    /// Syntax
1966    /// ```sql
1967    /// { IDENTITY | AUTOINCREMENT } [ (seed , increment) | START num INCREMENT num ] [ ORDER | NOORDER ]
1968    /// ```
1969    /// [MS SQL Server]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property
1970    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1971    Identity(IdentityPropertyKind),
1972    /// SQLite specific: ON CONFLICT option on column definition
1973    /// <https://www.sqlite.org/lang_conflict.html>
1974    OnConflict(Keyword),
1975    /// Snowflake specific: an option of specifying security masking or projection policy to set on a column.
1976    /// Syntax:
1977    /// ```sql
1978    /// [ WITH ] MASKING POLICY <policy_name> [ USING ( <col_name> , <cond_col1> , ... ) ]
1979    /// [ WITH ] PROJECTION POLICY <policy_name>
1980    /// ```
1981    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1982    Policy(ColumnPolicy),
1983    /// Snowflake specific: Specifies the tag name and the tag string value.
1984    /// Syntax:
1985    /// ```sql
1986    /// [ WITH ] TAG ( <tag_name> = '<tag_value>' [ , <tag_name> = '<tag_value>' , ... ] )
1987    /// ```
1988    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1989    Tags(TagsColumnOption),
1990    /// MySQL specific: Spatial reference identifier
1991    /// Syntax:
1992    /// ```sql
1993    /// CREATE TABLE geom (g GEOMETRY NOT NULL SRID 4326);
1994    /// ```
1995    /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/creating-spatial-indexes.html
1996    Srid(Box<Expr>),
1997    /// MySQL specific: Column is invisible via SELECT *
1998    /// Syntax:
1999    /// ```sql
2000    /// CREATE TABLE t (foo INT, bar INT INVISIBLE);
2001    /// ```
2002    /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/invisible-columns.html
2003    Invisible,
2004}
2005
2006impl From<UniqueConstraint> for ColumnOption {
2007    fn from(c: UniqueConstraint) -> Self {
2008        ColumnOption::Unique(c)
2009    }
2010}
2011
2012impl From<PrimaryKeyConstraint> for ColumnOption {
2013    fn from(c: PrimaryKeyConstraint) -> Self {
2014        ColumnOption::PrimaryKey(c)
2015    }
2016}
2017
2018impl From<CheckConstraint> for ColumnOption {
2019    fn from(c: CheckConstraint) -> Self {
2020        ColumnOption::Check(c)
2021    }
2022}
2023impl From<ForeignKeyConstraint> for ColumnOption {
2024    fn from(fk: ForeignKeyConstraint) -> Self {
2025        ColumnOption::ForeignKey(fk)
2026    }
2027}
2028
2029impl fmt::Display for ColumnOption {
2030    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2031        use ColumnOption::*;
2032        match self {
2033            Null => write!(f, "NULL"),
2034            NotNull => write!(f, "NOT NULL"),
2035            Default(expr) => write!(f, "DEFAULT {expr}"),
2036            Materialized(expr) => write!(f, "MATERIALIZED {expr}"),
2037            Ephemeral(expr) => {
2038                if let Some(e) = expr {
2039                    write!(f, "EPHEMERAL {e}")
2040                } else {
2041                    write!(f, "EPHEMERAL")
2042                }
2043            }
2044            Alias(expr) => write!(f, "ALIAS {expr}"),
2045            PrimaryKey(constraint) => {
2046                write!(f, "PRIMARY KEY")?;
2047                if let Some(characteristics) = &constraint.characteristics {
2048                    write!(f, " {characteristics}")?;
2049                }
2050                Ok(())
2051            }
2052            Unique(constraint) => {
2053                write!(f, "UNIQUE{:>}", constraint.index_type_display)?;
2054                if let Some(characteristics) = &constraint.characteristics {
2055                    write!(f, " {characteristics}")?;
2056                }
2057                Ok(())
2058            }
2059            ForeignKey(constraint) => {
2060                write!(f, "REFERENCES {}", constraint.foreign_table)?;
2061                if !constraint.referred_columns.is_empty() {
2062                    write!(
2063                        f,
2064                        " ({})",
2065                        display_comma_separated(&constraint.referred_columns)
2066                    )?;
2067                }
2068                if let Some(match_kind) = &constraint.match_kind {
2069                    write!(f, " {match_kind}")?;
2070                }
2071                if let Some(action) = &constraint.on_delete {
2072                    write!(f, " ON DELETE {action}")?;
2073                }
2074                if let Some(action) = &constraint.on_update {
2075                    write!(f, " ON UPDATE {action}")?;
2076                }
2077                if let Some(characteristics) = &constraint.characteristics {
2078                    write!(f, " {characteristics}")?;
2079                }
2080                Ok(())
2081            }
2082            Check(constraint) => write!(f, "{constraint}"),
2083            DialectSpecific(val) => write!(f, "{}", display_separated(val, " ")),
2084            CharacterSet(n) => write!(f, "CHARACTER SET {n}"),
2085            Collation(n) => write!(f, "COLLATE {n}"),
2086            Comment(v) => write!(f, "COMMENT '{}'", escape_single_quote_string(v)),
2087            OnUpdate(expr) => write!(f, "ON UPDATE {expr}"),
2088            Generated {
2089                generated_as,
2090                sequence_options,
2091                generation_expr,
2092                generation_expr_mode,
2093                generated_keyword,
2094            } => {
2095                if let Some(expr) = generation_expr {
2096                    let modifier = match generation_expr_mode {
2097                        None => "",
2098                        Some(GeneratedExpressionMode::Virtual) => " VIRTUAL",
2099                        Some(GeneratedExpressionMode::Stored) => " STORED",
2100                    };
2101                    if *generated_keyword {
2102                        write!(f, "GENERATED ALWAYS AS ({expr}){modifier}")?;
2103                    } else {
2104                        write!(f, "AS ({expr}){modifier}")?;
2105                    }
2106                    Ok(())
2107                } else {
2108                    // Like Postgres - generated from sequence
2109                    let when = match generated_as {
2110                        GeneratedAs::Always => "ALWAYS",
2111                        GeneratedAs::ByDefault => "BY DEFAULT",
2112                        // ExpStored goes with an expression, handled above
2113                        GeneratedAs::ExpStored => "",
2114                    };
2115                    write!(f, "GENERATED {when} AS IDENTITY")?;
2116                    if sequence_options.is_some() {
2117                        let so = sequence_options.as_ref().unwrap();
2118                        if !so.is_empty() {
2119                            write!(f, " (")?;
2120                        }
2121                        for sequence_option in so {
2122                            write!(f, "{sequence_option}")?;
2123                        }
2124                        if !so.is_empty() {
2125                            write!(f, " )")?;
2126                        }
2127                    }
2128                    Ok(())
2129                }
2130            }
2131            Options(options) => {
2132                write!(f, "OPTIONS({})", display_comma_separated(options))
2133            }
2134            Identity(parameters) => {
2135                write!(f, "{parameters}")
2136            }
2137            OnConflict(keyword) => {
2138                write!(f, "ON CONFLICT {keyword:?}")?;
2139                Ok(())
2140            }
2141            Policy(parameters) => {
2142                write!(f, "{parameters}")
2143            }
2144            Tags(tags) => {
2145                write!(f, "{tags}")
2146            }
2147            Srid(srid) => {
2148                write!(f, "SRID {srid}")
2149            }
2150            Invisible => {
2151                write!(f, "INVISIBLE")
2152            }
2153        }
2154    }
2155}
2156
2157/// `GeneratedAs`s are modifiers that follow a column option in a `generated`.
2158/// 'ExpStored' is used for a column generated from an expression and stored.
2159#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2160#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2161#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2162pub enum GeneratedAs {
2163    /// `GENERATED ALWAYS`
2164    Always,
2165    /// `GENERATED BY DEFAULT`
2166    ByDefault,
2167    /// Expression-based generated column that is stored (used internally for expression-stored columns)
2168    ExpStored,
2169}
2170
2171/// `GeneratedExpressionMode`s are modifiers that follow an expression in a `generated`.
2172/// No modifier is typically the same as Virtual.
2173#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2174#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2175#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2176pub enum GeneratedExpressionMode {
2177    /// `VIRTUAL` generated expression
2178    Virtual,
2179    /// `STORED` generated expression
2180    Stored,
2181}
2182
2183#[must_use]
2184pub(crate) fn display_constraint_name(name: &'_ Option<Ident>) -> impl fmt::Display + '_ {
2185    struct ConstraintName<'a>(&'a Option<Ident>);
2186    impl fmt::Display for ConstraintName<'_> {
2187        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2188            if let Some(name) = self.0 {
2189                write!(f, "CONSTRAINT {name} ")?;
2190            }
2191            Ok(())
2192        }
2193    }
2194    ConstraintName(name)
2195}
2196
2197/// If `option` is
2198/// * `Some(inner)` => create display struct for `"{prefix}{inner}{postfix}"`
2199/// * `_` => do nothing
2200#[must_use]
2201pub(crate) fn display_option<'a, T: fmt::Display>(
2202    prefix: &'a str,
2203    postfix: &'a str,
2204    option: &'a Option<T>,
2205) -> impl fmt::Display + 'a {
2206    struct OptionDisplay<'a, T>(&'a str, &'a str, &'a Option<T>);
2207    impl<T: fmt::Display> fmt::Display for OptionDisplay<'_, T> {
2208        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2209            if let Some(inner) = self.2 {
2210                let (prefix, postfix) = (self.0, self.1);
2211                write!(f, "{prefix}{inner}{postfix}")?;
2212            }
2213            Ok(())
2214        }
2215    }
2216    OptionDisplay(prefix, postfix, option)
2217}
2218
2219/// If `option` is
2220/// * `Some(inner)` => create display struct for `" {inner}"`
2221/// * `_` => do nothing
2222#[must_use]
2223pub(crate) fn display_option_spaced<T: fmt::Display>(option: &Option<T>) -> impl fmt::Display + '_ {
2224    display_option(" ", "", option)
2225}
2226
2227/// `<constraint_characteristics> = [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ ENFORCED | NOT ENFORCED ]`
2228///
2229/// Used in UNIQUE and foreign key constraints. The individual settings may occur in any order.
2230#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Default, Eq, Ord, Hash)]
2231#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2232#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2233pub struct ConstraintCharacteristics {
2234    /// `[ DEFERRABLE | NOT DEFERRABLE ]`
2235    pub deferrable: Option<bool>,
2236    /// `[ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]`
2237    pub initially: Option<DeferrableInitial>,
2238    /// `[ ENFORCED | NOT ENFORCED ]`
2239    pub enforced: Option<bool>,
2240}
2241
2242/// Initial setting for deferrable constraints (`INITIALLY IMMEDIATE` or `INITIALLY DEFERRED`).
2243#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2244#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2245#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2246pub enum DeferrableInitial {
2247    /// `INITIALLY IMMEDIATE`
2248    Immediate,
2249    /// `INITIALLY DEFERRED`
2250    Deferred,
2251}
2252
2253impl ConstraintCharacteristics {
2254    fn deferrable_text(&self) -> Option<&'static str> {
2255        self.deferrable.map(|deferrable| {
2256            if deferrable {
2257                "DEFERRABLE"
2258            } else {
2259                "NOT DEFERRABLE"
2260            }
2261        })
2262    }
2263
2264    fn initially_immediate_text(&self) -> Option<&'static str> {
2265        self.initially
2266            .map(|initially_immediate| match initially_immediate {
2267                DeferrableInitial::Immediate => "INITIALLY IMMEDIATE",
2268                DeferrableInitial::Deferred => "INITIALLY DEFERRED",
2269            })
2270    }
2271
2272    fn enforced_text(&self) -> Option<&'static str> {
2273        self.enforced.map(
2274            |enforced| {
2275                if enforced {
2276                    "ENFORCED"
2277                } else {
2278                    "NOT ENFORCED"
2279                }
2280            },
2281        )
2282    }
2283}
2284
2285impl fmt::Display for ConstraintCharacteristics {
2286    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2287        let deferrable = self.deferrable_text();
2288        let initially_immediate = self.initially_immediate_text();
2289        let enforced = self.enforced_text();
2290
2291        match (deferrable, initially_immediate, enforced) {
2292            (None, None, None) => Ok(()),
2293            (None, None, Some(enforced)) => write!(f, "{enforced}"),
2294            (None, Some(initial), None) => write!(f, "{initial}"),
2295            (None, Some(initial), Some(enforced)) => write!(f, "{initial} {enforced}"),
2296            (Some(deferrable), None, None) => write!(f, "{deferrable}"),
2297            (Some(deferrable), None, Some(enforced)) => write!(f, "{deferrable} {enforced}"),
2298            (Some(deferrable), Some(initial), None) => write!(f, "{deferrable} {initial}"),
2299            (Some(deferrable), Some(initial), Some(enforced)) => {
2300                write!(f, "{deferrable} {initial} {enforced}")
2301            }
2302        }
2303    }
2304}
2305
2306/// `<referential_action> =
2307/// { RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT }`
2308///
2309/// Used in foreign key constraints in `ON UPDATE` and `ON DELETE` options.
2310#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2311#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2312#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2313pub enum ReferentialAction {
2314    /// `RESTRICT` - disallow action if it would break referential integrity.
2315    Restrict,
2316    /// `CASCADE` - propagate the action to referencing rows.
2317    Cascade,
2318    /// `SET NULL` - set referencing columns to NULL.
2319    SetNull,
2320    /// `NO ACTION` - no action at the time; may be deferred.
2321    NoAction,
2322    /// `SET DEFAULT` - set referencing columns to their default values.
2323    SetDefault,
2324}
2325
2326impl fmt::Display for ReferentialAction {
2327    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2328        f.write_str(match self {
2329            ReferentialAction::Restrict => "RESTRICT",
2330            ReferentialAction::Cascade => "CASCADE",
2331            ReferentialAction::SetNull => "SET NULL",
2332            ReferentialAction::NoAction => "NO ACTION",
2333            ReferentialAction::SetDefault => "SET DEFAULT",
2334        })
2335    }
2336}
2337
2338/// `<drop behavior> ::= CASCADE | RESTRICT`.
2339///
2340/// Used in `DROP` statements.
2341#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2342#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2343#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2344pub enum DropBehavior {
2345    /// `RESTRICT` - refuse to drop if there are any dependent objects.
2346    Restrict,
2347    /// `CASCADE` - automatically drop objects that depend on the object being dropped.
2348    Cascade,
2349}
2350
2351impl fmt::Display for DropBehavior {
2352    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2353        f.write_str(match self {
2354            DropBehavior::Restrict => "RESTRICT",
2355            DropBehavior::Cascade => "CASCADE",
2356        })
2357    }
2358}
2359
2360/// SQL user defined type definition
2361#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2362#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2363#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2364pub enum UserDefinedTypeRepresentation {
2365    /// Composite type: `CREATE TYPE name AS (attributes)`
2366    Composite {
2367        /// List of attributes for the composite type.
2368        attributes: Vec<UserDefinedTypeCompositeAttributeDef>,
2369    },
2370    /// Enum type: `CREATE TYPE name AS ENUM (labels)`
2371    ///
2372    /// Note: this is PostgreSQL-specific. See <https://www.postgresql.org/docs/current/sql-createtype.html>
2373    /// Enum type: `CREATE TYPE name AS ENUM (labels)`
2374    Enum {
2375        /// Labels that make up the enum type.
2376        labels: Vec<Ident>,
2377    },
2378    /// Range type: `CREATE TYPE name AS RANGE (options)`
2379    ///
2380    /// Note: this is PostgreSQL-specific. See <https://www.postgresql.org/docs/current/sql-createtype.html>
2381    Range {
2382        /// Options for the range type definition.
2383        options: Vec<UserDefinedTypeRangeOption>,
2384    },
2385    /// Base type (SQL definition): `CREATE TYPE name (options)`
2386    ///
2387    /// Note the lack of `AS` keyword
2388    ///
2389    /// Note: this is PostgreSQL-specific. See <https://www.postgresql.org/docs/current/sql-createtype.html>
2390    SqlDefinition {
2391        /// Options for SQL definition of the user-defined type.
2392        options: Vec<UserDefinedTypeSqlDefinitionOption>,
2393    },
2394}
2395
2396impl fmt::Display for UserDefinedTypeRepresentation {
2397    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2398        match self {
2399            Self::Composite { attributes } => {
2400                write!(f, "AS ({})", display_comma_separated(attributes))
2401            }
2402            Self::Enum { labels } => {
2403                write!(f, "AS ENUM ({})", display_comma_separated(labels))
2404            }
2405            Self::Range { options } => {
2406                write!(f, "AS RANGE ({})", display_comma_separated(options))
2407            }
2408            Self::SqlDefinition { options } => {
2409                write!(f, "({})", display_comma_separated(options))
2410            }
2411        }
2412    }
2413}
2414
2415/// SQL user defined type attribute definition
2416#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2417#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2418#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2419pub struct UserDefinedTypeCompositeAttributeDef {
2420    /// Attribute name.
2421    pub name: Ident,
2422    /// Attribute data type.
2423    pub data_type: DataType,
2424    /// Optional collation for the attribute.
2425    pub collation: Option<ObjectName>,
2426}
2427
2428impl fmt::Display for UserDefinedTypeCompositeAttributeDef {
2429    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2430        write!(f, "{} {}", self.name, self.data_type)?;
2431        if let Some(collation) = &self.collation {
2432            write!(f, " COLLATE {collation}")?;
2433        }
2434        Ok(())
2435    }
2436}
2437
2438/// Internal length specification for PostgreSQL user-defined base types.
2439///
2440/// Specifies the internal length in bytes of the new type's internal representation.
2441/// The default assumption is that it is variable-length.
2442///
2443/// # PostgreSQL Documentation
2444/// See: <https://www.postgresql.org/docs/current/sql-createtype.html>
2445///
2446/// # Examples
2447/// ```sql
2448/// CREATE TYPE mytype (
2449///     INPUT = in_func,
2450///     OUTPUT = out_func,
2451///     INTERNALLENGTH = 16  -- Fixed 16-byte length
2452/// );
2453///
2454/// CREATE TYPE mytype2 (
2455///     INPUT = in_func,
2456///     OUTPUT = out_func,
2457///     INTERNALLENGTH = VARIABLE  -- Variable length
2458/// );
2459/// ```
2460#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2461#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2462#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2463pub enum UserDefinedTypeInternalLength {
2464    /// Fixed internal length: `INTERNALLENGTH = <number>`
2465    Fixed(u64),
2466    /// Variable internal length: `INTERNALLENGTH = VARIABLE`
2467    Variable,
2468}
2469
2470impl fmt::Display for UserDefinedTypeInternalLength {
2471    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2472        match self {
2473            UserDefinedTypeInternalLength::Fixed(n) => write!(f, "{}", n),
2474            UserDefinedTypeInternalLength::Variable => write!(f, "VARIABLE"),
2475        }
2476    }
2477}
2478
2479/// Alignment specification for PostgreSQL user-defined base types.
2480///
2481/// Specifies the storage alignment requirement for values of the data type.
2482/// The allowed values equate to alignment on 1, 2, 4, or 8 byte boundaries.
2483/// Note that variable-length types must have an alignment of at least 4, since
2484/// they necessarily contain an int4 as their first component.
2485///
2486/// # PostgreSQL Documentation
2487/// See: <https://www.postgresql.org/docs/current/sql-createtype.html>
2488///
2489/// # Examples
2490/// ```sql
2491/// CREATE TYPE mytype (
2492///     INPUT = in_func,
2493///     OUTPUT = out_func,
2494///     ALIGNMENT = int4  -- 4-byte alignment
2495/// );
2496/// ```
2497#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2498#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2499#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2500pub enum Alignment {
2501    /// Single-byte alignment: `ALIGNMENT = char`
2502    Char,
2503    /// 2-byte alignment: `ALIGNMENT = int2`
2504    Int2,
2505    /// 4-byte alignment: `ALIGNMENT = int4`
2506    Int4,
2507    /// 8-byte alignment: `ALIGNMENT = double`
2508    Double,
2509}
2510
2511impl fmt::Display for Alignment {
2512    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2513        match self {
2514            Alignment::Char => write!(f, "char"),
2515            Alignment::Int2 => write!(f, "int2"),
2516            Alignment::Int4 => write!(f, "int4"),
2517            Alignment::Double => write!(f, "double"),
2518        }
2519    }
2520}
2521
2522/// Storage specification for PostgreSQL user-defined base types.
2523///
2524/// Specifies the storage strategy for values of the data type:
2525/// - `plain`: Prevents compression and out-of-line storage (for fixed-length types)
2526/// - `external`: Allows out-of-line storage but not compression
2527/// - `extended`: Allows both compression and out-of-line storage (default for most types)
2528/// - `main`: Allows compression but discourages out-of-line storage
2529///
2530/// # PostgreSQL Documentation
2531/// See: <https://www.postgresql.org/docs/current/sql-createtype.html>
2532///
2533/// # Examples
2534/// ```sql
2535/// CREATE TYPE mytype (
2536///     INPUT = in_func,
2537///     OUTPUT = out_func,
2538///     STORAGE = plain
2539/// );
2540/// ```
2541#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2542#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2543#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2544pub enum UserDefinedTypeStorage {
2545    /// No compression or out-of-line storage: `STORAGE = plain`
2546    Plain,
2547    /// Out-of-line storage allowed, no compression: `STORAGE = external`
2548    External,
2549    /// Both compression and out-of-line storage allowed: `STORAGE = extended`
2550    Extended,
2551    /// Compression allowed, out-of-line discouraged: `STORAGE = main`
2552    Main,
2553}
2554
2555impl fmt::Display for UserDefinedTypeStorage {
2556    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2557        match self {
2558            UserDefinedTypeStorage::Plain => write!(f, "plain"),
2559            UserDefinedTypeStorage::External => write!(f, "external"),
2560            UserDefinedTypeStorage::Extended => write!(f, "extended"),
2561            UserDefinedTypeStorage::Main => write!(f, "main"),
2562        }
2563    }
2564}
2565
2566/// Options for PostgreSQL `CREATE TYPE ... AS RANGE` statement.
2567///
2568/// Range types are data types representing a range of values of some element type
2569/// (called the range's subtype). These options configure the behavior of the range type.
2570///
2571/// # PostgreSQL Documentation
2572/// See: <https://www.postgresql.org/docs/current/sql-createtype.html>
2573///
2574/// # Examples
2575/// ```sql
2576/// CREATE TYPE int4range AS RANGE (
2577///     SUBTYPE = int4,
2578///     SUBTYPE_OPCLASS = int4_ops,
2579///     CANONICAL = int4range_canonical,
2580///     SUBTYPE_DIFF = int4range_subdiff
2581/// );
2582/// ```
2583#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2584#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2585#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2586pub enum UserDefinedTypeRangeOption {
2587    /// The element type that the range type will represent: `SUBTYPE = subtype`
2588    Subtype(DataType),
2589    /// The operator class for the subtype: `SUBTYPE_OPCLASS = subtype_operator_class`
2590    SubtypeOpClass(ObjectName),
2591    /// Collation to use for ordering the subtype: `COLLATION = collation`
2592    Collation(ObjectName),
2593    /// Function to convert range values to canonical form: `CANONICAL = canonical_function`
2594    Canonical(ObjectName),
2595    /// Function to compute the difference between two subtype values: `SUBTYPE_DIFF = subtype_diff_function`
2596    SubtypeDiff(ObjectName),
2597    /// Name of the corresponding multirange type: `MULTIRANGE_TYPE_NAME = multirange_type_name`
2598    MultirangeTypeName(ObjectName),
2599}
2600
2601impl fmt::Display for UserDefinedTypeRangeOption {
2602    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2603        match self {
2604            UserDefinedTypeRangeOption::Subtype(dt) => write!(f, "SUBTYPE = {}", dt),
2605            UserDefinedTypeRangeOption::SubtypeOpClass(name) => {
2606                write!(f, "SUBTYPE_OPCLASS = {}", name)
2607            }
2608            UserDefinedTypeRangeOption::Collation(name) => write!(f, "COLLATION = {}", name),
2609            UserDefinedTypeRangeOption::Canonical(name) => write!(f, "CANONICAL = {}", name),
2610            UserDefinedTypeRangeOption::SubtypeDiff(name) => write!(f, "SUBTYPE_DIFF = {}", name),
2611            UserDefinedTypeRangeOption::MultirangeTypeName(name) => {
2612                write!(f, "MULTIRANGE_TYPE_NAME = {}", name)
2613            }
2614        }
2615    }
2616}
2617
2618/// Options for PostgreSQL `CREATE TYPE ... (<options>)` statement (base type definition).
2619///
2620/// Base types are the lowest-level data types in PostgreSQL. To define a new base type,
2621/// you must specify functions that convert it to and from text representation, and optionally
2622/// binary representation and other properties.
2623///
2624/// Note: This syntax uses parentheses directly after the type name, without the `AS` keyword.
2625///
2626/// # PostgreSQL Documentation
2627/// See: <https://www.postgresql.org/docs/current/sql-createtype.html>
2628///
2629/// # Examples
2630/// ```sql
2631/// CREATE TYPE complex (
2632///     INPUT = complex_in,
2633///     OUTPUT = complex_out,
2634///     INTERNALLENGTH = 16,
2635///     ALIGNMENT = double
2636/// );
2637/// ```
2638#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2639#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2640#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2641pub enum UserDefinedTypeSqlDefinitionOption {
2642    /// Function to convert from external text representation to internal: `INPUT = input_function`
2643    Input(ObjectName),
2644    /// Function to convert from internal to external text representation: `OUTPUT = output_function`
2645    Output(ObjectName),
2646    /// Function to convert from external binary representation to internal: `RECEIVE = receive_function`
2647    Receive(ObjectName),
2648    /// Function to convert from internal to external binary representation: `SEND = send_function`
2649    Send(ObjectName),
2650    /// Function to convert type modifiers from text array to internal form: `TYPMOD_IN = type_modifier_input_function`
2651    TypmodIn(ObjectName),
2652    /// Function to convert type modifiers from internal to text form: `TYPMOD_OUT = type_modifier_output_function`
2653    TypmodOut(ObjectName),
2654    /// Function to compute statistics for the data type: `ANALYZE = analyze_function`
2655    Analyze(ObjectName),
2656    /// Function to handle subscripting operations: `SUBSCRIPT = subscript_function`
2657    Subscript(ObjectName),
2658    /// Internal storage size in bytes, or VARIABLE for variable-length: `INTERNALLENGTH = { internallength | VARIABLE }`
2659    InternalLength(UserDefinedTypeInternalLength),
2660    /// Indicates values are passed by value rather than by reference: `PASSEDBYVALUE`
2661    PassedByValue,
2662    /// Storage alignment requirement (1, 2, 4, or 8 bytes): `ALIGNMENT = alignment`
2663    Alignment(Alignment),
2664    /// Storage strategy for varlena types: `STORAGE = storage`
2665    Storage(UserDefinedTypeStorage),
2666    /// Copy properties from an existing type: `LIKE = like_type`
2667    Like(ObjectName),
2668    /// Type category for implicit casting rules (single char): `CATEGORY = category`
2669    Category(char),
2670    /// Whether this type is preferred within its category: `PREFERRED = preferred`
2671    Preferred(bool),
2672    /// Default value for the type: `DEFAULT = default`
2673    Default(Expr),
2674    /// Element type for array types: `ELEMENT = element`
2675    Element(DataType),
2676    /// Delimiter character for array value display: `DELIMITER = delimiter`
2677    Delimiter(String),
2678    /// Whether the type supports collation: `COLLATABLE = collatable`
2679    Collatable(bool),
2680}
2681
2682impl fmt::Display for UserDefinedTypeSqlDefinitionOption {
2683    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2684        match self {
2685            UserDefinedTypeSqlDefinitionOption::Input(name) => write!(f, "INPUT = {}", name),
2686            UserDefinedTypeSqlDefinitionOption::Output(name) => write!(f, "OUTPUT = {}", name),
2687            UserDefinedTypeSqlDefinitionOption::Receive(name) => write!(f, "RECEIVE = {}", name),
2688            UserDefinedTypeSqlDefinitionOption::Send(name) => write!(f, "SEND = {}", name),
2689            UserDefinedTypeSqlDefinitionOption::TypmodIn(name) => write!(f, "TYPMOD_IN = {}", name),
2690            UserDefinedTypeSqlDefinitionOption::TypmodOut(name) => {
2691                write!(f, "TYPMOD_OUT = {}", name)
2692            }
2693            UserDefinedTypeSqlDefinitionOption::Analyze(name) => write!(f, "ANALYZE = {}", name),
2694            UserDefinedTypeSqlDefinitionOption::Subscript(name) => {
2695                write!(f, "SUBSCRIPT = {}", name)
2696            }
2697            UserDefinedTypeSqlDefinitionOption::InternalLength(len) => {
2698                write!(f, "INTERNALLENGTH = {}", len)
2699            }
2700            UserDefinedTypeSqlDefinitionOption::PassedByValue => write!(f, "PASSEDBYVALUE"),
2701            UserDefinedTypeSqlDefinitionOption::Alignment(align) => {
2702                write!(f, "ALIGNMENT = {}", align)
2703            }
2704            UserDefinedTypeSqlDefinitionOption::Storage(storage) => {
2705                write!(f, "STORAGE = {}", storage)
2706            }
2707            UserDefinedTypeSqlDefinitionOption::Like(name) => write!(f, "LIKE = {}", name),
2708            UserDefinedTypeSqlDefinitionOption::Category(c) => write!(f, "CATEGORY = '{}'", c),
2709            UserDefinedTypeSqlDefinitionOption::Preferred(b) => write!(f, "PREFERRED = {}", b),
2710            UserDefinedTypeSqlDefinitionOption::Default(expr) => write!(f, "DEFAULT = {}", expr),
2711            UserDefinedTypeSqlDefinitionOption::Element(dt) => write!(f, "ELEMENT = {}", dt),
2712            UserDefinedTypeSqlDefinitionOption::Delimiter(s) => {
2713                write!(f, "DELIMITER = '{}'", escape_single_quote_string(s))
2714            }
2715            UserDefinedTypeSqlDefinitionOption::Collatable(b) => write!(f, "COLLATABLE = {}", b),
2716        }
2717    }
2718}
2719
2720/// PARTITION statement used in ALTER TABLE et al. such as in Hive and ClickHouse SQL.
2721/// For example, ClickHouse's OPTIMIZE TABLE supports syntax like PARTITION ID 'partition_id' and PARTITION expr.
2722/// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/optimize)
2723#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2724#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2725#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2726pub enum Partition {
2727    /// ClickHouse supports PARTITION ID 'partition_id' syntax.
2728    Identifier(Ident),
2729    /// ClickHouse supports PARTITION expr syntax.
2730    Expr(Expr),
2731    /// ClickHouse supports PART expr which represents physical partition in disk.
2732    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/partition#attach-partitionpart)
2733    Part(Expr),
2734    /// Hive supports multiple partitions in PARTITION (part1, part2, ...) syntax.
2735    Partitions(Vec<Expr>),
2736}
2737
2738impl fmt::Display for Partition {
2739    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2740        match self {
2741            Partition::Identifier(id) => write!(f, "PARTITION ID {id}"),
2742            Partition::Expr(expr) => write!(f, "PARTITION {expr}"),
2743            Partition::Part(expr) => write!(f, "PART {expr}"),
2744            Partition::Partitions(partitions) => {
2745                write!(f, "PARTITION ({})", display_comma_separated(partitions))
2746            }
2747        }
2748    }
2749}
2750
2751/// DEDUPLICATE statement used in OPTIMIZE TABLE et al. such as in ClickHouse SQL
2752/// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/optimize)
2753#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2754#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2755#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2756pub enum Deduplicate {
2757    /// DEDUPLICATE ALL
2758    All,
2759    /// DEDUPLICATE BY expr
2760    ByExpression(Expr),
2761}
2762
2763impl fmt::Display for Deduplicate {
2764    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2765        match self {
2766            Deduplicate::All => write!(f, "DEDUPLICATE"),
2767            Deduplicate::ByExpression(expr) => write!(f, "DEDUPLICATE BY {expr}"),
2768        }
2769    }
2770}
2771
2772/// Hive supports `CLUSTERED BY` statement in `CREATE TABLE`.
2773/// Syntax: `CLUSTERED BY (col_name, ...) [SORTED BY (col_name [ASC|DESC], ...)] INTO num_buckets BUCKETS`
2774///
2775/// [Hive](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-CreateTable)
2776#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2777#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2778#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2779pub struct ClusteredBy {
2780    /// columns used for clustering
2781    pub columns: Vec<Ident>,
2782    /// optional sorted by expressions
2783    pub sorted_by: Option<Vec<OrderByExpr>>,
2784    /// number of buckets
2785    pub num_buckets: Value,
2786}
2787
2788impl fmt::Display for ClusteredBy {
2789    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2790        write!(
2791            f,
2792            "CLUSTERED BY ({})",
2793            display_comma_separated(&self.columns)
2794        )?;
2795        if let Some(ref sorted_by) = self.sorted_by {
2796            write!(f, " SORTED BY ({})", display_comma_separated(sorted_by))?;
2797        }
2798        write!(f, " INTO {} BUCKETS", self.num_buckets)
2799    }
2800}
2801
2802/// CREATE INDEX statement.
2803#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2804#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2805#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2806pub struct CreateIndex {
2807    /// index name
2808    pub name: Option<ObjectName>,
2809    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2810    /// table name
2811    pub table_name: ObjectName,
2812    /// Index type used in the statement. Can also be found inside [`CreateIndex::index_options`]
2813    /// depending on the position of the option within the statement.
2814    pub using: Option<IndexType>,
2815    /// columns included in the index
2816    pub columns: Vec<IndexColumn>,
2817    /// whether the index is unique
2818    pub unique: bool,
2819    /// whether the index is created concurrently
2820    pub concurrently: bool,
2821    /// IF NOT EXISTS clause
2822    pub if_not_exists: bool,
2823    /// INCLUDE clause: <https://www.postgresql.org/docs/current/sql-createindex.html>
2824    pub include: Vec<Ident>,
2825    /// NULLS DISTINCT / NOT DISTINCT clause: <https://www.postgresql.org/docs/current/sql-createindex.html>
2826    pub nulls_distinct: Option<bool>,
2827    /// WITH clause: <https://www.postgresql.org/docs/current/sql-createindex.html>
2828    pub with: Vec<Expr>,
2829    /// WHERE clause: <https://www.postgresql.org/docs/current/sql-createindex.html>
2830    pub predicate: Option<Expr>,
2831    /// Index options: <https://www.postgresql.org/docs/current/sql-createindex.html>
2832    pub index_options: Vec<IndexOption>,
2833    /// [MySQL] allows a subset of options normally used for `ALTER TABLE`:
2834    ///
2835    /// - `ALGORITHM`
2836    /// - `LOCK`
2837    ///
2838    /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/create-index.html
2839    pub alter_options: Vec<AlterTableOperation>,
2840}
2841
2842impl fmt::Display for CreateIndex {
2843    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2844        write!(
2845            f,
2846            "CREATE {unique}INDEX {concurrently}{if_not_exists}",
2847            unique = if self.unique { "UNIQUE " } else { "" },
2848            concurrently = if self.concurrently {
2849                "CONCURRENTLY "
2850            } else {
2851                ""
2852            },
2853            if_not_exists = if self.if_not_exists {
2854                "IF NOT EXISTS "
2855            } else {
2856                ""
2857            },
2858        )?;
2859        if let Some(value) = &self.name {
2860            write!(f, "{value} ")?;
2861        }
2862        write!(f, "ON {}", self.table_name)?;
2863        if let Some(value) = &self.using {
2864            write!(f, " USING {value} ")?;
2865        }
2866        write!(f, "({})", display_comma_separated(&self.columns))?;
2867        if !self.include.is_empty() {
2868            write!(f, " INCLUDE ({})", display_comma_separated(&self.include))?;
2869        }
2870        if let Some(value) = self.nulls_distinct {
2871            if value {
2872                write!(f, " NULLS DISTINCT")?;
2873            } else {
2874                write!(f, " NULLS NOT DISTINCT")?;
2875            }
2876        }
2877        if !self.with.is_empty() {
2878            write!(f, " WITH ({})", display_comma_separated(&self.with))?;
2879        }
2880        if let Some(predicate) = &self.predicate {
2881            write!(f, " WHERE {predicate}")?;
2882        }
2883        if !self.index_options.is_empty() {
2884            write!(f, " {}", display_separated(&self.index_options, " "))?;
2885        }
2886        if !self.alter_options.is_empty() {
2887            write!(f, " {}", display_separated(&self.alter_options, " "))?;
2888        }
2889        Ok(())
2890    }
2891}
2892
2893/// CREATE TABLE statement.
2894#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2895#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2896#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2897pub struct CreateTable {
2898    /// `OR REPLACE` clause
2899    pub or_replace: bool,
2900    /// `TEMP` or `TEMPORARY` clause
2901    pub temporary: bool,
2902    /// `EXTERNAL` clause
2903    pub external: bool,
2904    /// `DYNAMIC` clause
2905    pub dynamic: bool,
2906    /// `GLOBAL` clause
2907    pub global: Option<bool>,
2908    /// `IF NOT EXISTS` clause
2909    pub if_not_exists: bool,
2910    /// `TRANSIENT` clause
2911    pub transient: bool,
2912    /// `VOLATILE` clause
2913    pub volatile: bool,
2914    /// `ICEBERG` clause
2915    pub iceberg: bool,
2916    /// `SNAPSHOT` clause
2917    /// <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_snapshot_table_statement>
2918    pub snapshot: bool,
2919    /// Table name
2920    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2921    pub name: ObjectName,
2922    /// Column definitions
2923    pub columns: Vec<ColumnDef>,
2924    /// Table constraints
2925    pub constraints: Vec<TableConstraint>,
2926    /// Hive-specific distribution style
2927    pub hive_distribution: HiveDistributionStyle,
2928    /// Hive-specific formats like `ROW FORMAT DELIMITED` or `ROW FORMAT SERDE 'serde_class' WITH SERDEPROPERTIES (...)`
2929    pub hive_formats: Option<HiveFormat>,
2930    /// Table options
2931    pub table_options: CreateTableOptions,
2932    /// General comment for the table
2933    pub file_format: Option<FileFormat>,
2934    /// Location of the table data
2935    pub location: Option<String>,
2936    /// Query used to populate the table
2937    pub query: Option<Box<Query>>,
2938    /// If the table should be created without a rowid (SQLite)
2939    pub without_rowid: bool,
2940    /// `LIKE` clause
2941    pub like: Option<CreateTableLikeKind>,
2942    /// `CLONE` clause
2943    pub clone: Option<ObjectName>,
2944    /// Table version (for systems that support versioned tables)
2945    pub version: Option<TableVersion>,
2946    /// For Hive dialect, the table comment is after the column definitions without `=`,
2947    /// so the `comment` field is optional and different than the comment field in the general options list.
2948    /// [Hive](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-CreateTable)
2949    pub comment: Option<CommentDef>,
2950    /// ClickHouse "ON COMMIT" clause:
2951    /// <https://clickhouse.com/docs/en/sql-reference/statements/create/table/>
2952    pub on_commit: Option<OnCommit>,
2953    /// ClickHouse "ON CLUSTER" clause:
2954    /// <https://clickhouse.com/docs/en/sql-reference/distributed-ddl/>
2955    pub on_cluster: Option<Ident>,
2956    /// ClickHouse "PRIMARY KEY " clause.
2957    /// <https://clickhouse.com/docs/en/sql-reference/statements/create/table/>
2958    pub primary_key: Option<Box<Expr>>,
2959    /// ClickHouse "ORDER BY " clause. Note that omitted ORDER BY is different
2960    /// than empty (represented as ()), the latter meaning "no sorting".
2961    /// <https://clickhouse.com/docs/en/sql-reference/statements/create/table/>
2962    pub order_by: Option<OneOrManyWithParens<Expr>>,
2963    /// BigQuery: A partition expression for the table.
2964    /// <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#partition_expression>
2965    pub partition_by: Option<Box<Expr>>,
2966    /// BigQuery: Table clustering column list.
2967    /// <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#table_option_list>
2968    /// Snowflake: Table clustering list which contains base column, expressions on base columns.
2969    /// <https://docs.snowflake.com/en/user-guide/tables-clustering-keys#defining-a-clustering-key-for-a-table>
2970    pub cluster_by: Option<WrappedCollection<Vec<Expr>>>,
2971    /// Hive: Table clustering column list.
2972    /// <https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-CreateTable>
2973    pub clustered_by: Option<ClusteredBy>,
2974    /// Postgres `INHERITs` clause, which contains the list of tables from which
2975    /// the new table inherits.
2976    /// <https://www.postgresql.org/docs/current/ddl-inherit.html>
2977    /// <https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-PARMS-INHERITS>
2978    pub inherits: Option<Vec<ObjectName>>,
2979    /// PostgreSQL `PARTITION OF` clause to create a partition of a parent table.
2980    /// Contains the parent table name.
2981    /// <https://www.postgresql.org/docs/current/sql-createtable.html>
2982    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2983    pub partition_of: Option<ObjectName>,
2984    /// PostgreSQL partition bound specification for PARTITION OF.
2985    /// <https://www.postgresql.org/docs/current/sql-createtable.html>
2986    pub for_values: Option<ForValues>,
2987    /// SQLite "STRICT" clause.
2988    /// if the "STRICT" table-option keyword is added to the end, after the closing ")",
2989    /// then strict typing rules apply to that table.
2990    pub strict: bool,
2991    /// Snowflake "COPY GRANTS" clause
2992    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
2993    pub copy_grants: bool,
2994    /// Snowflake "ENABLE_SCHEMA_EVOLUTION" clause
2995    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
2996    pub enable_schema_evolution: Option<bool>,
2997    /// Snowflake "CHANGE_TRACKING" clause
2998    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
2999    pub change_tracking: Option<bool>,
3000    /// Snowflake "DATA_RETENTION_TIME_IN_DAYS" clause
3001    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
3002    pub data_retention_time_in_days: Option<u64>,
3003    /// Snowflake "MAX_DATA_EXTENSION_TIME_IN_DAYS" clause
3004    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
3005    pub max_data_extension_time_in_days: Option<u64>,
3006    /// Snowflake "DEFAULT_DDL_COLLATION" clause
3007    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
3008    pub default_ddl_collation: Option<String>,
3009    /// Snowflake "WITH AGGREGATION POLICY" clause
3010    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
3011    pub with_aggregation_policy: Option<ObjectName>,
3012    /// Snowflake "WITH ROW ACCESS POLICY" clause
3013    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
3014    pub with_row_access_policy: Option<RowAccessPolicy>,
3015    /// Snowflake `WITH STORAGE LIFECYCLE POLICY` clause
3016    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
3017    pub with_storage_lifecycle_policy: Option<StorageLifecyclePolicy>,
3018    /// Snowflake "WITH TAG" clause
3019    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
3020    pub with_tags: Option<Vec<Tag>>,
3021    /// Snowflake "EXTERNAL_VOLUME" clause for Iceberg tables
3022    /// <https://docs.snowflake.com/en/sql-reference/sql/create-iceberg-table>
3023    pub external_volume: Option<String>,
3024    /// Snowflake "BASE_LOCATION" clause for Iceberg tables
3025    /// <https://docs.snowflake.com/en/sql-reference/sql/create-iceberg-table>
3026    pub base_location: Option<String>,
3027    /// Snowflake "CATALOG" clause for Iceberg tables
3028    /// <https://docs.snowflake.com/en/sql-reference/sql/create-iceberg-table>
3029    pub catalog: Option<String>,
3030    /// Snowflake "CATALOG_SYNC" clause for Iceberg tables
3031    /// <https://docs.snowflake.com/en/sql-reference/sql/create-iceberg-table>
3032    pub catalog_sync: Option<String>,
3033    /// Snowflake "STORAGE_SERIALIZATION_POLICY" clause for Iceberg tables
3034    /// <https://docs.snowflake.com/en/sql-reference/sql/create-iceberg-table>
3035    pub storage_serialization_policy: Option<StorageSerializationPolicy>,
3036    /// Snowflake "TARGET_LAG" clause for dybamic tables
3037    /// <https://docs.snowflake.com/en/sql-reference/sql/create-dynamic-table>
3038    pub target_lag: Option<String>,
3039    /// Snowflake "WAREHOUSE" clause for dybamic tables
3040    /// <https://docs.snowflake.com/en/sql-reference/sql/create-dynamic-table>
3041    pub warehouse: Option<Ident>,
3042    /// Snowflake "REFRESH_MODE" clause for dybamic tables
3043    /// <https://docs.snowflake.com/en/sql-reference/sql/create-dynamic-table>
3044    pub refresh_mode: Option<RefreshModeKind>,
3045    /// Snowflake "INITIALIZE" clause for dybamic tables
3046    /// <https://docs.snowflake.com/en/sql-reference/sql/create-dynamic-table>
3047    pub initialize: Option<InitializeKind>,
3048    /// Snowflake "REQUIRE USER" clause for dybamic tables
3049    /// <https://docs.snowflake.com/en/sql-reference/sql/create-dynamic-table>
3050    pub require_user: bool,
3051    /// Redshift `DISTSTYLE` option
3052    /// <https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html>
3053    pub diststyle: Option<DistStyle>,
3054    /// Redshift `DISTKEY` option
3055    /// <https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html>
3056    pub distkey: Option<Expr>,
3057    /// Redshift `SORTKEY` option
3058    /// <https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html>
3059    pub sortkey: Option<Vec<Expr>>,
3060    /// Redshift `BACKUP` option: `BACKUP { YES | NO }`
3061    /// <https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html>
3062    pub backup: Option<bool>,
3063}
3064
3065impl fmt::Display for CreateTable {
3066    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3067        // We want to allow the following options
3068        // Empty column list, allowed by PostgreSQL:
3069        //   `CREATE TABLE t ()`
3070        // No columns provided for CREATE TABLE AS:
3071        //   `CREATE TABLE t AS SELECT a from t2`
3072        // Columns provided for CREATE TABLE AS:
3073        //   `CREATE TABLE t (a INT) AS SELECT a from t2`
3074        write!(
3075            f,
3076            "CREATE {or_replace}{external}{global}{temporary}{transient}{volatile}{dynamic}{iceberg}{snapshot}TABLE {if_not_exists}{name}",
3077            or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3078            external = if self.external { "EXTERNAL " } else { "" },
3079            snapshot = if self.snapshot { "SNAPSHOT " } else { "" },
3080            global = self.global
3081                .map(|global| {
3082                    if global {
3083                        "GLOBAL "
3084                    } else {
3085                        "LOCAL "
3086                    }
3087                })
3088                .unwrap_or(""),
3089            if_not_exists = if self.if_not_exists { "IF NOT EXISTS " } else { "" },
3090            temporary = if self.temporary { "TEMPORARY " } else { "" },
3091            transient = if self.transient { "TRANSIENT " } else { "" },
3092            volatile = if self.volatile { "VOLATILE " } else { "" },
3093            // Only for Snowflake
3094            iceberg = if self.iceberg { "ICEBERG " } else { "" },
3095            dynamic = if self.dynamic { "DYNAMIC " } else { "" },
3096            name = self.name,
3097        )?;
3098        if let Some(partition_of) = &self.partition_of {
3099            write!(f, " PARTITION OF {partition_of}")?;
3100        }
3101        if let Some(on_cluster) = &self.on_cluster {
3102            write!(f, " ON CLUSTER {on_cluster}")?;
3103        }
3104        if !self.columns.is_empty() || !self.constraints.is_empty() {
3105            f.write_str(" (")?;
3106            NewLine.fmt(f)?;
3107            Indent(DisplayCommaSeparated(&self.columns)).fmt(f)?;
3108            if !self.columns.is_empty() && !self.constraints.is_empty() {
3109                f.write_str(",")?;
3110                SpaceOrNewline.fmt(f)?;
3111            }
3112            Indent(DisplayCommaSeparated(&self.constraints)).fmt(f)?;
3113            NewLine.fmt(f)?;
3114            f.write_str(")")?;
3115        } else if self.query.is_none()
3116            && self.like.is_none()
3117            && self.clone.is_none()
3118            && self.partition_of.is_none()
3119        {
3120            // PostgreSQL allows `CREATE TABLE t ();`, but requires empty parens
3121            f.write_str(" ()")?;
3122        } else if let Some(CreateTableLikeKind::Parenthesized(like_in_columns_list)) = &self.like {
3123            write!(f, " ({like_in_columns_list})")?;
3124        }
3125        if let Some(for_values) = &self.for_values {
3126            write!(f, " {for_values}")?;
3127        }
3128
3129        // Hive table comment should be after column definitions, please refer to:
3130        // [Hive](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-CreateTable)
3131        if let Some(comment) = &self.comment {
3132            write!(f, " COMMENT '{comment}'")?;
3133        }
3134
3135        // Only for SQLite
3136        if self.without_rowid {
3137            write!(f, " WITHOUT ROWID")?;
3138        }
3139
3140        if let Some(CreateTableLikeKind::Plain(like)) = &self.like {
3141            write!(f, " {like}")?;
3142        }
3143
3144        if let Some(c) = &self.clone {
3145            write!(f, " CLONE {c}")?;
3146        }
3147
3148        if let Some(version) = &self.version {
3149            write!(f, " {version}")?;
3150        }
3151
3152        match &self.hive_distribution {
3153            HiveDistributionStyle::PARTITIONED { columns } => {
3154                write!(f, " PARTITIONED BY ({})", display_comma_separated(columns))?;
3155            }
3156            HiveDistributionStyle::SKEWED {
3157                columns,
3158                on,
3159                stored_as_directories,
3160            } => {
3161                write!(
3162                    f,
3163                    " SKEWED BY ({})) ON ({})",
3164                    display_comma_separated(columns),
3165                    display_comma_separated(on)
3166                )?;
3167                if *stored_as_directories {
3168                    write!(f, " STORED AS DIRECTORIES")?;
3169                }
3170            }
3171            _ => (),
3172        }
3173
3174        if let Some(clustered_by) = &self.clustered_by {
3175            write!(f, " {clustered_by}")?;
3176        }
3177
3178        if let Some(HiveFormat {
3179            row_format,
3180            serde_properties,
3181            storage,
3182            location,
3183        }) = &self.hive_formats
3184        {
3185            match row_format {
3186                Some(HiveRowFormat::SERDE { class }) => write!(f, " ROW FORMAT SERDE '{class}'")?,
3187                Some(HiveRowFormat::DELIMITED { delimiters }) => {
3188                    write!(f, " ROW FORMAT DELIMITED")?;
3189                    if !delimiters.is_empty() {
3190                        write!(f, " {}", display_separated(delimiters, " "))?;
3191                    }
3192                }
3193                None => (),
3194            }
3195            match storage {
3196                Some(HiveIOFormat::IOF {
3197                    input_format,
3198                    output_format,
3199                }) => write!(
3200                    f,
3201                    " STORED AS INPUTFORMAT {input_format} OUTPUTFORMAT {output_format}"
3202                )?,
3203                Some(HiveIOFormat::FileFormat { format }) if !self.external => {
3204                    write!(f, " STORED AS {format}")?
3205                }
3206                _ => (),
3207            }
3208            if let Some(serde_properties) = serde_properties.as_ref() {
3209                write!(
3210                    f,
3211                    " WITH SERDEPROPERTIES ({})",
3212                    display_comma_separated(serde_properties)
3213                )?;
3214            }
3215            if !self.external {
3216                if let Some(loc) = location {
3217                    write!(f, " LOCATION '{loc}'")?;
3218                }
3219            }
3220        }
3221        if self.external {
3222            if let Some(file_format) = self.file_format {
3223                write!(f, " STORED AS {file_format}")?;
3224            }
3225            if let Some(location) = &self.location {
3226                write!(f, " LOCATION '{location}'")?;
3227            }
3228        }
3229
3230        match &self.table_options {
3231            options @ CreateTableOptions::With(_)
3232            | options @ CreateTableOptions::Plain(_)
3233            | options @ CreateTableOptions::TableProperties(_) => write!(f, " {options}")?,
3234            _ => (),
3235        }
3236
3237        if let Some(primary_key) = &self.primary_key {
3238            write!(f, " PRIMARY KEY {primary_key}")?;
3239        }
3240        if let Some(order_by) = &self.order_by {
3241            write!(f, " ORDER BY {order_by}")?;
3242        }
3243        if let Some(inherits) = &self.inherits {
3244            write!(f, " INHERITS ({})", display_comma_separated(inherits))?;
3245        }
3246        if let Some(partition_by) = self.partition_by.as_ref() {
3247            write!(f, " PARTITION BY {partition_by}")?;
3248        }
3249        if let Some(cluster_by) = self.cluster_by.as_ref() {
3250            write!(f, " CLUSTER BY {cluster_by}")?;
3251        }
3252        if let options @ CreateTableOptions::Options(_) = &self.table_options {
3253            write!(f, " {options}")?;
3254        }
3255        if let Some(external_volume) = self.external_volume.as_ref() {
3256            write!(f, " EXTERNAL_VOLUME='{external_volume}'")?;
3257        }
3258
3259        if let Some(catalog) = self.catalog.as_ref() {
3260            write!(f, " CATALOG='{catalog}'")?;
3261        }
3262
3263        if self.iceberg {
3264            if let Some(base_location) = self.base_location.as_ref() {
3265                write!(f, " BASE_LOCATION='{base_location}'")?;
3266            }
3267        }
3268
3269        if let Some(catalog_sync) = self.catalog_sync.as_ref() {
3270            write!(f, " CATALOG_SYNC='{catalog_sync}'")?;
3271        }
3272
3273        if let Some(storage_serialization_policy) = self.storage_serialization_policy.as_ref() {
3274            write!(
3275                f,
3276                " STORAGE_SERIALIZATION_POLICY={storage_serialization_policy}"
3277            )?;
3278        }
3279
3280        if self.copy_grants {
3281            write!(f, " COPY GRANTS")?;
3282        }
3283
3284        if let Some(is_enabled) = self.enable_schema_evolution {
3285            write!(
3286                f,
3287                " ENABLE_SCHEMA_EVOLUTION={}",
3288                if is_enabled { "TRUE" } else { "FALSE" }
3289            )?;
3290        }
3291
3292        if let Some(is_enabled) = self.change_tracking {
3293            write!(
3294                f,
3295                " CHANGE_TRACKING={}",
3296                if is_enabled { "TRUE" } else { "FALSE" }
3297            )?;
3298        }
3299
3300        if let Some(data_retention_time_in_days) = self.data_retention_time_in_days {
3301            write!(
3302                f,
3303                " DATA_RETENTION_TIME_IN_DAYS={data_retention_time_in_days}",
3304            )?;
3305        }
3306
3307        if let Some(max_data_extension_time_in_days) = self.max_data_extension_time_in_days {
3308            write!(
3309                f,
3310                " MAX_DATA_EXTENSION_TIME_IN_DAYS={max_data_extension_time_in_days}",
3311            )?;
3312        }
3313
3314        if let Some(default_ddl_collation) = &self.default_ddl_collation {
3315            write!(f, " DEFAULT_DDL_COLLATION='{default_ddl_collation}'",)?;
3316        }
3317
3318        if let Some(with_aggregation_policy) = &self.with_aggregation_policy {
3319            write!(f, " WITH AGGREGATION POLICY {with_aggregation_policy}",)?;
3320        }
3321
3322        if let Some(row_access_policy) = &self.with_row_access_policy {
3323            write!(f, " {row_access_policy}",)?;
3324        }
3325
3326        if let Some(storage_lifecycle_policy) = &self.with_storage_lifecycle_policy {
3327            write!(f, " {storage_lifecycle_policy}",)?;
3328        }
3329
3330        if let Some(tag) = &self.with_tags {
3331            write!(f, " WITH TAG ({})", display_comma_separated(tag.as_slice()))?;
3332        }
3333
3334        if let Some(target_lag) = &self.target_lag {
3335            write!(f, " TARGET_LAG='{target_lag}'")?;
3336        }
3337
3338        if let Some(warehouse) = &self.warehouse {
3339            write!(f, " WAREHOUSE={warehouse}")?;
3340        }
3341
3342        if let Some(refresh_mode) = &self.refresh_mode {
3343            write!(f, " REFRESH_MODE={refresh_mode}")?;
3344        }
3345
3346        if let Some(initialize) = &self.initialize {
3347            write!(f, " INITIALIZE={initialize}")?;
3348        }
3349
3350        if self.require_user {
3351            write!(f, " REQUIRE USER")?;
3352        }
3353
3354        if self.on_commit.is_some() {
3355            let on_commit = match self.on_commit {
3356                Some(OnCommit::DeleteRows) => "ON COMMIT DELETE ROWS",
3357                Some(OnCommit::PreserveRows) => "ON COMMIT PRESERVE ROWS",
3358                Some(OnCommit::Drop) => "ON COMMIT DROP",
3359                None => "",
3360            };
3361            write!(f, " {on_commit}")?;
3362        }
3363        if self.strict {
3364            write!(f, " STRICT")?;
3365        }
3366        if let Some(backup) = self.backup {
3367            write!(f, " BACKUP {}", if backup { "YES" } else { "NO" })?;
3368        }
3369        if let Some(diststyle) = &self.diststyle {
3370            write!(f, " DISTSTYLE {diststyle}")?;
3371        }
3372        if let Some(distkey) = &self.distkey {
3373            write!(f, " DISTKEY({distkey})")?;
3374        }
3375        if let Some(sortkey) = &self.sortkey {
3376            write!(f, " SORTKEY({})", display_comma_separated(sortkey))?;
3377        }
3378        if let Some(query) = &self.query {
3379            write!(f, " AS {query}")?;
3380        }
3381        Ok(())
3382    }
3383}
3384
3385/// PostgreSQL partition bound specification for `PARTITION OF`.
3386///
3387/// Specifies partition bounds for a child partition table.
3388///
3389/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtable.html)
3390#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3391#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3392#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3393pub enum ForValues {
3394    /// `FOR VALUES IN (expr, ...)`
3395    In(Vec<Expr>),
3396    /// `FOR VALUES FROM (expr|MINVALUE|MAXVALUE, ...) TO (expr|MINVALUE|MAXVALUE, ...)`
3397    From {
3398        /// The lower bound values for the partition.
3399        from: Vec<PartitionBoundValue>,
3400        /// The upper bound values for the partition.
3401        to: Vec<PartitionBoundValue>,
3402    },
3403    /// `FOR VALUES WITH (MODULUS n, REMAINDER r)`
3404    With {
3405        /// The modulus value for hash partitioning.
3406        modulus: u64,
3407        /// The remainder value for hash partitioning.
3408        remainder: u64,
3409    },
3410    /// `DEFAULT`
3411    Default,
3412}
3413
3414impl fmt::Display for ForValues {
3415    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3416        match self {
3417            ForValues::In(values) => {
3418                write!(f, "FOR VALUES IN ({})", display_comma_separated(values))
3419            }
3420            ForValues::From { from, to } => {
3421                write!(
3422                    f,
3423                    "FOR VALUES FROM ({}) TO ({})",
3424                    display_comma_separated(from),
3425                    display_comma_separated(to)
3426                )
3427            }
3428            ForValues::With { modulus, remainder } => {
3429                write!(
3430                    f,
3431                    "FOR VALUES WITH (MODULUS {modulus}, REMAINDER {remainder})"
3432                )
3433            }
3434            ForValues::Default => write!(f, "DEFAULT"),
3435        }
3436    }
3437}
3438
3439/// A value in a partition bound specification.
3440///
3441/// Used in RANGE partition bounds where values can be expressions,
3442/// MINVALUE (negative infinity), or MAXVALUE (positive infinity).
3443#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3444#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3445#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3446pub enum PartitionBoundValue {
3447    /// An expression representing a partition bound value.
3448    Expr(Expr),
3449    /// Represents negative infinity in partition bounds.
3450    MinValue,
3451    /// Represents positive infinity in partition bounds.
3452    MaxValue,
3453}
3454
3455impl fmt::Display for PartitionBoundValue {
3456    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3457        match self {
3458            PartitionBoundValue::Expr(expr) => write!(f, "{expr}"),
3459            PartitionBoundValue::MinValue => write!(f, "MINVALUE"),
3460            PartitionBoundValue::MaxValue => write!(f, "MAXVALUE"),
3461        }
3462    }
3463}
3464
3465/// Redshift distribution style for `CREATE TABLE`.
3466///
3467/// See [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html)
3468#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3469#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3470#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3471pub enum DistStyle {
3472    /// `DISTSTYLE AUTO`
3473    Auto,
3474    /// `DISTSTYLE EVEN`
3475    Even,
3476    /// `DISTSTYLE KEY`
3477    Key,
3478    /// `DISTSTYLE ALL`
3479    All,
3480}
3481
3482impl fmt::Display for DistStyle {
3483    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3484        match self {
3485            DistStyle::Auto => write!(f, "AUTO"),
3486            DistStyle::Even => write!(f, "EVEN"),
3487            DistStyle::Key => write!(f, "KEY"),
3488            DistStyle::All => write!(f, "ALL"),
3489        }
3490    }
3491}
3492
3493
3494#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3495#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3496#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3497/// ```sql
3498/// CREATE DOMAIN name [ AS ] data_type
3499///         [ COLLATE collation ]
3500///         [ DEFAULT expression ]
3501///         [ domain_constraint [ ... ] ]
3502///
3503///     where domain_constraint is:
3504///
3505///     [ CONSTRAINT constraint_name ]
3506///     { NOT NULL | NULL | CHECK (expression) }
3507/// ```
3508/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createdomain.html)
3509pub struct CreateDomain {
3510    /// The name of the domain to be created.
3511    pub name: ObjectName,
3512    /// The data type of the domain.
3513    pub data_type: DataType,
3514    /// The collation of the domain.
3515    pub collation: Option<Ident>,
3516    /// The default value of the domain.
3517    pub default: Option<Expr>,
3518    /// The constraints of the domain.
3519    pub constraints: Vec<TableConstraint>,
3520}
3521
3522impl fmt::Display for CreateDomain {
3523    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3524        write!(
3525            f,
3526            "CREATE DOMAIN {name} AS {data_type}",
3527            name = self.name,
3528            data_type = self.data_type
3529        )?;
3530        if let Some(collation) = &self.collation {
3531            write!(f, " COLLATE {collation}")?;
3532        }
3533        if let Some(default) = &self.default {
3534            write!(f, " DEFAULT {default}")?;
3535        }
3536        if !self.constraints.is_empty() {
3537            write!(f, " {}", display_separated(&self.constraints, " "))?;
3538        }
3539        Ok(())
3540    }
3541}
3542
3543/// The return type of a `CREATE FUNCTION` statement.
3544#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3545#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3546#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3547pub enum FunctionReturnType {
3548    /// `RETURNS <type>`
3549    DataType(DataType),
3550    /// `RETURNS SETOF <type>`
3551    ///
3552    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
3553    SetOf(DataType),
3554}
3555
3556impl fmt::Display for FunctionReturnType {
3557    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3558        match self {
3559            FunctionReturnType::DataType(data_type) => write!(f, "{data_type}"),
3560            FunctionReturnType::SetOf(data_type) => write!(f, "SETOF {data_type}"),
3561        }
3562    }
3563}
3564
3565#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3566#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3567#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3568/// CREATE FUNCTION statement
3569pub struct CreateFunction {
3570    /// True if this is a `CREATE OR ALTER FUNCTION` statement
3571    ///
3572    /// [MsSql](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql?view=sql-server-ver16#or-alter)
3573    pub or_alter: bool,
3574    /// True if this is a `CREATE OR REPLACE FUNCTION` statement
3575    pub or_replace: bool,
3576    /// True if this is a `CREATE TEMPORARY FUNCTION` statement
3577    pub temporary: bool,
3578    /// True if this is a `CREATE IF NOT EXISTS FUNCTION` statement
3579    pub if_not_exists: bool,
3580    /// Name of the function to be created.
3581    pub name: ObjectName,
3582    /// List of arguments for the function.
3583    pub args: Option<Vec<OperateFunctionArg>>,
3584    /// The return type of the function.
3585    pub return_type: Option<FunctionReturnType>,
3586    /// The expression that defines the function.
3587    ///
3588    /// Examples:
3589    /// ```sql
3590    /// AS ((SELECT 1))
3591    /// AS "console.log();"
3592    /// ```
3593    pub function_body: Option<CreateFunctionBody>,
3594    /// Behavior attribute for the function
3595    ///
3596    /// IMMUTABLE | STABLE | VOLATILE
3597    ///
3598    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
3599    pub behavior: Option<FunctionBehavior>,
3600    /// CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT
3601    ///
3602    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
3603    pub called_on_null: Option<FunctionCalledOnNull>,
3604    /// PARALLEL { UNSAFE | RESTRICTED | SAFE }
3605    ///
3606    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
3607    pub parallel: Option<FunctionParallel>,
3608    /// SECURITY { DEFINER | INVOKER }
3609    ///
3610    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
3611    pub security: Option<FunctionSecurity>,
3612    /// SET configuration_parameter clauses
3613    ///
3614    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
3615    pub set_params: Vec<FunctionDefinitionSetParam>,
3616    /// USING ... (Hive only)
3617    pub using: Option<CreateFunctionUsing>,
3618    /// Language used in a UDF definition.
3619    ///
3620    /// Example:
3621    /// ```sql
3622    /// CREATE FUNCTION foo() LANGUAGE js AS "console.log();"
3623    /// ```
3624    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_a_javascript_udf)
3625    pub language: Option<Ident>,
3626    /// Determinism keyword used for non-sql UDF definitions.
3627    ///
3628    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#syntax_11)
3629    pub determinism_specifier: Option<FunctionDeterminismSpecifier>,
3630    /// List of options for creating the function.
3631    ///
3632    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#syntax_11)
3633    pub options: Option<Vec<SqlOption>>,
3634    /// Connection resource for a remote function.
3635    ///
3636    /// Example:
3637    /// ```sql
3638    /// CREATE FUNCTION foo()
3639    /// RETURNS FLOAT64
3640    /// REMOTE WITH CONNECTION us.myconnection
3641    /// ```
3642    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_a_remote_function)
3643    pub remote_connection: Option<ObjectName>,
3644}
3645
3646impl fmt::Display for CreateFunction {
3647    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3648        write!(
3649            f,
3650            "CREATE {or_alter}{or_replace}{temp}FUNCTION {if_not_exists}{name}",
3651            name = self.name,
3652            temp = if self.temporary { "TEMPORARY " } else { "" },
3653            or_alter = if self.or_alter { "OR ALTER " } else { "" },
3654            or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3655            if_not_exists = if self.if_not_exists {
3656                "IF NOT EXISTS "
3657            } else {
3658                ""
3659            },
3660        )?;
3661        if let Some(args) = &self.args {
3662            write!(f, "({})", display_comma_separated(args))?;
3663        }
3664        if let Some(return_type) = &self.return_type {
3665            write!(f, " RETURNS {return_type}")?;
3666        }
3667        if let Some(determinism_specifier) = &self.determinism_specifier {
3668            write!(f, " {determinism_specifier}")?;
3669        }
3670        if let Some(language) = &self.language {
3671            write!(f, " LANGUAGE {language}")?;
3672        }
3673        if let Some(behavior) = &self.behavior {
3674            write!(f, " {behavior}")?;
3675        }
3676        if let Some(called_on_null) = &self.called_on_null {
3677            write!(f, " {called_on_null}")?;
3678        }
3679        if let Some(parallel) = &self.parallel {
3680            write!(f, " {parallel}")?;
3681        }
3682        if let Some(security) = &self.security {
3683            write!(f, " {security}")?;
3684        }
3685        for set_param in &self.set_params {
3686            write!(f, " {set_param}")?;
3687        }
3688        if let Some(remote_connection) = &self.remote_connection {
3689            write!(f, " REMOTE WITH CONNECTION {remote_connection}")?;
3690        }
3691        if let Some(CreateFunctionBody::AsBeforeOptions { body, link_symbol }) = &self.function_body
3692        {
3693            write!(f, " AS {body}")?;
3694            if let Some(link_symbol) = link_symbol {
3695                write!(f, ", {link_symbol}")?;
3696            }
3697        }
3698        if let Some(CreateFunctionBody::Return(function_body)) = &self.function_body {
3699            write!(f, " RETURN {function_body}")?;
3700        }
3701        if let Some(CreateFunctionBody::AsReturnExpr(function_body)) = &self.function_body {
3702            write!(f, " AS RETURN {function_body}")?;
3703        }
3704        if let Some(CreateFunctionBody::AsReturnSelect(function_body)) = &self.function_body {
3705            write!(f, " AS RETURN {function_body}")?;
3706        }
3707        if let Some(using) = &self.using {
3708            write!(f, " {using}")?;
3709        }
3710        if let Some(options) = &self.options {
3711            write!(
3712                f,
3713                " OPTIONS({})",
3714                display_comma_separated(options.as_slice())
3715            )?;
3716        }
3717        if let Some(CreateFunctionBody::AsAfterOptions(function_body)) = &self.function_body {
3718            write!(f, " AS {function_body}")?;
3719        }
3720        if let Some(CreateFunctionBody::AsBeginEnd(bes)) = &self.function_body {
3721            write!(f, " AS {bes}")?;
3722        }
3723        Ok(())
3724    }
3725}
3726
3727/// ```sql
3728/// CREATE CONNECTOR [IF NOT EXISTS] connector_name
3729/// [TYPE datasource_type]
3730/// [URL datasource_url]
3731/// [COMMENT connector_comment]
3732/// [WITH DCPROPERTIES(property_name=property_value, ...)]
3733/// ```
3734///
3735/// [Hive](https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=27362034#LanguageManualDDL-CreateDataConnectorCreateConnector)
3736#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3737#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3738#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3739pub struct CreateConnector {
3740    /// The name of the connector to be created.
3741    pub name: Ident,
3742    /// Whether `IF NOT EXISTS` was specified.
3743    pub if_not_exists: bool,
3744    /// The type of the connector.
3745    pub connector_type: Option<String>,
3746    /// The URL of the connector.
3747    pub url: Option<String>,
3748    /// The comment for the connector.
3749    pub comment: Option<CommentDef>,
3750    /// The DC properties for the connector.
3751    pub with_dcproperties: Option<Vec<SqlOption>>,
3752}
3753
3754impl fmt::Display for CreateConnector {
3755    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3756        write!(
3757            f,
3758            "CREATE CONNECTOR {if_not_exists}{name}",
3759            if_not_exists = if self.if_not_exists {
3760                "IF NOT EXISTS "
3761            } else {
3762                ""
3763            },
3764            name = self.name,
3765        )?;
3766
3767        if let Some(connector_type) = &self.connector_type {
3768            write!(f, " TYPE '{connector_type}'")?;
3769        }
3770
3771        if let Some(url) = &self.url {
3772            write!(f, " URL '{url}'")?;
3773        }
3774
3775        if let Some(comment) = &self.comment {
3776            write!(f, " COMMENT = '{comment}'")?;
3777        }
3778
3779        if let Some(with_dcproperties) = &self.with_dcproperties {
3780            write!(
3781                f,
3782                " WITH DCPROPERTIES({})",
3783                display_comma_separated(with_dcproperties)
3784            )?;
3785        }
3786
3787        Ok(())
3788    }
3789}
3790
3791/// An `ALTER SCHEMA` (`Statement::AlterSchema`) operation.
3792///
3793/// See [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#alter_schema_collate_statement)
3794/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-alterschema.html)
3795#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3796#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3797#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3798pub enum AlterSchemaOperation {
3799    /// Set the default collation for the schema.
3800    SetDefaultCollate {
3801        /// The collation to set as default.
3802        collate: Expr,
3803    },
3804    /// Add a replica to the schema.
3805    AddReplica {
3806        /// The replica to add.
3807        replica: Ident,
3808        /// Optional options for the replica.
3809        options: Option<Vec<SqlOption>>,
3810    },
3811    /// Drop a replica from the schema.
3812    DropReplica {
3813        /// The replica to drop.
3814        replica: Ident,
3815    },
3816    /// Set options for the schema.
3817    SetOptionsParens {
3818        /// The options to set.
3819        options: Vec<SqlOption>,
3820    },
3821    /// Rename the schema.
3822    Rename {
3823        /// The new name for the schema.
3824        name: ObjectName,
3825    },
3826    /// Change the owner of the schema.
3827    OwnerTo {
3828        /// The new owner of the schema.
3829        owner: Owner,
3830    },
3831}
3832
3833impl fmt::Display for AlterSchemaOperation {
3834    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3835        match self {
3836            AlterSchemaOperation::SetDefaultCollate { collate } => {
3837                write!(f, "SET DEFAULT COLLATE {collate}")
3838            }
3839            AlterSchemaOperation::AddReplica { replica, options } => {
3840                write!(f, "ADD REPLICA {replica}")?;
3841                if let Some(options) = options {
3842                    write!(f, " OPTIONS ({})", display_comma_separated(options))?;
3843                }
3844                Ok(())
3845            }
3846            AlterSchemaOperation::DropReplica { replica } => write!(f, "DROP REPLICA {replica}"),
3847            AlterSchemaOperation::SetOptionsParens { options } => {
3848                write!(f, "SET OPTIONS ({})", display_comma_separated(options))
3849            }
3850            AlterSchemaOperation::Rename { name } => write!(f, "RENAME TO {name}"),
3851            AlterSchemaOperation::OwnerTo { owner } => write!(f, "OWNER TO {owner}"),
3852        }
3853    }
3854}
3855/// `RenameTableNameKind` is the kind used in an `ALTER TABLE _ RENAME` statement.
3856///
3857/// Note: [MySQL] is the only database that supports the AS keyword for this operation.
3858///
3859/// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/alter-table.html
3860#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3861#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3862#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3863pub enum RenameTableNameKind {
3864    /// `AS new_table_name`
3865    As(ObjectName),
3866    /// `TO new_table_name`
3867    To(ObjectName),
3868}
3869
3870impl fmt::Display for RenameTableNameKind {
3871    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3872        match self {
3873            RenameTableNameKind::As(name) => write!(f, "AS {name}"),
3874            RenameTableNameKind::To(name) => write!(f, "TO {name}"),
3875        }
3876    }
3877}
3878
3879#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3880#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3881#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3882/// An `ALTER SCHEMA` (`Statement::AlterSchema`) statement.
3883pub struct AlterSchema {
3884    /// The schema name to alter.
3885    pub name: ObjectName,
3886    /// Whether `IF EXISTS` was specified.
3887    pub if_exists: bool,
3888    /// The list of operations to perform on the schema.
3889    pub operations: Vec<AlterSchemaOperation>,
3890}
3891
3892impl fmt::Display for AlterSchema {
3893    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3894        write!(f, "ALTER SCHEMA ")?;
3895        if self.if_exists {
3896            write!(f, "IF EXISTS ")?;
3897        }
3898        write!(f, "{}", self.name)?;
3899        for operation in &self.operations {
3900            write!(f, " {operation}")?;
3901        }
3902
3903        Ok(())
3904    }
3905}
3906
3907impl Spanned for RenameTableNameKind {
3908    fn span(&self) -> Span {
3909        match self {
3910            RenameTableNameKind::As(name) => name.span(),
3911            RenameTableNameKind::To(name) => name.span(),
3912        }
3913    }
3914}
3915
3916#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
3917#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3918#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3919/// Whether the syntax used for the trigger object (ROW or STATEMENT) is `FOR` or `FOR EACH`.
3920pub enum TriggerObjectKind {
3921    /// The `FOR` syntax is used.
3922    For(TriggerObject),
3923    /// The `FOR EACH` syntax is used.
3924    ForEach(TriggerObject),
3925}
3926
3927impl Display for TriggerObjectKind {
3928    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3929        match self {
3930            TriggerObjectKind::For(obj) => write!(f, "FOR {obj}"),
3931            TriggerObjectKind::ForEach(obj) => write!(f, "FOR EACH {obj}"),
3932        }
3933    }
3934}
3935
3936#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3937#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3938#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3939/// CREATE TRIGGER
3940///
3941/// Examples:
3942///
3943/// ```sql
3944/// CREATE TRIGGER trigger_name
3945/// BEFORE INSERT ON table_name
3946/// FOR EACH ROW
3947/// EXECUTE FUNCTION trigger_function();
3948/// ```
3949///
3950/// Postgres: <https://www.postgresql.org/docs/current/sql-createtrigger.html>
3951/// SQL Server: <https://learn.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql>
3952pub struct CreateTrigger {
3953    /// True if this is a `CREATE OR ALTER TRIGGER` statement
3954    ///
3955    /// [MsSql](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql?view=sql-server-ver16#arguments)
3956    pub or_alter: bool,
3957    /// True if this is a temporary trigger.
3958    ///
3959    /// Examples:
3960    ///
3961    /// ```sql
3962    /// CREATE TEMP TRIGGER trigger_name
3963    /// ```
3964    ///
3965    /// or
3966    ///
3967    /// ```sql
3968    /// CREATE TEMPORARY TRIGGER trigger_name;
3969    /// CREATE TEMP TRIGGER trigger_name;
3970    /// ```
3971    ///
3972    /// [SQLite](https://sqlite.org/lang_createtrigger.html#temp_triggers_on_non_temp_tables)
3973    pub temporary: bool,
3974    /// The `OR REPLACE` clause is used to re-create the trigger if it already exists.
3975    ///
3976    /// Example:
3977    /// ```sql
3978    /// CREATE OR REPLACE TRIGGER trigger_name
3979    /// AFTER INSERT ON table_name
3980    /// FOR EACH ROW
3981    /// EXECUTE FUNCTION trigger_function();
3982    /// ```
3983    pub or_replace: bool,
3984    /// The `CONSTRAINT` keyword is used to create a trigger as a constraint.
3985    pub is_constraint: bool,
3986    /// The name of the trigger to be created.
3987    pub name: ObjectName,
3988    /// Determines whether the function is called before, after, or instead of the event.
3989    ///
3990    /// Example of BEFORE:
3991    ///
3992    /// ```sql
3993    /// CREATE TRIGGER trigger_name
3994    /// BEFORE INSERT ON table_name
3995    /// FOR EACH ROW
3996    /// EXECUTE FUNCTION trigger_function();
3997    /// ```
3998    ///
3999    /// Example of AFTER:
4000    ///
4001    /// ```sql
4002    /// CREATE TRIGGER trigger_name
4003    /// AFTER INSERT ON table_name
4004    /// FOR EACH ROW
4005    /// EXECUTE FUNCTION trigger_function();
4006    /// ```
4007    ///
4008    /// Example of INSTEAD OF:
4009    ///
4010    /// ```sql
4011    /// CREATE TRIGGER trigger_name
4012    /// INSTEAD OF INSERT ON table_name
4013    /// FOR EACH ROW
4014    /// EXECUTE FUNCTION trigger_function();
4015    /// ```
4016    pub period: Option<TriggerPeriod>,
4017    /// Whether the trigger period was specified before the target table name.
4018    /// This does not refer to whether the period is BEFORE, AFTER, or INSTEAD OF,
4019    /// but rather the position of the period clause in relation to the table name.
4020    ///
4021    /// ```sql
4022    /// -- period_before_table == true: Postgres, MySQL, and standard SQL
4023    /// CREATE TRIGGER t BEFORE INSERT ON table_name ...;
4024    /// -- period_before_table == false: MSSQL
4025    /// CREATE TRIGGER t ON table_name BEFORE INSERT ...;
4026    /// ```
4027    pub period_before_table: bool,
4028    /// Multiple events can be specified using OR, such as `INSERT`, `UPDATE`, `DELETE`, or `TRUNCATE`.
4029    pub events: Vec<TriggerEvent>,
4030    /// The table on which the trigger is to be created.
4031    pub table_name: ObjectName,
4032    /// The optional referenced table name that can be referenced via
4033    /// the `FROM` keyword.
4034    pub referenced_table_name: Option<ObjectName>,
4035    /// This keyword immediately precedes the declaration of one or two relation names that provide access to the transition relations of the triggering statement.
4036    pub referencing: Vec<TriggerReferencing>,
4037    /// This specifies whether the trigger function should be fired once for
4038    /// every row affected by the trigger event, or just once per SQL statement.
4039    /// This is optional in some SQL dialects, such as SQLite, and if not specified, in
4040    /// those cases, the implied default is `FOR EACH ROW`.
4041    pub trigger_object: Option<TriggerObjectKind>,
4042    ///  Triggering conditions
4043    pub condition: Option<Expr>,
4044    /// Execute logic block
4045    pub exec_body: Option<TriggerExecBody>,
4046    /// For MSSQL and dialects where statements are preceded by `AS`
4047    pub statements_as: bool,
4048    /// For SQL dialects with statement(s) for a body
4049    pub statements: Option<ConditionalStatements>,
4050    /// The characteristic of the trigger, which include whether the trigger is `DEFERRABLE`, `INITIALLY DEFERRED`, or `INITIALLY IMMEDIATE`,
4051    pub characteristics: Option<ConstraintCharacteristics>,
4052}
4053
4054impl Display for CreateTrigger {
4055    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4056        let CreateTrigger {
4057            or_alter,
4058            temporary,
4059            or_replace,
4060            is_constraint,
4061            name,
4062            period_before_table,
4063            period,
4064            events,
4065            table_name,
4066            referenced_table_name,
4067            referencing,
4068            trigger_object,
4069            condition,
4070            exec_body,
4071            statements_as,
4072            statements,
4073            characteristics,
4074        } = self;
4075        write!(
4076            f,
4077            "CREATE {temporary}{or_alter}{or_replace}{is_constraint}TRIGGER {name} ",
4078            temporary = if *temporary { "TEMPORARY " } else { "" },
4079            or_alter = if *or_alter { "OR ALTER " } else { "" },
4080            or_replace = if *or_replace { "OR REPLACE " } else { "" },
4081            is_constraint = if *is_constraint { "CONSTRAINT " } else { "" },
4082        )?;
4083
4084        if *period_before_table {
4085            if let Some(p) = period {
4086                write!(f, "{p} ")?;
4087            }
4088            if !events.is_empty() {
4089                write!(f, "{} ", display_separated(events, " OR "))?;
4090            }
4091            write!(f, "ON {table_name}")?;
4092        } else {
4093            write!(f, "ON {table_name} ")?;
4094            if let Some(p) = period {
4095                write!(f, "{p}")?;
4096            }
4097            if !events.is_empty() {
4098                write!(f, " {}", display_separated(events, ", "))?;
4099            }
4100        }
4101
4102        if let Some(referenced_table_name) = referenced_table_name {
4103            write!(f, " FROM {referenced_table_name}")?;
4104        }
4105
4106        if let Some(characteristics) = characteristics {
4107            write!(f, " {characteristics}")?;
4108        }
4109
4110        if !referencing.is_empty() {
4111            write!(f, " REFERENCING {}", display_separated(referencing, " "))?;
4112        }
4113
4114        if let Some(trigger_object) = trigger_object {
4115            write!(f, " {trigger_object}")?;
4116        }
4117        if let Some(condition) = condition {
4118            write!(f, " WHEN {condition}")?;
4119        }
4120        if let Some(exec_body) = exec_body {
4121            write!(f, " EXECUTE {exec_body}")?;
4122        }
4123        if let Some(statements) = statements {
4124            if *statements_as {
4125                write!(f, " AS")?;
4126            }
4127            write!(f, " {statements}")?;
4128        }
4129        Ok(())
4130    }
4131}
4132
4133#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4134#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4135#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4136/// DROP TRIGGER
4137///
4138/// ```sql
4139/// DROP TRIGGER [ IF EXISTS ] name ON table_name [ CASCADE | RESTRICT ]
4140/// ```
4141///
4142pub struct DropTrigger {
4143    /// Whether to include the `IF EXISTS` clause.
4144    pub if_exists: bool,
4145    /// The name of the trigger to be dropped.
4146    pub trigger_name: ObjectName,
4147    /// The name of the table from which the trigger is to be dropped.
4148    pub table_name: Option<ObjectName>,
4149    /// `CASCADE` or `RESTRICT`
4150    pub option: Option<ReferentialAction>,
4151}
4152
4153impl fmt::Display for DropTrigger {
4154    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4155        let DropTrigger {
4156            if_exists,
4157            trigger_name,
4158            table_name,
4159            option,
4160        } = self;
4161        write!(f, "DROP TRIGGER")?;
4162        if *if_exists {
4163            write!(f, " IF EXISTS")?;
4164        }
4165        match &table_name {
4166            Some(table_name) => write!(f, " {trigger_name} ON {table_name}")?,
4167            None => write!(f, " {trigger_name}")?,
4168        };
4169        if let Some(option) = option {
4170            write!(f, " {option}")?;
4171        }
4172        Ok(())
4173    }
4174}
4175
4176/// A `TRUNCATE` statement.
4177///
4178/// ```sql
4179/// TRUNCATE TABLE [IF EXISTS] table_names [PARTITION (partitions)] [RESTART IDENTITY | CONTINUE IDENTITY] [CASCADE | RESTRICT] [ON CLUSTER cluster_name]
4180/// ```
4181#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4182#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4183#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4184pub struct Truncate {
4185    /// Table names to truncate
4186    pub table_names: Vec<super::TruncateTableTarget>,
4187    /// Optional partition specification
4188    pub partitions: Option<Vec<Expr>>,
4189    /// TABLE - optional keyword
4190    pub table: bool,
4191    /// Snowflake/Redshift-specific option: [ IF EXISTS ]
4192    pub if_exists: bool,
4193    /// Postgres-specific option: [ RESTART IDENTITY | CONTINUE IDENTITY ]
4194    pub identity: Option<super::TruncateIdentityOption>,
4195    /// Postgres-specific option: [ CASCADE | RESTRICT ]
4196    pub cascade: Option<super::CascadeOption>,
4197    /// ClickHouse-specific option: [ ON CLUSTER cluster_name ]
4198    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/truncate/)
4199    pub on_cluster: Option<Ident>,
4200}
4201
4202impl fmt::Display for Truncate {
4203    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4204        let table = if self.table { "TABLE " } else { "" };
4205        let if_exists = if self.if_exists { "IF EXISTS " } else { "" };
4206
4207        write!(
4208            f,
4209            "TRUNCATE {table}{if_exists}{table_names}",
4210            table_names = display_comma_separated(&self.table_names)
4211        )?;
4212
4213        if let Some(identity) = &self.identity {
4214            match identity {
4215                super::TruncateIdentityOption::Restart => write!(f, " RESTART IDENTITY")?,
4216                super::TruncateIdentityOption::Continue => write!(f, " CONTINUE IDENTITY")?,
4217            }
4218        }
4219        if let Some(cascade) = &self.cascade {
4220            match cascade {
4221                super::CascadeOption::Cascade => write!(f, " CASCADE")?,
4222                super::CascadeOption::Restrict => write!(f, " RESTRICT")?,
4223            }
4224        }
4225
4226        if let Some(ref parts) = &self.partitions {
4227            if !parts.is_empty() {
4228                write!(f, " PARTITION ({})", display_comma_separated(parts))?;
4229            }
4230        }
4231        if let Some(on_cluster) = &self.on_cluster {
4232            write!(f, " ON CLUSTER {on_cluster}")?;
4233        }
4234        Ok(())
4235    }
4236}
4237
4238impl Spanned for Truncate {
4239    fn span(&self) -> Span {
4240        Span::union_iter(
4241            self.table_names.iter().map(|i| i.name.span()).chain(
4242                self.partitions
4243                    .iter()
4244                    .flat_map(|i| i.iter().map(|k| k.span())),
4245            ),
4246        )
4247    }
4248}
4249
4250/// An `MSCK` statement.
4251///
4252/// ```sql
4253/// MSCK [REPAIR] TABLE table_name [ADD|DROP|SYNC PARTITIONS]
4254/// ```
4255/// MSCK (Hive) - MetaStore Check command
4256#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4257#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4258#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4259pub struct Msck {
4260    /// Table name to check
4261    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4262    pub table_name: ObjectName,
4263    /// Whether to repair the table
4264    pub repair: bool,
4265    /// Partition action (ADD, DROP, or SYNC)
4266    pub partition_action: Option<super::AddDropSync>,
4267}
4268
4269impl fmt::Display for Msck {
4270    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4271        write!(
4272            f,
4273            "MSCK {repair}TABLE {table}",
4274            repair = if self.repair { "REPAIR " } else { "" },
4275            table = self.table_name
4276        )?;
4277        if let Some(pa) = &self.partition_action {
4278            write!(f, " {pa}")?;
4279        }
4280        Ok(())
4281    }
4282}
4283
4284impl Spanned for Msck {
4285    fn span(&self) -> Span {
4286        self.table_name.span()
4287    }
4288}
4289
4290/// CREATE VIEW statement.
4291#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4292#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4293#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4294pub struct CreateView {
4295    /// True if this is a `CREATE OR ALTER VIEW` statement
4296    ///
4297    /// [MsSql](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-view-transact-sql)
4298    pub or_alter: bool,
4299    /// The `OR REPLACE` clause is used to re-create the view if it already exists.
4300    pub or_replace: bool,
4301    /// if true, has MATERIALIZED view modifier
4302    pub materialized: bool,
4303    /// Snowflake: SECURE view modifier
4304    /// <https://docs.snowflake.com/en/sql-reference/sql/create-view#syntax>
4305    pub secure: bool,
4306    /// View name
4307    pub name: ObjectName,
4308    /// If `if_not_exists` is true, this flag is set to true if the view name comes before the `IF NOT EXISTS` clause.
4309    /// Example:
4310    /// ```sql
4311    /// CREATE VIEW myview IF NOT EXISTS AS SELECT 1`
4312    ///  ```
4313    /// Otherwise, the flag is set to false if the view name comes after the clause
4314    /// Example:
4315    /// ```sql
4316    /// CREATE VIEW IF NOT EXISTS myview AS SELECT 1`
4317    ///  ```
4318    pub name_before_not_exists: bool,
4319    /// Optional column definitions
4320    pub columns: Vec<ViewColumnDef>,
4321    /// The query that defines the view.
4322    pub query: Box<Query>,
4323    /// Table options (e.g., WITH (..), OPTIONS (...))
4324    pub options: CreateTableOptions,
4325    /// BigQuery: CLUSTER BY columns
4326    pub cluster_by: Vec<Ident>,
4327    /// Snowflake: Views can have comments in Snowflake.
4328    /// <https://docs.snowflake.com/en/sql-reference/sql/create-view#syntax>
4329    pub comment: Option<String>,
4330    /// if true, has RedShift [`WITH NO SCHEMA BINDING`] clause <https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_VIEW.html>
4331    pub with_no_schema_binding: bool,
4332    /// if true, has SQLite `IF NOT EXISTS` clause <https://www.sqlite.org/lang_createview.html>
4333    pub if_not_exists: bool,
4334    /// if true, has SQLite `TEMP` or `TEMPORARY` clause <https://www.sqlite.org/lang_createview.html>
4335    pub temporary: bool,
4336    /// Snowflake: `COPY GRANTS` clause
4337    /// <https://docs.snowflake.com/en/sql-reference/sql/create-view>
4338    pub copy_grants: bool,
4339    /// if not None, has Clickhouse `TO` clause, specify the table into which to insert results
4340    /// <https://clickhouse.com/docs/en/sql-reference/statements/create/view#materialized-view>
4341    pub to: Option<ObjectName>,
4342    /// MySQL: Optional parameters for the view algorithm, definer, and security context
4343    pub params: Option<CreateViewParams>,
4344}
4345
4346impl fmt::Display for CreateView {
4347    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4348        write!(
4349            f,
4350            "CREATE {or_alter}{or_replace}",
4351            or_alter = if self.or_alter { "OR ALTER " } else { "" },
4352            or_replace = if self.or_replace { "OR REPLACE " } else { "" },
4353        )?;
4354        if let Some(ref params) = self.params {
4355            params.fmt(f)?;
4356        }
4357        write!(
4358            f,
4359            "{secure}{materialized}{temporary}VIEW {if_not_and_name}{to}",
4360            if_not_and_name = if self.if_not_exists {
4361                if self.name_before_not_exists {
4362                    format!("{} IF NOT EXISTS", self.name)
4363                } else {
4364                    format!("IF NOT EXISTS {}", self.name)
4365                }
4366            } else {
4367                format!("{}", self.name)
4368            },
4369            secure = if self.secure { "SECURE " } else { "" },
4370            materialized = if self.materialized {
4371                "MATERIALIZED "
4372            } else {
4373                ""
4374            },
4375            temporary = if self.temporary { "TEMPORARY " } else { "" },
4376            to = self
4377                .to
4378                .as_ref()
4379                .map(|to| format!(" TO {to}"))
4380                .unwrap_or_default()
4381        )?;
4382        if self.copy_grants {
4383            write!(f, " COPY GRANTS")?;
4384        }
4385        if !self.columns.is_empty() {
4386            write!(f, " ({})", display_comma_separated(&self.columns))?;
4387        }
4388        if matches!(self.options, CreateTableOptions::With(_)) {
4389            write!(f, " {}", self.options)?;
4390        }
4391        if let Some(ref comment) = self.comment {
4392            write!(f, " COMMENT = '{}'", escape_single_quote_string(comment))?;
4393        }
4394        if !self.cluster_by.is_empty() {
4395            write!(
4396                f,
4397                " CLUSTER BY ({})",
4398                display_comma_separated(&self.cluster_by)
4399            )?;
4400        }
4401        if matches!(self.options, CreateTableOptions::Options(_)) {
4402            write!(f, " {}", self.options)?;
4403        }
4404        f.write_str(" AS")?;
4405        SpaceOrNewline.fmt(f)?;
4406        self.query.fmt(f)?;
4407        if self.with_no_schema_binding {
4408            write!(f, " WITH NO SCHEMA BINDING")?;
4409        }
4410        Ok(())
4411    }
4412}
4413
4414/// CREATE EXTENSION statement
4415/// Note: this is a PostgreSQL-specific statement
4416#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4417#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4418#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4419pub struct CreateExtension {
4420    /// Extension name
4421    pub name: Ident,
4422    /// Whether `IF NOT EXISTS` was specified for the CREATE EXTENSION.
4423    pub if_not_exists: bool,
4424    /// Whether `CASCADE` was specified for the CREATE EXTENSION.
4425    pub cascade: bool,
4426    /// Optional schema name for the extension.
4427    pub schema: Option<Ident>,
4428    /// Optional version for the extension.
4429    pub version: Option<Ident>,
4430}
4431
4432impl fmt::Display for CreateExtension {
4433    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4434        write!(
4435            f,
4436            "CREATE EXTENSION {if_not_exists}{name}",
4437            if_not_exists = if self.if_not_exists {
4438                "IF NOT EXISTS "
4439            } else {
4440                ""
4441            },
4442            name = self.name
4443        )?;
4444        if self.cascade || self.schema.is_some() || self.version.is_some() {
4445            write!(f, " WITH")?;
4446
4447            if let Some(name) = &self.schema {
4448                write!(f, " SCHEMA {name}")?;
4449            }
4450            if let Some(version) = &self.version {
4451                write!(f, " VERSION {version}")?;
4452            }
4453            if self.cascade {
4454                write!(f, " CASCADE")?;
4455            }
4456        }
4457
4458        Ok(())
4459    }
4460}
4461
4462impl Spanned for CreateExtension {
4463    fn span(&self) -> Span {
4464        Span::empty()
4465    }
4466}
4467
4468/// DROP EXTENSION statement
4469/// Note: this is a PostgreSQL-specific statement
4470///
4471/// # References
4472///
4473/// PostgreSQL Documentation:
4474/// <https://www.postgresql.org/docs/current/sql-dropextension.html>
4475#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4476#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4477#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4478pub struct DropExtension {
4479    /// One or more extension names to drop
4480    pub names: Vec<Ident>,
4481    /// Whether `IF EXISTS` was specified for the DROP EXTENSION.
4482    pub if_exists: bool,
4483    /// `CASCADE` or `RESTRICT` behaviour for the drop.
4484    pub cascade_or_restrict: Option<ReferentialAction>,
4485}
4486
4487impl fmt::Display for DropExtension {
4488    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4489        write!(f, "DROP EXTENSION")?;
4490        if self.if_exists {
4491            write!(f, " IF EXISTS")?;
4492        }
4493        write!(f, " {}", display_comma_separated(&self.names))?;
4494        if let Some(cascade_or_restrict) = &self.cascade_or_restrict {
4495            write!(f, " {cascade_or_restrict}")?;
4496        }
4497        Ok(())
4498    }
4499}
4500
4501impl Spanned for DropExtension {
4502    fn span(&self) -> Span {
4503        Span::empty()
4504    }
4505}
4506
4507/// CREATE COLLATION statement.
4508/// Note: this is a PostgreSQL-specific statement.
4509#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4510#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4511#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4512pub struct CreateCollation {
4513    /// Whether `IF NOT EXISTS` was specified.
4514    pub if_not_exists: bool,
4515    /// Name of the collation being created.
4516    pub name: ObjectName,
4517    /// Source definition for the collation.
4518    pub definition: CreateCollationDefinition,
4519}
4520
4521/// Definition forms supported by `CREATE COLLATION`.
4522#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4523#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4524#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4525pub enum CreateCollationDefinition {
4526    /// Create from an existing collation.
4527    ///
4528    /// ```sql
4529    /// CREATE COLLATION name FROM existing_collation
4530    /// ```
4531    From(ObjectName),
4532    /// Create with an option list.
4533    ///
4534    /// ```sql
4535    /// CREATE COLLATION name (key = value, ...)
4536    /// ```
4537    Options(Vec<SqlOption>),
4538}
4539
4540impl fmt::Display for CreateCollation {
4541    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4542        write!(
4543            f,
4544            "CREATE COLLATION {if_not_exists}{name}",
4545            if_not_exists = if self.if_not_exists {
4546                "IF NOT EXISTS "
4547            } else {
4548                ""
4549            },
4550            name = self.name
4551        )?;
4552        match &self.definition {
4553            CreateCollationDefinition::From(existing_collation) => {
4554                write!(f, " FROM {existing_collation}")
4555            }
4556            CreateCollationDefinition::Options(options) => {
4557                write!(f, " ({})", display_comma_separated(options))
4558            }
4559        }
4560    }
4561}
4562
4563impl Spanned for CreateCollation {
4564    fn span(&self) -> Span {
4565        Span::empty()
4566    }
4567}
4568
4569/// ALTER COLLATION statement.
4570/// Note: this is a PostgreSQL-specific statement.
4571#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4572#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4573#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4574pub struct AlterCollation {
4575    /// Name of the collation being altered.
4576    pub name: ObjectName,
4577    /// The operation to perform on the collation.
4578    pub operation: AlterCollationOperation,
4579}
4580
4581/// Operations supported by `ALTER COLLATION`.
4582#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4583#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4584#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4585pub enum AlterCollationOperation {
4586    /// Rename the collation.
4587    ///
4588    /// ```sql
4589    /// ALTER COLLATION name RENAME TO new_name
4590    /// ```
4591    RenameTo {
4592        /// New collation name.
4593        new_name: Ident,
4594    },
4595    /// Change the collation owner.
4596    ///
4597    /// ```sql
4598    /// ALTER COLLATION name OWNER TO role_name
4599    /// ```
4600    OwnerTo(Owner),
4601    /// Move the collation to another schema.
4602    ///
4603    /// ```sql
4604    /// ALTER COLLATION name SET SCHEMA new_schema
4605    /// ```
4606    SetSchema {
4607        /// Target schema name.
4608        schema_name: ObjectName,
4609    },
4610    /// Refresh collation version metadata.
4611    ///
4612    /// ```sql
4613    /// ALTER COLLATION name REFRESH VERSION
4614    /// ```
4615    RefreshVersion,
4616}
4617
4618impl fmt::Display for AlterCollationOperation {
4619    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4620        match self {
4621            AlterCollationOperation::RenameTo { new_name } => write!(f, "RENAME TO {new_name}"),
4622            AlterCollationOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
4623            AlterCollationOperation::SetSchema { schema_name } => {
4624                write!(f, "SET SCHEMA {schema_name}")
4625            }
4626            AlterCollationOperation::RefreshVersion => write!(f, "REFRESH VERSION"),
4627        }
4628    }
4629}
4630
4631impl fmt::Display for AlterCollation {
4632    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4633        write!(f, "ALTER COLLATION {} {}", self.name, self.operation)
4634    }
4635}
4636
4637impl Spanned for AlterCollation {
4638    fn span(&self) -> Span {
4639        Span::empty()
4640    }
4641}
4642
4643/// Table type for ALTER TABLE statements.
4644/// Used to distinguish between regular tables, Iceberg tables, and Dynamic tables.
4645#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4646#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4647#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4648pub enum AlterTableType {
4649    /// Iceberg table type
4650    /// <https://docs.snowflake.com/en/sql-reference/sql/alter-iceberg-table>
4651    Iceberg,
4652    /// Dynamic table type
4653    /// <https://docs.snowflake.com/en/sql-reference/sql/alter-dynamic-table>
4654    Dynamic,
4655    /// External table type
4656    /// <https://docs.snowflake.com/en/sql-reference/sql/alter-external-table>
4657    External,
4658}
4659
4660/// ALTER TABLE statement
4661#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4662#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4663#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4664pub struct AlterTable {
4665    /// Table name
4666    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4667    pub name: ObjectName,
4668    /// Whether `IF EXISTS` was specified for the `ALTER TABLE`.
4669    pub if_exists: bool,
4670    /// Whether the `ONLY` keyword was used (restrict scope to the named table).
4671    pub only: bool,
4672    /// List of `ALTER TABLE` operations to apply.
4673    pub operations: Vec<AlterTableOperation>,
4674    /// Optional Hive `SET LOCATION` clause for the alter operation.
4675    pub location: Option<HiveSetLocation>,
4676    /// ClickHouse dialect supports `ON CLUSTER` clause for ALTER TABLE
4677    /// For example: `ALTER TABLE table_name ON CLUSTER cluster_name ADD COLUMN c UInt32`
4678    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/update)
4679    pub on_cluster: Option<Ident>,
4680    /// Table type: None for regular tables, Some(AlterTableType) for Iceberg or Dynamic tables
4681    pub table_type: Option<AlterTableType>,
4682    /// Token that represents the end of the statement (semicolon or EOF)
4683    pub end_token: AttachedToken,
4684}
4685
4686impl fmt::Display for AlterTable {
4687    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4688        match &self.table_type {
4689            Some(AlterTableType::Iceberg) => write!(f, "ALTER ICEBERG TABLE ")?,
4690            Some(AlterTableType::Dynamic) => write!(f, "ALTER DYNAMIC TABLE ")?,
4691            Some(AlterTableType::External) => write!(f, "ALTER EXTERNAL TABLE ")?,
4692            None => write!(f, "ALTER TABLE ")?,
4693        }
4694
4695        if self.if_exists {
4696            write!(f, "IF EXISTS ")?;
4697        }
4698        if self.only {
4699            write!(f, "ONLY ")?;
4700        }
4701        write!(f, "{} ", &self.name)?;
4702        if let Some(cluster) = &self.on_cluster {
4703            write!(f, "ON CLUSTER {cluster} ")?;
4704        }
4705        write!(f, "{}", display_comma_separated(&self.operations))?;
4706        if let Some(loc) = &self.location {
4707            write!(f, " {loc}")?
4708        }
4709        Ok(())
4710    }
4711}
4712
4713/// DROP FUNCTION statement
4714#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4715#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4716#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4717pub struct DropFunction {
4718    /// Whether to include the `IF EXISTS` clause.
4719    pub if_exists: bool,
4720    /// One or more functions to drop
4721    pub func_desc: Vec<FunctionDesc>,
4722    /// `CASCADE` or `RESTRICT`
4723    pub drop_behavior: Option<DropBehavior>,
4724}
4725
4726impl fmt::Display for DropFunction {
4727    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4728        write!(
4729            f,
4730            "DROP FUNCTION{} {}",
4731            if self.if_exists { " IF EXISTS" } else { "" },
4732            display_comma_separated(&self.func_desc),
4733        )?;
4734        if let Some(op) = &self.drop_behavior {
4735            write!(f, " {op}")?;
4736        }
4737        Ok(())
4738    }
4739}
4740
4741impl Spanned for DropFunction {
4742    fn span(&self) -> Span {
4743        Span::empty()
4744    }
4745}
4746
4747/// CREATE OPERATOR statement
4748/// See <https://www.postgresql.org/docs/current/sql-createoperator.html>
4749#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4750#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4751#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4752pub struct CreateOperator {
4753    /// Operator name (can be schema-qualified)
4754    pub name: ObjectName,
4755    /// FUNCTION or PROCEDURE parameter (function name)
4756    pub function: ObjectName,
4757    /// Whether PROCEDURE keyword was used (vs FUNCTION)
4758    pub is_procedure: bool,
4759    /// LEFTARG parameter (left operand type)
4760    pub left_arg: Option<DataType>,
4761    /// RIGHTARG parameter (right operand type)
4762    pub right_arg: Option<DataType>,
4763    /// Operator options (COMMUTATOR, NEGATOR, RESTRICT, JOIN, HASHES, MERGES)
4764    pub options: Vec<OperatorOption>,
4765}
4766
4767/// CREATE OPERATOR FAMILY statement
4768/// See <https://www.postgresql.org/docs/current/sql-createopfamily.html>
4769#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4770#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4771#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4772pub struct CreateOperatorFamily {
4773    /// Operator family name (can be schema-qualified)
4774    pub name: ObjectName,
4775    /// Index method (btree, hash, gist, gin, etc.)
4776    pub using: Ident,
4777}
4778
4779/// CREATE OPERATOR CLASS statement
4780/// See <https://www.postgresql.org/docs/current/sql-createopclass.html>
4781#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4782#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4783#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4784pub struct CreateOperatorClass {
4785    /// Operator class name (can be schema-qualified)
4786    pub name: ObjectName,
4787    /// Whether this is the default operator class for the type
4788    pub default: bool,
4789    /// The data type
4790    pub for_type: DataType,
4791    /// Index method (btree, hash, gist, gin, etc.)
4792    pub using: Ident,
4793    /// Optional operator family name
4794    pub family: Option<ObjectName>,
4795    /// List of operator class items (operators, functions, storage)
4796    pub items: Vec<OperatorClassItem>,
4797}
4798
4799impl fmt::Display for CreateOperator {
4800    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4801        write!(f, "CREATE OPERATOR {} (", self.name)?;
4802
4803        let function_keyword = if self.is_procedure {
4804            "PROCEDURE"
4805        } else {
4806            "FUNCTION"
4807        };
4808        let mut params = vec![format!("{} = {}", function_keyword, self.function)];
4809
4810        if let Some(left_arg) = &self.left_arg {
4811            params.push(format!("LEFTARG = {}", left_arg));
4812        }
4813        if let Some(right_arg) = &self.right_arg {
4814            params.push(format!("RIGHTARG = {}", right_arg));
4815        }
4816
4817        for option in &self.options {
4818            params.push(option.to_string());
4819        }
4820
4821        write!(f, "{}", params.join(", "))?;
4822        write!(f, ")")
4823    }
4824}
4825
4826impl fmt::Display for CreateOperatorFamily {
4827    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4828        write!(
4829            f,
4830            "CREATE OPERATOR FAMILY {} USING {}",
4831            self.name, self.using
4832        )
4833    }
4834}
4835
4836impl fmt::Display for CreateOperatorClass {
4837    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4838        write!(f, "CREATE OPERATOR CLASS {}", self.name)?;
4839        if self.default {
4840            write!(f, " DEFAULT")?;
4841        }
4842        write!(f, " FOR TYPE {} USING {}", self.for_type, self.using)?;
4843        if let Some(family) = &self.family {
4844            write!(f, " FAMILY {}", family)?;
4845        }
4846        write!(f, " AS {}", display_comma_separated(&self.items))
4847    }
4848}
4849
4850/// Operator argument types for CREATE OPERATOR CLASS
4851#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4852#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4853#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4854pub struct OperatorArgTypes {
4855    /// Left-hand operand data type for the operator.
4856    pub left: DataType,
4857    /// Right-hand operand data type for the operator.
4858    pub right: DataType,
4859}
4860
4861impl fmt::Display for OperatorArgTypes {
4862    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4863        write!(f, "{}, {}", self.left, self.right)
4864    }
4865}
4866
4867/// An item in a CREATE OPERATOR CLASS statement
4868#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4869#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4870#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4871pub enum OperatorClassItem {
4872    /// `OPERATOR` clause describing a specific operator implementation.
4873    Operator {
4874        /// Strategy number identifying the operator position in the opclass.
4875        strategy_number: u64,
4876        /// The operator name referenced by this clause.
4877        operator_name: ObjectName,
4878        /// Optional operator argument types.
4879        op_types: Option<OperatorArgTypes>,
4880        /// Optional purpose such as `FOR SEARCH` or `FOR ORDER BY`.
4881        purpose: Option<OperatorPurpose>,
4882    },
4883    /// `FUNCTION` clause describing a support function for the operator class.
4884    Function {
4885        /// Support function number for this entry.
4886        support_number: u64,
4887        /// Optional function argument types for the operator class.
4888        op_types: Option<Vec<DataType>>,
4889        /// The function name implementing the support function.
4890        function_name: ObjectName,
4891        /// Function argument types for the support function.
4892        argument_types: Vec<DataType>,
4893    },
4894    /// `STORAGE` clause specifying the storage type.
4895    Storage {
4896        /// The storage data type.
4897        storage_type: DataType,
4898    },
4899}
4900
4901/// Purpose of an operator in an operator class
4902#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4903#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4904#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4905pub enum OperatorPurpose {
4906    /// Purpose: used for index/search operations.
4907    ForSearch,
4908    /// Purpose: used for ORDER BY; optionally includes a sort family name.
4909    ForOrderBy {
4910        /// Optional sort family object name.
4911        sort_family: ObjectName,
4912    },
4913}
4914
4915impl fmt::Display for OperatorClassItem {
4916    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4917        match self {
4918            OperatorClassItem::Operator {
4919                strategy_number,
4920                operator_name,
4921                op_types,
4922                purpose,
4923            } => {
4924                write!(f, "OPERATOR {strategy_number} {operator_name}")?;
4925                if let Some(types) = op_types {
4926                    write!(f, " ({types})")?;
4927                }
4928                if let Some(purpose) = purpose {
4929                    write!(f, " {purpose}")?;
4930                }
4931                Ok(())
4932            }
4933            OperatorClassItem::Function {
4934                support_number,
4935                op_types,
4936                function_name,
4937                argument_types,
4938            } => {
4939                write!(f, "FUNCTION {support_number}")?;
4940                if let Some(types) = op_types {
4941                    write!(f, " ({})", display_comma_separated(types))?;
4942                }
4943                write!(f, " {function_name}")?;
4944                if !argument_types.is_empty() {
4945                    write!(f, "({})", display_comma_separated(argument_types))?;
4946                }
4947                Ok(())
4948            }
4949            OperatorClassItem::Storage { storage_type } => {
4950                write!(f, "STORAGE {storage_type}")
4951            }
4952        }
4953    }
4954}
4955
4956impl fmt::Display for OperatorPurpose {
4957    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4958        match self {
4959            OperatorPurpose::ForSearch => write!(f, "FOR SEARCH"),
4960            OperatorPurpose::ForOrderBy { sort_family } => {
4961                write!(f, "FOR ORDER BY {sort_family}")
4962            }
4963        }
4964    }
4965}
4966
4967/// `DROP OPERATOR` statement
4968/// See <https://www.postgresql.org/docs/current/sql-dropoperator.html>
4969#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4970#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4971#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4972pub struct DropOperator {
4973    /// `IF EXISTS` clause
4974    pub if_exists: bool,
4975    /// One or more operators to drop with their signatures
4976    pub operators: Vec<DropOperatorSignature>,
4977    /// `CASCADE or RESTRICT`
4978    pub drop_behavior: Option<DropBehavior>,
4979}
4980
4981/// Operator signature for a `DROP OPERATOR` statement
4982#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4983#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4984#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4985pub struct DropOperatorSignature {
4986    /// Operator name
4987    pub name: ObjectName,
4988    /// Left operand type
4989    pub left_type: Option<DataType>,
4990    /// Right operand type
4991    pub right_type: DataType,
4992}
4993
4994impl fmt::Display for DropOperatorSignature {
4995    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4996        write!(f, "{} (", self.name)?;
4997        if let Some(left_type) = &self.left_type {
4998            write!(f, "{}", left_type)?;
4999        } else {
5000            write!(f, "NONE")?;
5001        }
5002        write!(f, ", {})", self.right_type)
5003    }
5004}
5005
5006impl fmt::Display for DropOperator {
5007    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5008        write!(f, "DROP OPERATOR")?;
5009        if self.if_exists {
5010            write!(f, " IF EXISTS")?;
5011        }
5012        write!(f, " {}", display_comma_separated(&self.operators))?;
5013        if let Some(drop_behavior) = &self.drop_behavior {
5014            write!(f, " {}", drop_behavior)?;
5015        }
5016        Ok(())
5017    }
5018}
5019
5020impl Spanned for DropOperator {
5021    fn span(&self) -> Span {
5022        Span::empty()
5023    }
5024}
5025
5026/// `DROP OPERATOR FAMILY` statement
5027/// See <https://www.postgresql.org/docs/current/sql-dropopfamily.html>
5028#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5029#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5030#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5031pub struct DropOperatorFamily {
5032    /// `IF EXISTS` clause
5033    pub if_exists: bool,
5034    /// One or more operator families to drop
5035    pub names: Vec<ObjectName>,
5036    /// Index method (btree, hash, gist, gin, etc.)
5037    pub using: Ident,
5038    /// `CASCADE or RESTRICT`
5039    pub drop_behavior: Option<DropBehavior>,
5040}
5041
5042impl fmt::Display for DropOperatorFamily {
5043    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5044        write!(f, "DROP OPERATOR FAMILY")?;
5045        if self.if_exists {
5046            write!(f, " IF EXISTS")?;
5047        }
5048        write!(f, " {}", display_comma_separated(&self.names))?;
5049        write!(f, " USING {}", self.using)?;
5050        if let Some(drop_behavior) = &self.drop_behavior {
5051            write!(f, " {}", drop_behavior)?;
5052        }
5053        Ok(())
5054    }
5055}
5056
5057impl Spanned for DropOperatorFamily {
5058    fn span(&self) -> Span {
5059        Span::empty()
5060    }
5061}
5062
5063/// `DROP OPERATOR CLASS` statement
5064/// See <https://www.postgresql.org/docs/current/sql-dropopclass.html>
5065#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5066#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5067#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5068pub struct DropOperatorClass {
5069    /// `IF EXISTS` clause
5070    pub if_exists: bool,
5071    /// One or more operator classes to drop
5072    pub names: Vec<ObjectName>,
5073    /// Index method (btree, hash, gist, gin, etc.)
5074    pub using: Ident,
5075    /// `CASCADE or RESTRICT`
5076    pub drop_behavior: Option<DropBehavior>,
5077}
5078
5079impl fmt::Display for DropOperatorClass {
5080    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5081        write!(f, "DROP OPERATOR CLASS")?;
5082        if self.if_exists {
5083            write!(f, " IF EXISTS")?;
5084        }
5085        write!(f, " {}", display_comma_separated(&self.names))?;
5086        write!(f, " USING {}", self.using)?;
5087        if let Some(drop_behavior) = &self.drop_behavior {
5088            write!(f, " {}", drop_behavior)?;
5089        }
5090        Ok(())
5091    }
5092}
5093
5094impl Spanned for DropOperatorClass {
5095    fn span(&self) -> Span {
5096        Span::empty()
5097    }
5098}
5099
5100/// An item in an ALTER OPERATOR FAMILY ADD statement
5101#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5102#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5103#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5104pub enum OperatorFamilyItem {
5105    /// `OPERATOR` clause in an operator family modification.
5106    Operator {
5107        /// Strategy number for the operator.
5108        strategy_number: u64,
5109        /// Operator name referenced by this entry.
5110        operator_name: ObjectName,
5111        /// Operator argument types.
5112        op_types: Vec<DataType>,
5113        /// Optional purpose such as `FOR SEARCH` or `FOR ORDER BY`.
5114        purpose: Option<OperatorPurpose>,
5115    },
5116    /// `FUNCTION` clause in an operator family modification.
5117    Function {
5118        /// Support function number.
5119        support_number: u64,
5120        /// Optional operator argument types for the function.
5121        op_types: Option<Vec<DataType>>,
5122        /// Function name for the support function.
5123        function_name: ObjectName,
5124        /// Function argument types.
5125        argument_types: Vec<DataType>,
5126    },
5127}
5128
5129/// An item in an ALTER OPERATOR FAMILY DROP statement
5130#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5131#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5132#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5133pub enum OperatorFamilyDropItem {
5134    /// `OPERATOR` clause for DROP within an operator family.
5135    Operator {
5136        /// Strategy number for the operator.
5137        strategy_number: u64,
5138        /// Operator argument types.
5139        op_types: Vec<DataType>,
5140    },
5141    /// `FUNCTION` clause for DROP within an operator family.
5142    Function {
5143        /// Support function number.
5144        support_number: u64,
5145        /// Operator argument types for the function.
5146        op_types: Vec<DataType>,
5147    },
5148}
5149
5150impl fmt::Display for OperatorFamilyItem {
5151    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5152        match self {
5153            OperatorFamilyItem::Operator {
5154                strategy_number,
5155                operator_name,
5156                op_types,
5157                purpose,
5158            } => {
5159                write!(
5160                    f,
5161                    "OPERATOR {strategy_number} {operator_name} ({})",
5162                    display_comma_separated(op_types)
5163                )?;
5164                if let Some(purpose) = purpose {
5165                    write!(f, " {purpose}")?;
5166                }
5167                Ok(())
5168            }
5169            OperatorFamilyItem::Function {
5170                support_number,
5171                op_types,
5172                function_name,
5173                argument_types,
5174            } => {
5175                write!(f, "FUNCTION {support_number}")?;
5176                if let Some(types) = op_types {
5177                    write!(f, " ({})", display_comma_separated(types))?;
5178                }
5179                write!(f, " {function_name}")?;
5180                if !argument_types.is_empty() {
5181                    write!(f, "({})", display_comma_separated(argument_types))?;
5182                }
5183                Ok(())
5184            }
5185        }
5186    }
5187}
5188
5189impl fmt::Display for OperatorFamilyDropItem {
5190    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5191        match self {
5192            OperatorFamilyDropItem::Operator {
5193                strategy_number,
5194                op_types,
5195            } => {
5196                write!(
5197                    f,
5198                    "OPERATOR {strategy_number} ({})",
5199                    display_comma_separated(op_types)
5200                )
5201            }
5202            OperatorFamilyDropItem::Function {
5203                support_number,
5204                op_types,
5205            } => {
5206                write!(
5207                    f,
5208                    "FUNCTION {support_number} ({})",
5209                    display_comma_separated(op_types)
5210                )
5211            }
5212        }
5213    }
5214}
5215
5216/// `ALTER OPERATOR FAMILY` statement
5217/// See <https://www.postgresql.org/docs/current/sql-alteropfamily.html>
5218#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5219#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5220#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5221pub struct AlterOperatorFamily {
5222    /// Operator family name (can be schema-qualified)
5223    pub name: ObjectName,
5224    /// Index method (btree, hash, gist, gin, etc.)
5225    pub using: Ident,
5226    /// The operation to perform
5227    pub operation: AlterOperatorFamilyOperation,
5228}
5229
5230/// An [AlterOperatorFamily] operation
5231#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5232#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5233#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5234pub enum AlterOperatorFamilyOperation {
5235    /// `ADD { OPERATOR ... | FUNCTION ... } [, ...]`
5236    Add {
5237        /// List of operator family items to add
5238        items: Vec<OperatorFamilyItem>,
5239    },
5240    /// `DROP { OPERATOR ... | FUNCTION ... } [, ...]`
5241    Drop {
5242        /// List of operator family items to drop
5243        items: Vec<OperatorFamilyDropItem>,
5244    },
5245    /// `RENAME TO new_name`
5246    RenameTo {
5247        /// The new name for the operator family.
5248        new_name: ObjectName,
5249    },
5250    /// `OWNER TO { new_owner | CURRENT_ROLE | CURRENT_USER | SESSION_USER }`
5251    OwnerTo(Owner),
5252    /// `SET SCHEMA new_schema`
5253    SetSchema {
5254        /// The target schema name.
5255        schema_name: ObjectName,
5256    },
5257}
5258
5259impl fmt::Display for AlterOperatorFamily {
5260    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5261        write!(
5262            f,
5263            "ALTER OPERATOR FAMILY {} USING {}",
5264            self.name, self.using
5265        )?;
5266        write!(f, " {}", self.operation)
5267    }
5268}
5269
5270impl fmt::Display for AlterOperatorFamilyOperation {
5271    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5272        match self {
5273            AlterOperatorFamilyOperation::Add { items } => {
5274                write!(f, "ADD {}", display_comma_separated(items))
5275            }
5276            AlterOperatorFamilyOperation::Drop { items } => {
5277                write!(f, "DROP {}", display_comma_separated(items))
5278            }
5279            AlterOperatorFamilyOperation::RenameTo { new_name } => {
5280                write!(f, "RENAME TO {new_name}")
5281            }
5282            AlterOperatorFamilyOperation::OwnerTo(owner) => {
5283                write!(f, "OWNER TO {owner}")
5284            }
5285            AlterOperatorFamilyOperation::SetSchema { schema_name } => {
5286                write!(f, "SET SCHEMA {schema_name}")
5287            }
5288        }
5289    }
5290}
5291
5292impl Spanned for AlterOperatorFamily {
5293    fn span(&self) -> Span {
5294        Span::empty()
5295    }
5296}
5297
5298/// `ALTER OPERATOR CLASS` statement
5299/// See <https://www.postgresql.org/docs/current/sql-alteropclass.html>
5300#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5301#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5302#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5303pub struct AlterOperatorClass {
5304    /// Operator class name (can be schema-qualified)
5305    pub name: ObjectName,
5306    /// Index method (btree, hash, gist, gin, etc.)
5307    pub using: Ident,
5308    /// The operation to perform
5309    pub operation: AlterOperatorClassOperation,
5310}
5311
5312/// An [AlterOperatorClass] operation
5313#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5314#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5315#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5316pub enum AlterOperatorClassOperation {
5317    /// `RENAME TO new_name`
5318    /// Rename the operator class to a new name.
5319    RenameTo {
5320        /// The new name for the operator class.
5321        new_name: ObjectName,
5322    },
5323    /// `OWNER TO { new_owner | CURRENT_ROLE | CURRENT_USER | SESSION_USER }`
5324    OwnerTo(Owner),
5325    /// `SET SCHEMA new_schema`
5326    /// Set the schema for the operator class.
5327    SetSchema {
5328        /// The target schema name.
5329        schema_name: ObjectName,
5330    },
5331}
5332
5333impl fmt::Display for AlterOperatorClass {
5334    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5335        write!(f, "ALTER OPERATOR CLASS {} USING {}", self.name, self.using)?;
5336        write!(f, " {}", self.operation)
5337    }
5338}
5339
5340impl fmt::Display for AlterOperatorClassOperation {
5341    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5342        match self {
5343            AlterOperatorClassOperation::RenameTo { new_name } => {
5344                write!(f, "RENAME TO {new_name}")
5345            }
5346            AlterOperatorClassOperation::OwnerTo(owner) => {
5347                write!(f, "OWNER TO {owner}")
5348            }
5349            AlterOperatorClassOperation::SetSchema { schema_name } => {
5350                write!(f, "SET SCHEMA {schema_name}")
5351            }
5352        }
5353    }
5354}
5355
5356impl Spanned for AlterOperatorClass {
5357    fn span(&self) -> Span {
5358        Span::empty()
5359    }
5360}
5361
5362/// `ALTER FUNCTION` / `ALTER AGGREGATE` statement.
5363#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5364#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5365#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5366pub struct AlterFunction {
5367    /// Object type being altered.
5368    pub kind: AlterFunctionKind,
5369    /// Function or aggregate signature.
5370    pub function: FunctionDesc,
5371    /// `ORDER BY` argument list for aggregate signatures.
5372    ///
5373    /// This is only used for `ALTER AGGREGATE`.
5374    pub aggregate_order_by: Option<Vec<OperateFunctionArg>>,
5375    /// Whether the aggregate signature uses `*`.
5376    ///
5377    /// This is only used for `ALTER AGGREGATE`.
5378    pub aggregate_star: bool,
5379    /// Operation applied to the object.
5380    pub operation: AlterFunctionOperation,
5381}
5382
5383/// Function-like object type used by [`AlterFunction`].
5384#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5385#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5386#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5387pub enum AlterFunctionKind {
5388    /// `FUNCTION`
5389    Function,
5390    /// `AGGREGATE`
5391    Aggregate,
5392}
5393
5394impl fmt::Display for AlterFunctionKind {
5395    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5396        match self {
5397            Self::Function => write!(f, "FUNCTION"),
5398            Self::Aggregate => write!(f, "AGGREGATE"),
5399        }
5400    }
5401}
5402
5403/// Operation for `ALTER FUNCTION` / `ALTER AGGREGATE`.
5404#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5405#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5406#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5407pub enum AlterFunctionOperation {
5408    /// `RENAME TO new_name`
5409    RenameTo {
5410        /// New unqualified function or aggregate name.
5411        new_name: Ident,
5412    },
5413    /// `OWNER TO { new_owner | CURRENT_ROLE | CURRENT_USER | SESSION_USER }`
5414    OwnerTo(Owner),
5415    /// `SET SCHEMA schema_name`
5416    SetSchema {
5417        /// The target schema name.
5418        schema_name: ObjectName,
5419    },
5420    /// `[ NO ] DEPENDS ON EXTENSION extension_name`
5421    DependsOnExtension {
5422        /// `true` when `NO DEPENDS ON EXTENSION`.
5423        no: bool,
5424        /// Extension name.
5425        extension_name: ObjectName,
5426    },
5427    /// `action [ ... ] [ RESTRICT ]` (function only).
5428    Actions {
5429        /// One or more function actions.
5430        actions: Vec<AlterFunctionAction>,
5431        /// Whether `RESTRICT` is present.
5432        restrict: bool,
5433    },
5434}
5435
5436/// Function action in `ALTER FUNCTION ... action [ ... ] [ RESTRICT ]`.
5437#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5438#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5439#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5440pub enum AlterFunctionAction {
5441    /// `CALLED ON NULL INPUT` / `RETURNS NULL ON NULL INPUT` / `STRICT`
5442    CalledOnNull(FunctionCalledOnNull),
5443    /// `IMMUTABLE` / `STABLE` / `VOLATILE`
5444    Behavior(FunctionBehavior),
5445    /// `[ NOT ] LEAKPROOF`
5446    Leakproof(bool),
5447    /// `[ EXTERNAL ] SECURITY { DEFINER | INVOKER }`
5448    Security {
5449        /// Whether the optional `EXTERNAL` keyword was present.
5450        external: bool,
5451        /// Security mode.
5452        security: FunctionSecurity,
5453    },
5454    /// `PARALLEL { UNSAFE | RESTRICTED | SAFE }`
5455    Parallel(FunctionParallel),
5456    /// `COST execution_cost`
5457    Cost(Expr),
5458    /// `ROWS result_rows`
5459    Rows(Expr),
5460    /// `SUPPORT support_function`
5461    Support(ObjectName),
5462    /// `SET configuration_parameter { TO | = } { value | DEFAULT }`
5463    /// or `SET configuration_parameter FROM CURRENT`
5464    Set(FunctionDefinitionSetParam),
5465    /// `RESET configuration_parameter` or `RESET ALL`
5466    Reset(ResetConfig),
5467}
5468
5469impl fmt::Display for AlterFunction {
5470    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5471        write!(f, "ALTER {} ", self.kind)?;
5472        match self.kind {
5473            AlterFunctionKind::Function => {
5474                write!(f, "{} ", self.function)?;
5475            }
5476            AlterFunctionKind::Aggregate => {
5477                write!(f, "{}(", self.function.name)?;
5478                if self.aggregate_star {
5479                    write!(f, "*")?;
5480                } else {
5481                    if let Some(args) = &self.function.args {
5482                        write!(f, "{}", display_comma_separated(args))?;
5483                    }
5484                    if let Some(order_by_args) = &self.aggregate_order_by {
5485                        if self
5486                            .function
5487                            .args
5488                            .as_ref()
5489                            .is_some_and(|args| !args.is_empty())
5490                        {
5491                            write!(f, " ")?;
5492                        }
5493                        write!(f, "ORDER BY {}", display_comma_separated(order_by_args))?;
5494                    }
5495                }
5496                write!(f, ") ")?;
5497            }
5498        }
5499        write!(f, "{}", self.operation)
5500    }
5501}
5502
5503impl fmt::Display for AlterFunctionOperation {
5504    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5505        match self {
5506            AlterFunctionOperation::RenameTo { new_name } => {
5507                write!(f, "RENAME TO {new_name}")
5508            }
5509            AlterFunctionOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
5510            AlterFunctionOperation::SetSchema { schema_name } => {
5511                write!(f, "SET SCHEMA {schema_name}")
5512            }
5513            AlterFunctionOperation::DependsOnExtension { no, extension_name } => {
5514                if *no {
5515                    write!(f, "NO DEPENDS ON EXTENSION {extension_name}")
5516                } else {
5517                    write!(f, "DEPENDS ON EXTENSION {extension_name}")
5518                }
5519            }
5520            AlterFunctionOperation::Actions { actions, restrict } => {
5521                write!(f, "{}", display_separated(actions, " "))?;
5522                if *restrict {
5523                    write!(f, " RESTRICT")?;
5524                }
5525                Ok(())
5526            }
5527        }
5528    }
5529}
5530
5531impl fmt::Display for AlterFunctionAction {
5532    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5533        match self {
5534            AlterFunctionAction::CalledOnNull(called_on_null) => write!(f, "{called_on_null}"),
5535            AlterFunctionAction::Behavior(behavior) => write!(f, "{behavior}"),
5536            AlterFunctionAction::Leakproof(leakproof) => {
5537                if *leakproof {
5538                    write!(f, "LEAKPROOF")
5539                } else {
5540                    write!(f, "NOT LEAKPROOF")
5541                }
5542            }
5543            AlterFunctionAction::Security { external, security } => {
5544                if *external {
5545                    write!(f, "EXTERNAL ")?;
5546                }
5547                write!(f, "{security}")
5548            }
5549            AlterFunctionAction::Parallel(parallel) => write!(f, "{parallel}"),
5550            AlterFunctionAction::Cost(execution_cost) => write!(f, "COST {execution_cost}"),
5551            AlterFunctionAction::Rows(result_rows) => write!(f, "ROWS {result_rows}"),
5552            AlterFunctionAction::Support(support_function) => {
5553                write!(f, "SUPPORT {support_function}")
5554            }
5555            AlterFunctionAction::Set(set_param) => write!(f, "{set_param}"),
5556            AlterFunctionAction::Reset(reset_config) => match reset_config {
5557                ResetConfig::ALL => write!(f, "RESET ALL"),
5558                ResetConfig::ConfigName(name) => write!(f, "RESET {name}"),
5559            },
5560        }
5561    }
5562}
5563
5564impl Spanned for AlterFunction {
5565    fn span(&self) -> Span {
5566        Span::empty()
5567    }
5568}
5569
5570/// CREATE POLICY statement.
5571///
5572/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createpolicy.html)
5573#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5574#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5575#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5576pub struct CreatePolicy {
5577    /// Name of the policy.
5578    pub name: Ident,
5579    /// Table the policy is defined on.
5580    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5581    pub table_name: ObjectName,
5582    /// Optional policy type (e.g., `PERMISSIVE` / `RESTRICTIVE`).
5583    pub policy_type: Option<CreatePolicyType>,
5584    /// Optional command the policy applies to (e.g., `SELECT`).
5585    pub command: Option<CreatePolicyCommand>,
5586    /// Optional list of grantee owners.
5587    pub to: Option<Vec<Owner>>,
5588    /// Optional expression for the `USING` clause.
5589    pub using: Option<Expr>,
5590    /// Optional expression for the `WITH CHECK` clause.
5591    pub with_check: Option<Expr>,
5592}
5593
5594impl fmt::Display for CreatePolicy {
5595    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5596        write!(
5597            f,
5598            "CREATE POLICY {name} ON {table_name}",
5599            name = self.name,
5600            table_name = self.table_name,
5601        )?;
5602        if let Some(ref policy_type) = self.policy_type {
5603            write!(f, " AS {policy_type}")?;
5604        }
5605        if let Some(ref command) = self.command {
5606            write!(f, " FOR {command}")?;
5607        }
5608        if let Some(ref to) = self.to {
5609            write!(f, " TO {}", display_comma_separated(to))?;
5610        }
5611        if let Some(ref using) = self.using {
5612            write!(f, " USING ({using})")?;
5613        }
5614        if let Some(ref with_check) = self.with_check {
5615            write!(f, " WITH CHECK ({with_check})")?;
5616        }
5617        Ok(())
5618    }
5619}
5620
5621/// Policy type for a `CREATE POLICY` statement.
5622/// ```sql
5623/// AS [ PERMISSIVE | RESTRICTIVE ]
5624/// ```
5625/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createpolicy.html)
5626#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5627#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5628#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5629pub enum CreatePolicyType {
5630    /// Policy allows operations unless explicitly denied.
5631    Permissive,
5632    /// Policy denies operations unless explicitly allowed.
5633    Restrictive,
5634}
5635
5636impl fmt::Display for CreatePolicyType {
5637    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5638        match self {
5639            CreatePolicyType::Permissive => write!(f, "PERMISSIVE"),
5640            CreatePolicyType::Restrictive => write!(f, "RESTRICTIVE"),
5641        }
5642    }
5643}
5644
5645/// Command that a policy can apply to (FOR clause).
5646/// ```sql
5647/// FOR [ALL | SELECT | INSERT | UPDATE | DELETE]
5648/// ```
5649/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createpolicy.html)
5650#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5651#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5652#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5653pub enum CreatePolicyCommand {
5654    /// Applies to all commands.
5655    All,
5656    /// Applies to SELECT.
5657    Select,
5658    /// Applies to INSERT.
5659    Insert,
5660    /// Applies to UPDATE.
5661    Update,
5662    /// Applies to DELETE.
5663    Delete,
5664}
5665
5666impl fmt::Display for CreatePolicyCommand {
5667    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5668        match self {
5669            CreatePolicyCommand::All => write!(f, "ALL"),
5670            CreatePolicyCommand::Select => write!(f, "SELECT"),
5671            CreatePolicyCommand::Insert => write!(f, "INSERT"),
5672            CreatePolicyCommand::Update => write!(f, "UPDATE"),
5673            CreatePolicyCommand::Delete => write!(f, "DELETE"),
5674        }
5675    }
5676}
5677
5678/// DROP POLICY statement.
5679///
5680/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-droppolicy.html)
5681#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5682#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5683#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5684pub struct DropPolicy {
5685    /// `true` when `IF EXISTS` was present.
5686    pub if_exists: bool,
5687    /// Name of the policy to drop.
5688    pub name: Ident,
5689    /// Name of the table the policy applies to.
5690    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5691    pub table_name: ObjectName,
5692    /// Optional drop behavior (`CASCADE` or `RESTRICT`).
5693    pub drop_behavior: Option<DropBehavior>,
5694}
5695
5696impl fmt::Display for DropPolicy {
5697    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5698        write!(
5699            f,
5700            "DROP POLICY {if_exists}{name} ON {table_name}",
5701            if_exists = if self.if_exists { "IF EXISTS " } else { "" },
5702            name = self.name,
5703            table_name = self.table_name
5704        )?;
5705        if let Some(ref behavior) = self.drop_behavior {
5706            write!(f, " {behavior}")?;
5707        }
5708        Ok(())
5709    }
5710}
5711
5712impl From<CreatePolicy> for crate::ast::Statement {
5713    fn from(v: CreatePolicy) -> Self {
5714        crate::ast::Statement::CreatePolicy(v)
5715    }
5716}
5717
5718impl From<DropPolicy> for crate::ast::Statement {
5719    fn from(v: DropPolicy) -> Self {
5720        crate::ast::Statement::DropPolicy(v)
5721    }
5722}
5723
5724/// ALTER POLICY statement.
5725///
5726/// ```sql
5727/// ALTER POLICY <NAME> ON <TABLE NAME> [<OPERATION>]
5728/// ```
5729/// (Postgresql-specific)
5730#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5731#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5732#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5733pub struct AlterPolicy {
5734    /// Policy name to alter.
5735    pub name: Ident,
5736    /// Target table name the policy is defined on.
5737    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5738    pub table_name: ObjectName,
5739    /// Optional operation specific to the policy alteration.
5740    pub operation: AlterPolicyOperation,
5741}
5742
5743impl fmt::Display for AlterPolicy {
5744    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5745        write!(
5746            f,
5747            "ALTER POLICY {name} ON {table_name}{operation}",
5748            name = self.name,
5749            table_name = self.table_name,
5750            operation = self.operation
5751        )
5752    }
5753}
5754
5755impl From<AlterPolicy> for crate::ast::Statement {
5756    fn from(v: AlterPolicy) -> Self {
5757        crate::ast::Statement::AlterPolicy(v)
5758    }
5759}