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 STORAGE { PLAIN | EXTERNAL | EXTENDED | MAIN | DEFAULT }`
1282    SetStorage {
1283        /// PostgreSQL column storage strategy.
1284        storage: AlterColumnStorage,
1285    },
1286    /// `[SET DATA] TYPE <data_type> [USING <expr>]`
1287    SetDataType {
1288        /// Target data type for the column.
1289        data_type: DataType,
1290        /// PostgreSQL-specific `USING <expr>` expression for conversion.
1291        using: Option<Expr>,
1292        /// Set to true if the statement includes the `SET DATA TYPE` keywords.
1293        had_set: bool,
1294    },
1295
1296    /// `ADD GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( sequence_options ) ]`
1297    ///
1298    /// Note: this is a PostgreSQL-specific operation.
1299    AddGenerated {
1300        /// Optional `GENERATED AS` specifier (e.g. `ALWAYS` or `BY DEFAULT`).
1301        generated_as: Option<GeneratedAs>,
1302        /// Optional sequence options for identity generation.
1303        sequence_options: Option<Vec<SequenceOptions>>,
1304    },
1305}
1306
1307impl fmt::Display for AlterColumnOperation {
1308    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1309        match self {
1310            AlterColumnOperation::SetNotNull => write!(f, "SET NOT NULL",),
1311            AlterColumnOperation::DropNotNull => write!(f, "DROP NOT NULL",),
1312            AlterColumnOperation::SetDefault { value } => {
1313                write!(f, "SET DEFAULT {value}")
1314            }
1315            AlterColumnOperation::DropDefault => {
1316                write!(f, "DROP DEFAULT")
1317            }
1318            AlterColumnOperation::SetStorage { storage } => {
1319                write!(f, "SET STORAGE {storage}")
1320            }
1321            AlterColumnOperation::SetDataType {
1322                data_type,
1323                using,
1324                had_set,
1325            } => {
1326                if *had_set {
1327                    write!(f, "SET DATA ")?;
1328                }
1329                write!(f, "TYPE {data_type}")?;
1330                if let Some(expr) = using {
1331                    write!(f, " USING {expr}")?;
1332                }
1333                Ok(())
1334            }
1335            AlterColumnOperation::AddGenerated {
1336                generated_as,
1337                sequence_options,
1338            } => {
1339                let generated_as = match generated_as {
1340                    Some(GeneratedAs::Always) => " ALWAYS",
1341                    Some(GeneratedAs::ByDefault) => " BY DEFAULT",
1342                    _ => "",
1343                };
1344
1345                write!(f, "ADD GENERATED{generated_as} AS IDENTITY",)?;
1346                if let Some(options) = sequence_options {
1347                    write!(f, " (")?;
1348
1349                    for sequence_option in options {
1350                        write!(f, "{sequence_option}")?;
1351                    }
1352
1353                    write!(f, " )")?;
1354                }
1355                Ok(())
1356            }
1357        }
1358    }
1359}
1360
1361/// PostgreSQL column storage strategy used by `ALTER COLUMN ... SET STORAGE`.
1362#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1363#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1364#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1365pub enum AlterColumnStorage {
1366    /// No compression or out-of-line storage.
1367    Plain,
1368    /// Out-of-line storage without compression.
1369    External,
1370    /// Compression and out-of-line storage.
1371    Extended,
1372    /// Compression with a preference for in-line storage.
1373    Main,
1374    /// Reset to the data type's default storage strategy.
1375    Default,
1376}
1377
1378impl fmt::Display for AlterColumnStorage {
1379    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1380        match self {
1381            AlterColumnStorage::Plain => write!(f, "PLAIN"),
1382            AlterColumnStorage::External => write!(f, "EXTERNAL"),
1383            AlterColumnStorage::Extended => write!(f, "EXTENDED"),
1384            AlterColumnStorage::Main => write!(f, "MAIN"),
1385            AlterColumnStorage::Default => write!(f, "DEFAULT"),
1386        }
1387    }
1388}
1389
1390/// Representation whether a definition can can contains the KEY or INDEX keywords with the same
1391/// meaning.
1392///
1393/// This enum initially is directed to `FULLTEXT`,`SPATIAL`, and `UNIQUE` indexes on create table
1394/// statements of `MySQL` [(1)].
1395///
1396/// [1]: https://dev.mysql.com/doc/refman/8.0/en/create-table.html
1397#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1398#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1399#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1400pub enum KeyOrIndexDisplay {
1401    /// Nothing to display
1402    None,
1403    /// Display the KEY keyword
1404    Key,
1405    /// Display the INDEX keyword
1406    Index,
1407}
1408
1409impl KeyOrIndexDisplay {
1410    /// Check if this is the `None` variant.
1411    pub fn is_none(self) -> bool {
1412        matches!(self, Self::None)
1413    }
1414}
1415
1416impl fmt::Display for KeyOrIndexDisplay {
1417    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1418        let left_space = matches!(f.align(), Some(fmt::Alignment::Right));
1419
1420        if left_space && !self.is_none() {
1421            f.write_char(' ')?
1422        }
1423
1424        match self {
1425            KeyOrIndexDisplay::None => {
1426                write!(f, "")
1427            }
1428            KeyOrIndexDisplay::Key => {
1429                write!(f, "KEY")
1430            }
1431            KeyOrIndexDisplay::Index => {
1432                write!(f, "INDEX")
1433            }
1434        }
1435    }
1436}
1437
1438/// Indexing method used by that index.
1439///
1440/// This structure isn't present on ANSI, but is found at least in [`MySQL` CREATE TABLE][1],
1441/// [`MySQL` CREATE INDEX][2], and [Postgresql CREATE INDEX][3] statements.
1442///
1443/// [1]: https://dev.mysql.com/doc/refman/8.0/en/create-table.html
1444/// [2]: https://dev.mysql.com/doc/refman/8.0/en/create-index.html
1445/// [3]: https://www.postgresql.org/docs/14/sql-createindex.html
1446#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1447#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1448#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1449pub enum IndexType {
1450    /// B-Tree index (commonly default for many databases).
1451    BTree,
1452    /// Hash index.
1453    Hash,
1454    /// Generalized Inverted Index (GIN).
1455    GIN,
1456    /// Generalized Search Tree (GiST) index.
1457    GiST,
1458    /// Space-partitioned GiST (SPGiST) index.
1459    SPGiST,
1460    /// Block Range Index (BRIN).
1461    BRIN,
1462    /// Bloom filter based index.
1463    Bloom,
1464    /// Users may define their own index types, which would
1465    /// not be covered by the above variants.
1466    Custom(Ident),
1467}
1468
1469impl fmt::Display for IndexType {
1470    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1471        match self {
1472            Self::BTree => write!(f, "BTREE"),
1473            Self::Hash => write!(f, "HASH"),
1474            Self::GIN => write!(f, "GIN"),
1475            Self::GiST => write!(f, "GIST"),
1476            Self::SPGiST => write!(f, "SPGIST"),
1477            Self::BRIN => write!(f, "BRIN"),
1478            Self::Bloom => write!(f, "BLOOM"),
1479            Self::Custom(name) => write!(f, "{name}"),
1480        }
1481    }
1482}
1483
1484/// MySQL index option, used in [`CREATE TABLE`], [`CREATE INDEX`], and [`ALTER TABLE`].
1485///
1486/// [`CREATE TABLE`]: https://dev.mysql.com/doc/refman/8.4/en/create-table.html
1487/// [`CREATE INDEX`]: https://dev.mysql.com/doc/refman/8.4/en/create-index.html
1488/// [`ALTER TABLE`]: https://dev.mysql.com/doc/refman/8.4/en/alter-table.html
1489#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1490#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1491#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1492pub enum IndexOption {
1493    /// `USING { BTREE | HASH }`: Index type to use for the index.
1494    ///
1495    /// Note that we permissively parse non-MySQL index types, like `GIN`.
1496    Using(IndexType),
1497    /// `COMMENT 'string'`: Specifies a comment for the index.
1498    Comment(String),
1499}
1500
1501impl fmt::Display for IndexOption {
1502    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1503        match self {
1504            Self::Using(index_type) => write!(f, "USING {index_type}"),
1505            Self::Comment(s) => write!(f, "COMMENT '{s}'"),
1506        }
1507    }
1508}
1509
1510/// [PostgreSQL] unique index nulls handling option: `[ NULLS [ NOT ] DISTINCT ]`
1511///
1512/// [PostgreSQL]: https://www.postgresql.org/docs/17/sql-altertable.html
1513#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1514#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1515#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1516pub enum NullsDistinctOption {
1517    /// Not specified
1518    None,
1519    /// NULLS DISTINCT
1520    Distinct,
1521    /// NULLS NOT DISTINCT
1522    NotDistinct,
1523}
1524
1525impl fmt::Display for NullsDistinctOption {
1526    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1527        match self {
1528            Self::None => Ok(()),
1529            Self::Distinct => write!(f, " NULLS DISTINCT"),
1530            Self::NotDistinct => write!(f, " NULLS NOT DISTINCT"),
1531        }
1532    }
1533}
1534
1535#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1536#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1537#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1538/// A parameter of a stored procedure or function declaration.
1539pub struct ProcedureParam {
1540    /// Parameter name.
1541    pub name: Ident,
1542    /// Parameter data type.
1543    pub data_type: DataType,
1544    /// Optional mode (`IN`, `OUT`, `INOUT`, etc.).
1545    pub mode: Option<ArgMode>,
1546    /// Optional default expression for the parameter.
1547    pub default: Option<Expr>,
1548}
1549
1550impl fmt::Display for ProcedureParam {
1551    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1552        if let Some(mode) = &self.mode {
1553            if let Some(default) = &self.default {
1554                write!(f, "{mode} {} {} = {}", self.name, self.data_type, default)
1555            } else {
1556                write!(f, "{mode} {} {}", self.name, self.data_type)
1557            }
1558        } else if let Some(default) = &self.default {
1559            write!(f, "{} {} = {}", self.name, self.data_type, default)
1560        } else {
1561            write!(f, "{} {}", self.name, self.data_type)
1562        }
1563    }
1564}
1565
1566/// SQL column definition
1567#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1568#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1569#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1570pub struct ColumnDef {
1571    /// Column name.
1572    pub name: Ident,
1573    /// Column data type.
1574    pub data_type: DataType,
1575    /// Column options (defaults, constraints, generated, etc.).
1576    pub options: Vec<ColumnOptionDef>,
1577}
1578
1579impl fmt::Display for ColumnDef {
1580    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1581        if self.data_type == DataType::Unspecified {
1582            write!(f, "{}", self.name)?;
1583        } else {
1584            write!(f, "{} {}", self.name, self.data_type)?;
1585        }
1586        for option in &self.options {
1587            write!(f, " {option}")?;
1588        }
1589        Ok(())
1590    }
1591}
1592
1593/// Column definition specified in a `CREATE VIEW` statement.
1594///
1595/// Syntax
1596/// ```markdown
1597/// <name> [data_type][OPTIONS(option, ...)]
1598///
1599/// option: <name> = <value>
1600/// ```
1601///
1602/// Examples:
1603/// ```sql
1604/// name
1605/// age OPTIONS(description = "age column", tag = "prod")
1606/// amount COMMENT 'The total amount for the order line'
1607/// created_at DateTime64
1608/// ```
1609#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1610#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1611#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1612pub struct ViewColumnDef {
1613    /// Column identifier.
1614    pub name: Ident,
1615    /// Optional data type for the column.
1616    pub data_type: Option<DataType>,
1617    /// Optional column options (defaults, comments, etc.).
1618    pub options: Option<ColumnOptions>,
1619}
1620
1621#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1622#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1623#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1624/// Representation of how multiple `ColumnOption`s are grouped for a column.
1625pub enum ColumnOptions {
1626    /// Options separated by comma: `OPTIONS(a, b, c)`.
1627    CommaSeparated(Vec<ColumnOption>),
1628    /// Options separated by spaces: `OPTION_A OPTION_B`.
1629    SpaceSeparated(Vec<ColumnOption>),
1630}
1631
1632impl ColumnOptions {
1633    /// Get the column options as a slice.
1634    pub fn as_slice(&self) -> &[ColumnOption] {
1635        match self {
1636            ColumnOptions::CommaSeparated(options) => options.as_slice(),
1637            ColumnOptions::SpaceSeparated(options) => options.as_slice(),
1638        }
1639    }
1640}
1641
1642impl fmt::Display for ViewColumnDef {
1643    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1644        write!(f, "{}", self.name)?;
1645        if let Some(data_type) = self.data_type.as_ref() {
1646            write!(f, " {data_type}")?;
1647        }
1648        if let Some(options) = self.options.as_ref() {
1649            match options {
1650                ColumnOptions::CommaSeparated(column_options) => {
1651                    write!(f, " {}", display_comma_separated(column_options.as_slice()))?;
1652                }
1653                ColumnOptions::SpaceSeparated(column_options) => {
1654                    write!(f, " {}", display_separated(column_options.as_slice(), " "))?
1655                }
1656            }
1657        }
1658        Ok(())
1659    }
1660}
1661
1662/// An optionally-named `ColumnOption`: `[ CONSTRAINT <name> ] <column-option>`.
1663///
1664/// Note that implementations are substantially more permissive than the ANSI
1665/// specification on what order column options can be presented in, and whether
1666/// they are allowed to be named. The specification distinguishes between
1667/// constraints (NOT NULL, UNIQUE, PRIMARY KEY, and CHECK), which can be named
1668/// and can appear in any order, and other options (DEFAULT, GENERATED), which
1669/// cannot be named and must appear in a fixed order. `PostgreSQL`, however,
1670/// allows preceding any option with `CONSTRAINT <name>`, even those that are
1671/// not really constraints, like NULL and DEFAULT. MSSQL is less permissive,
1672/// allowing DEFAULT, UNIQUE, PRIMARY KEY and CHECK to be named, but not NULL or
1673/// NOT NULL constraints (the last of which is in violation of the spec).
1674///
1675/// For maximum flexibility, we don't distinguish between constraint and
1676/// non-constraint options, lumping them all together under the umbrella of
1677/// "column options," and we allow any column option to be named.
1678#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1679#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1680#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1681pub struct ColumnOptionDef {
1682    /// Optional name of the constraint.
1683    pub name: Option<Ident>,
1684    /// The actual column option (e.g. `NOT NULL`, `DEFAULT`, `GENERATED`, ...).
1685    pub option: ColumnOption,
1686}
1687
1688impl fmt::Display for ColumnOptionDef {
1689    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1690        write!(f, "{}{}", display_constraint_name(&self.name), self.option)
1691    }
1692}
1693
1694/// Identity is a column option for defining an identity or autoincrement column in a `CREATE TABLE` statement.
1695/// Syntax
1696/// ```sql
1697/// { IDENTITY | AUTOINCREMENT } [ (seed , increment) | START num INCREMENT num ] [ ORDER | NOORDER ]
1698/// ```
1699/// [MS SQL Server]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property
1700/// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1701#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1702#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1703#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1704pub enum IdentityPropertyKind {
1705    /// An identity property declared via the `AUTOINCREMENT` key word
1706    /// Example:
1707    /// ```sql
1708    ///  AUTOINCREMENT(100, 1) NOORDER
1709    ///  AUTOINCREMENT START 100 INCREMENT 1 ORDER
1710    /// ```
1711    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1712    Autoincrement(IdentityProperty),
1713    /// An identity property declared via the `IDENTITY` key word
1714    /// Example, [MS SQL Server] or [Snowflake]:
1715    /// ```sql
1716    ///  IDENTITY(100, 1)
1717    /// ```
1718    /// [Snowflake]
1719    /// ```sql
1720    ///  IDENTITY(100, 1) ORDER
1721    ///  IDENTITY START 100 INCREMENT 1 NOORDER
1722    /// ```
1723    /// [MS SQL Server]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property
1724    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1725    Identity(IdentityProperty),
1726}
1727
1728impl fmt::Display for IdentityPropertyKind {
1729    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1730        let (command, property) = match self {
1731            IdentityPropertyKind::Identity(property) => ("IDENTITY", property),
1732            IdentityPropertyKind::Autoincrement(property) => ("AUTOINCREMENT", property),
1733        };
1734        write!(f, "{command}")?;
1735        if let Some(parameters) = &property.parameters {
1736            write!(f, "{parameters}")?;
1737        }
1738        if let Some(order) = &property.order {
1739            write!(f, "{order}")?;
1740        }
1741        Ok(())
1742    }
1743}
1744
1745/// Properties for the `IDENTITY` / `AUTOINCREMENT` column option.
1746#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1747#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1748#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1749pub struct IdentityProperty {
1750    /// Optional parameters specifying seed/increment for the identity column.
1751    pub parameters: Option<IdentityPropertyFormatKind>,
1752    /// Optional ordering specifier (`ORDER` / `NOORDER`).
1753    pub order: Option<IdentityPropertyOrder>,
1754}
1755
1756/// A format of parameters of identity column.
1757///
1758/// It is [Snowflake] specific.
1759/// Syntax
1760/// ```sql
1761/// (seed , increment) | START num INCREMENT num
1762/// ```
1763/// [MS SQL Server] uses one way of representing these parameters.
1764/// Syntax
1765/// ```sql
1766/// (seed , increment)
1767/// ```
1768/// [MS SQL Server]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property
1769/// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1770#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1771#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1772#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1773pub enum IdentityPropertyFormatKind {
1774    /// A parameters of identity column declared like parameters of function call
1775    /// Example:
1776    /// ```sql
1777    ///  (100, 1)
1778    /// ```
1779    /// [MS SQL Server]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property
1780    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1781    FunctionCall(IdentityParameters),
1782    /// A parameters of identity column declared with keywords `START` and `INCREMENT`
1783    /// Example:
1784    /// ```sql
1785    ///  START 100 INCREMENT 1
1786    /// ```
1787    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1788    StartAndIncrement(IdentityParameters),
1789}
1790
1791impl fmt::Display for IdentityPropertyFormatKind {
1792    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1793        match self {
1794            IdentityPropertyFormatKind::FunctionCall(parameters) => {
1795                write!(f, "({}, {})", parameters.seed, parameters.increment)
1796            }
1797            IdentityPropertyFormatKind::StartAndIncrement(parameters) => {
1798                write!(
1799                    f,
1800                    " START {} INCREMENT {}",
1801                    parameters.seed, parameters.increment
1802                )
1803            }
1804        }
1805    }
1806}
1807/// Parameters specifying seed and increment for identity columns.
1808#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1809#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1810#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1811pub struct IdentityParameters {
1812    /// The initial seed expression for the identity column.
1813    pub seed: Expr,
1814    /// The increment expression for the identity column.
1815    pub increment: Expr,
1816}
1817
1818/// The identity column option specifies how values are generated for the auto-incremented column, either in increasing or decreasing order.
1819/// Syntax
1820/// ```sql
1821/// ORDER | NOORDER
1822/// ```
1823/// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1824#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1825#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1826#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1827pub enum IdentityPropertyOrder {
1828    /// `ORDER` - preserve ordering for generated values (where supported).
1829    Order,
1830    /// `NOORDER` - do not enforce ordering for generated values.
1831    NoOrder,
1832}
1833
1834impl fmt::Display for IdentityPropertyOrder {
1835    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1836        match self {
1837            IdentityPropertyOrder::Order => write!(f, " ORDER"),
1838            IdentityPropertyOrder::NoOrder => write!(f, " NOORDER"),
1839        }
1840    }
1841}
1842
1843/// Column policy that identify a security policy of access to a column.
1844/// Syntax
1845/// ```sql
1846/// [ WITH ] MASKING POLICY <policy_name> [ USING ( <col_name> , <cond_col1> , ... ) ]
1847/// [ WITH ] PROJECTION POLICY <policy_name>
1848/// ```
1849/// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1850#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1851#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1852#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1853pub enum ColumnPolicy {
1854    /// `MASKING POLICY (<property>)`
1855    MaskingPolicy(ColumnPolicyProperty),
1856    /// `PROJECTION POLICY (<property>)`
1857    ProjectionPolicy(ColumnPolicyProperty),
1858}
1859
1860impl fmt::Display for ColumnPolicy {
1861    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1862        let (command, property) = match self {
1863            ColumnPolicy::MaskingPolicy(property) => ("MASKING POLICY", property),
1864            ColumnPolicy::ProjectionPolicy(property) => ("PROJECTION POLICY", property),
1865        };
1866        if property.with {
1867            write!(f, "WITH ")?;
1868        }
1869        write!(f, "{command} {}", property.policy_name)?;
1870        if let Some(using_columns) = &property.using_columns {
1871            write!(f, " USING ({})", display_comma_separated(using_columns))?;
1872        }
1873        Ok(())
1874    }
1875}
1876
1877#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1878#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1879#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1880/// Properties describing a column policy (masking or projection).
1881pub struct ColumnPolicyProperty {
1882    /// This flag indicates that the column policy option is declared using the `WITH` prefix.
1883    /// Example
1884    /// ```sql
1885    /// WITH PROJECTION POLICY sample_policy
1886    /// ```
1887    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1888    pub with: bool,
1889    /// The name of the policy to apply to the column.
1890    pub policy_name: ObjectName,
1891    /// Optional list of column identifiers referenced by the policy.
1892    pub using_columns: Option<Vec<Ident>>,
1893}
1894
1895/// Tags option of column
1896/// Syntax
1897/// ```sql
1898/// [ WITH ] TAG ( <tag_name> = '<tag_value>' [ , <tag_name> = '<tag_value>' , ... ] )
1899/// ```
1900/// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1901#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1902#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1903#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1904pub struct TagsColumnOption {
1905    /// This flag indicates that the tags option is declared using the `WITH` prefix.
1906    /// Example:
1907    /// ```sql
1908    /// WITH TAG (A = 'Tag A')
1909    /// ```
1910    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
1911    pub with: bool,
1912    /// List of tags to attach to the column.
1913    pub tags: Vec<Tag>,
1914}
1915
1916impl fmt::Display for TagsColumnOption {
1917    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1918        if self.with {
1919            write!(f, "WITH ")?;
1920        }
1921        write!(f, "TAG ({})", display_comma_separated(&self.tags))?;
1922        Ok(())
1923    }
1924}
1925
1926/// `ColumnOption`s are modifiers that follow a column definition in a `CREATE
1927/// TABLE` statement.
1928#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1929#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1930#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1931pub enum ColumnOption {
1932    /// `NULL`
1933    Null,
1934    /// `NOT NULL`
1935    NotNull,
1936    /// `DEFAULT <restricted-expr>`
1937    Default(Expr),
1938
1939    /// `MATERIALIZE <expr>`
1940    /// Syntax: `b INT MATERIALIZE (a + 1)`
1941    ///
1942    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/create/table#default_values)
1943    Materialized(Expr),
1944    /// `EPHEMERAL [<expr>]`
1945    ///
1946    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/create/table#default_values)
1947    Ephemeral(Option<Expr>),
1948    /// `ALIAS <expr>`
1949    ///
1950    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/create/table#default_values)
1951    Alias(Expr),
1952
1953    /// `PRIMARY KEY [<constraint_characteristics>]`
1954    PrimaryKey(PrimaryKeyConstraint),
1955    /// `UNIQUE [<constraint_characteristics>]`
1956    Unique(UniqueConstraint),
1957    /// A referential integrity constraint (`REFERENCES <foreign_table> (<referred_columns>)
1958    /// [ MATCH { FULL | PARTIAL | SIMPLE } ]
1959    /// { [ON DELETE <referential_action>] [ON UPDATE <referential_action>] |
1960    ///   [ON UPDATE <referential_action>] [ON DELETE <referential_action>]
1961    /// }
1962    /// [<constraint_characteristics>]
1963    /// `).
1964    ForeignKey(ForeignKeyConstraint),
1965    /// `CHECK (<expr>)`
1966    Check(CheckConstraint),
1967    /// Dialect-specific options, such as:
1968    /// - MySQL's `AUTO_INCREMENT` or SQLite's `AUTOINCREMENT`
1969    /// - ...
1970    DialectSpecific(Vec<Token>),
1971    /// `CHARACTER SET <name>` column option
1972    CharacterSet(ObjectName),
1973    /// `COLLATE <name>` column option
1974    Collation(ObjectName),
1975    /// `COMMENT '<text>'` column option
1976    Comment(String),
1977    /// `ON UPDATE <expr>` column option
1978    OnUpdate(Expr),
1979    /// `Generated`s are modifiers that follow a column definition in a `CREATE
1980    /// TABLE` statement.
1981    Generated {
1982        /// How the column is generated (e.g. `GENERATED ALWAYS`, `BY DEFAULT`, or expression-stored).
1983        generated_as: GeneratedAs,
1984        /// Sequence/identity options when generation is backed by a sequence.
1985        sequence_options: Option<Vec<SequenceOptions>>,
1986        /// Optional expression used to generate the column value.
1987        generation_expr: Option<Expr>,
1988        /// Mode of the generated expression (`VIRTUAL` or `STORED`) when `generation_expr` is present.
1989        generation_expr_mode: Option<GeneratedExpressionMode>,
1990        /// false if 'GENERATED ALWAYS' is skipped (option starts with AS)
1991        generated_keyword: bool,
1992    },
1993    /// BigQuery specific: Explicit column options in a view [1] or table [2]
1994    /// Syntax
1995    /// ```sql
1996    /// OPTIONS(description="field desc")
1997    /// ```
1998    /// [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#view_column_option_list
1999    /// [2]: https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#column_option_list
2000    Options(Vec<SqlOption>),
2001    /// Creates an identity or an autoincrement column in a table.
2002    /// Syntax
2003    /// ```sql
2004    /// { IDENTITY | AUTOINCREMENT } [ (seed , increment) | START num INCREMENT num ] [ ORDER | NOORDER ]
2005    /// ```
2006    /// [MS SQL Server]: https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property
2007    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
2008    Identity(IdentityPropertyKind),
2009    /// SQLite specific: ON CONFLICT option on column definition
2010    /// <https://www.sqlite.org/lang_conflict.html>
2011    OnConflict(Keyword),
2012    /// Snowflake specific: an option of specifying security masking or projection policy to set on a column.
2013    /// Syntax:
2014    /// ```sql
2015    /// [ WITH ] MASKING POLICY <policy_name> [ USING ( <col_name> , <cond_col1> , ... ) ]
2016    /// [ WITH ] PROJECTION POLICY <policy_name>
2017    /// ```
2018    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
2019    Policy(ColumnPolicy),
2020    /// Snowflake specific: Specifies the tag name and the tag string value.
2021    /// Syntax:
2022    /// ```sql
2023    /// [ WITH ] TAG ( <tag_name> = '<tag_value>' [ , <tag_name> = '<tag_value>' , ... ] )
2024    /// ```
2025    /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/sql/create-table
2026    Tags(TagsColumnOption),
2027    /// MySQL specific: Spatial reference identifier
2028    /// Syntax:
2029    /// ```sql
2030    /// CREATE TABLE geom (g GEOMETRY NOT NULL SRID 4326);
2031    /// ```
2032    /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/creating-spatial-indexes.html
2033    Srid(Box<Expr>),
2034    /// MySQL specific: Column is invisible via SELECT *
2035    /// Syntax:
2036    /// ```sql
2037    /// CREATE TABLE t (foo INT, bar INT INVISIBLE);
2038    /// ```
2039    /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/invisible-columns.html
2040    Invisible,
2041}
2042
2043impl From<UniqueConstraint> for ColumnOption {
2044    fn from(c: UniqueConstraint) -> Self {
2045        ColumnOption::Unique(c)
2046    }
2047}
2048
2049impl From<PrimaryKeyConstraint> for ColumnOption {
2050    fn from(c: PrimaryKeyConstraint) -> Self {
2051        ColumnOption::PrimaryKey(c)
2052    }
2053}
2054
2055impl From<CheckConstraint> for ColumnOption {
2056    fn from(c: CheckConstraint) -> Self {
2057        ColumnOption::Check(c)
2058    }
2059}
2060impl From<ForeignKeyConstraint> for ColumnOption {
2061    fn from(fk: ForeignKeyConstraint) -> Self {
2062        ColumnOption::ForeignKey(fk)
2063    }
2064}
2065
2066impl fmt::Display for ColumnOption {
2067    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2068        use ColumnOption::*;
2069        match self {
2070            Null => write!(f, "NULL"),
2071            NotNull => write!(f, "NOT NULL"),
2072            Default(expr) => write!(f, "DEFAULT {expr}"),
2073            Materialized(expr) => write!(f, "MATERIALIZED {expr}"),
2074            Ephemeral(expr) => {
2075                if let Some(e) = expr {
2076                    write!(f, "EPHEMERAL {e}")
2077                } else {
2078                    write!(f, "EPHEMERAL")
2079                }
2080            }
2081            Alias(expr) => write!(f, "ALIAS {expr}"),
2082            PrimaryKey(constraint) => {
2083                write!(f, "PRIMARY KEY")?;
2084                if let Some(characteristics) = &constraint.characteristics {
2085                    write!(f, " {characteristics}")?;
2086                }
2087                Ok(())
2088            }
2089            Unique(constraint) => {
2090                write!(f, "UNIQUE{:>}", constraint.index_type_display)?;
2091                if let Some(characteristics) = &constraint.characteristics {
2092                    write!(f, " {characteristics}")?;
2093                }
2094                Ok(())
2095            }
2096            ForeignKey(constraint) => {
2097                write!(f, "REFERENCES {}", constraint.foreign_table)?;
2098                if !constraint.referred_columns.is_empty() {
2099                    write!(
2100                        f,
2101                        " ({})",
2102                        display_comma_separated(&constraint.referred_columns)
2103                    )?;
2104                }
2105                if let Some(match_kind) = &constraint.match_kind {
2106                    write!(f, " {match_kind}")?;
2107                }
2108                if let Some(action) = &constraint.on_delete {
2109                    write!(f, " ON DELETE {action}")?;
2110                }
2111                if let Some(action) = &constraint.on_update {
2112                    write!(f, " ON UPDATE {action}")?;
2113                }
2114                if let Some(characteristics) = &constraint.characteristics {
2115                    write!(f, " {characteristics}")?;
2116                }
2117                Ok(())
2118            }
2119            Check(constraint) => write!(f, "{constraint}"),
2120            DialectSpecific(val) => write!(f, "{}", display_separated(val, " ")),
2121            CharacterSet(n) => write!(f, "CHARACTER SET {n}"),
2122            Collation(n) => write!(f, "COLLATE {n}"),
2123            Comment(v) => write!(f, "COMMENT '{}'", escape_single_quote_string(v)),
2124            OnUpdate(expr) => write!(f, "ON UPDATE {expr}"),
2125            Generated {
2126                generated_as,
2127                sequence_options,
2128                generation_expr,
2129                generation_expr_mode,
2130                generated_keyword,
2131            } => {
2132                if let Some(expr) = generation_expr {
2133                    let modifier = match generation_expr_mode {
2134                        None => "",
2135                        Some(GeneratedExpressionMode::Virtual) => " VIRTUAL",
2136                        Some(GeneratedExpressionMode::Stored) => " STORED",
2137                    };
2138                    if *generated_keyword {
2139                        write!(f, "GENERATED ALWAYS AS ({expr}){modifier}")?;
2140                    } else {
2141                        write!(f, "AS ({expr}){modifier}")?;
2142                    }
2143                    Ok(())
2144                } else {
2145                    // Like Postgres - generated from sequence
2146                    let when = match generated_as {
2147                        GeneratedAs::Always => "ALWAYS",
2148                        GeneratedAs::ByDefault => "BY DEFAULT",
2149                        // ExpStored goes with an expression, handled above
2150                        GeneratedAs::ExpStored => "",
2151                    };
2152                    write!(f, "GENERATED {when} AS IDENTITY")?;
2153                    if let Some(so) = sequence_options {
2154                        if !so.is_empty() {
2155                            write!(f, " (")?;
2156                        }
2157                        for sequence_option in so {
2158                            write!(f, "{sequence_option}")?;
2159                        }
2160                        if !so.is_empty() {
2161                            write!(f, " )")?;
2162                        }
2163                    }
2164                    Ok(())
2165                }
2166            }
2167            Options(options) => {
2168                write!(f, "OPTIONS({})", display_comma_separated(options))
2169            }
2170            Identity(parameters) => {
2171                write!(f, "{parameters}")
2172            }
2173            OnConflict(keyword) => {
2174                write!(f, "ON CONFLICT {keyword:?}")?;
2175                Ok(())
2176            }
2177            Policy(parameters) => {
2178                write!(f, "{parameters}")
2179            }
2180            Tags(tags) => {
2181                write!(f, "{tags}")
2182            }
2183            Srid(srid) => {
2184                write!(f, "SRID {srid}")
2185            }
2186            Invisible => {
2187                write!(f, "INVISIBLE")
2188            }
2189        }
2190    }
2191}
2192
2193/// `GeneratedAs`s are modifiers that follow a column option in a `generated`.
2194/// 'ExpStored' is used for a column generated from an expression and stored.
2195#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2196#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2197#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2198pub enum GeneratedAs {
2199    /// `GENERATED ALWAYS`
2200    Always,
2201    /// `GENERATED BY DEFAULT`
2202    ByDefault,
2203    /// Expression-based generated column that is stored (used internally for expression-stored columns)
2204    ExpStored,
2205}
2206
2207/// `GeneratedExpressionMode`s are modifiers that follow an expression in a `generated`.
2208/// No modifier is typically the same as Virtual.
2209#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2210#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2211#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2212pub enum GeneratedExpressionMode {
2213    /// `VIRTUAL` generated expression
2214    Virtual,
2215    /// `STORED` generated expression
2216    Stored,
2217}
2218
2219#[must_use]
2220pub(crate) fn display_constraint_name(name: &'_ Option<Ident>) -> impl fmt::Display + '_ {
2221    struct ConstraintName<'a>(&'a Option<Ident>);
2222    impl fmt::Display for ConstraintName<'_> {
2223        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2224            if let Some(name) = self.0 {
2225                write!(f, "CONSTRAINT {name} ")?;
2226            }
2227            Ok(())
2228        }
2229    }
2230    ConstraintName(name)
2231}
2232
2233/// If `option` is
2234/// * `Some(inner)` => create display struct for `"{prefix}{inner}{postfix}"`
2235/// * `_` => do nothing
2236#[must_use]
2237pub(crate) fn display_option<'a, T: fmt::Display>(
2238    prefix: &'a str,
2239    postfix: &'a str,
2240    option: &'a Option<T>,
2241) -> impl fmt::Display + 'a {
2242    struct OptionDisplay<'a, T>(&'a str, &'a str, &'a Option<T>);
2243    impl<T: fmt::Display> fmt::Display for OptionDisplay<'_, T> {
2244        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2245            if let Some(inner) = self.2 {
2246                let (prefix, postfix) = (self.0, self.1);
2247                write!(f, "{prefix}{inner}{postfix}")?;
2248            }
2249            Ok(())
2250        }
2251    }
2252    OptionDisplay(prefix, postfix, option)
2253}
2254
2255/// If `option` is
2256/// * `Some(inner)` => create display struct for `" {inner}"`
2257/// * `_` => do nothing
2258#[must_use]
2259pub(crate) fn display_option_spaced<T: fmt::Display>(option: &Option<T>) -> impl fmt::Display + '_ {
2260    display_option(" ", "", option)
2261}
2262
2263/// `<constraint_characteristics> = [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ] [ ENFORCED | NOT ENFORCED ]`
2264///
2265/// Used in UNIQUE and foreign key constraints. The individual settings may occur in any order.
2266#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Default, Eq, Ord, Hash)]
2267#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2268#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2269pub struct ConstraintCharacteristics {
2270    /// `[ DEFERRABLE | NOT DEFERRABLE ]`
2271    pub deferrable: Option<bool>,
2272    /// `[ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]`
2273    pub initially: Option<DeferrableInitial>,
2274    /// `[ ENFORCED | NOT ENFORCED ]`
2275    pub enforced: Option<bool>,
2276}
2277
2278/// Initial setting for deferrable constraints (`INITIALLY IMMEDIATE` or `INITIALLY DEFERRED`).
2279#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2280#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2281#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2282pub enum DeferrableInitial {
2283    /// `INITIALLY IMMEDIATE`
2284    Immediate,
2285    /// `INITIALLY DEFERRED`
2286    Deferred,
2287}
2288
2289impl ConstraintCharacteristics {
2290    fn deferrable_text(&self) -> Option<&'static str> {
2291        self.deferrable.map(|deferrable| {
2292            if deferrable {
2293                "DEFERRABLE"
2294            } else {
2295                "NOT DEFERRABLE"
2296            }
2297        })
2298    }
2299
2300    fn initially_immediate_text(&self) -> Option<&'static str> {
2301        self.initially
2302            .map(|initially_immediate| match initially_immediate {
2303                DeferrableInitial::Immediate => "INITIALLY IMMEDIATE",
2304                DeferrableInitial::Deferred => "INITIALLY DEFERRED",
2305            })
2306    }
2307
2308    fn enforced_text(&self) -> Option<&'static str> {
2309        self.enforced.map(
2310            |enforced| {
2311                if enforced {
2312                    "ENFORCED"
2313                } else {
2314                    "NOT ENFORCED"
2315                }
2316            },
2317        )
2318    }
2319}
2320
2321impl fmt::Display for ConstraintCharacteristics {
2322    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2323        let deferrable = self.deferrable_text();
2324        let initially_immediate = self.initially_immediate_text();
2325        let enforced = self.enforced_text();
2326
2327        match (deferrable, initially_immediate, enforced) {
2328            (None, None, None) => Ok(()),
2329            (None, None, Some(enforced)) => write!(f, "{enforced}"),
2330            (None, Some(initial), None) => write!(f, "{initial}"),
2331            (None, Some(initial), Some(enforced)) => write!(f, "{initial} {enforced}"),
2332            (Some(deferrable), None, None) => write!(f, "{deferrable}"),
2333            (Some(deferrable), None, Some(enforced)) => write!(f, "{deferrable} {enforced}"),
2334            (Some(deferrable), Some(initial), None) => write!(f, "{deferrable} {initial}"),
2335            (Some(deferrable), Some(initial), Some(enforced)) => {
2336                write!(f, "{deferrable} {initial} {enforced}")
2337            }
2338        }
2339    }
2340}
2341
2342/// `<referential_action> =
2343/// { RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT }`
2344///
2345/// Used in foreign key constraints in `ON UPDATE` and `ON DELETE` options.
2346#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2347#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2348#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2349pub enum ReferentialAction {
2350    /// `RESTRICT` - disallow action if it would break referential integrity.
2351    Restrict,
2352    /// `CASCADE` - propagate the action to referencing rows.
2353    Cascade,
2354    /// `SET NULL` - set referencing columns to NULL.
2355    SetNull,
2356    /// `NO ACTION` - no action at the time; may be deferred.
2357    NoAction,
2358    /// `SET DEFAULT` - set referencing columns to their default values.
2359    SetDefault,
2360}
2361
2362impl fmt::Display for ReferentialAction {
2363    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2364        f.write_str(match self {
2365            ReferentialAction::Restrict => "RESTRICT",
2366            ReferentialAction::Cascade => "CASCADE",
2367            ReferentialAction::SetNull => "SET NULL",
2368            ReferentialAction::NoAction => "NO ACTION",
2369            ReferentialAction::SetDefault => "SET DEFAULT",
2370        })
2371    }
2372}
2373
2374/// `<drop behavior> ::= CASCADE | RESTRICT`.
2375///
2376/// Used in `DROP` statements.
2377#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2378#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2379#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2380pub enum DropBehavior {
2381    /// `RESTRICT` - refuse to drop if there are any dependent objects.
2382    Restrict,
2383    /// `CASCADE` - automatically drop objects that depend on the object being dropped.
2384    Cascade,
2385}
2386
2387impl fmt::Display for DropBehavior {
2388    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2389        f.write_str(match self {
2390            DropBehavior::Restrict => "RESTRICT",
2391            DropBehavior::Cascade => "CASCADE",
2392        })
2393    }
2394}
2395
2396/// SQL user defined type definition
2397#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2398#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2399#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2400pub enum UserDefinedTypeRepresentation {
2401    /// Composite type: `CREATE TYPE name AS (attributes)`
2402    Composite {
2403        /// List of attributes for the composite type.
2404        attributes: Vec<UserDefinedTypeCompositeAttributeDef>,
2405    },
2406    /// Enum type: `CREATE TYPE name AS ENUM (labels)`
2407    ///
2408    /// Note: this is PostgreSQL-specific. See <https://www.postgresql.org/docs/current/sql-createtype.html>
2409    /// Enum type: `CREATE TYPE name AS ENUM (labels)`
2410    Enum {
2411        /// Labels that make up the enum type.
2412        labels: Vec<Ident>,
2413    },
2414    /// Range type: `CREATE TYPE name AS RANGE (options)`
2415    ///
2416    /// Note: this is PostgreSQL-specific. See <https://www.postgresql.org/docs/current/sql-createtype.html>
2417    Range {
2418        /// Options for the range type definition.
2419        options: Vec<UserDefinedTypeRangeOption>,
2420    },
2421    /// Base type (SQL definition): `CREATE TYPE name (options)`
2422    ///
2423    /// Note the lack of `AS` keyword
2424    ///
2425    /// Note: this is PostgreSQL-specific. See <https://www.postgresql.org/docs/current/sql-createtype.html>
2426    SqlDefinition {
2427        /// Options for SQL definition of the user-defined type.
2428        options: Vec<UserDefinedTypeSqlDefinitionOption>,
2429    },
2430}
2431
2432impl fmt::Display for UserDefinedTypeRepresentation {
2433    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2434        match self {
2435            Self::Composite { attributes } => {
2436                write!(f, "AS ({})", display_comma_separated(attributes))
2437            }
2438            Self::Enum { labels } => {
2439                write!(f, "AS ENUM ({})", display_comma_separated(labels))
2440            }
2441            Self::Range { options } => {
2442                write!(f, "AS RANGE ({})", display_comma_separated(options))
2443            }
2444            Self::SqlDefinition { options } => {
2445                write!(f, "({})", display_comma_separated(options))
2446            }
2447        }
2448    }
2449}
2450
2451/// SQL user defined type attribute definition
2452#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2453#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2454#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2455pub struct UserDefinedTypeCompositeAttributeDef {
2456    /// Attribute name.
2457    pub name: Ident,
2458    /// Attribute data type.
2459    pub data_type: DataType,
2460    /// Optional collation for the attribute.
2461    pub collation: Option<ObjectName>,
2462}
2463
2464impl fmt::Display for UserDefinedTypeCompositeAttributeDef {
2465    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2466        write!(f, "{} {}", self.name, self.data_type)?;
2467        if let Some(collation) = &self.collation {
2468            write!(f, " COLLATE {collation}")?;
2469        }
2470        Ok(())
2471    }
2472}
2473
2474/// Internal length specification for PostgreSQL user-defined base types.
2475///
2476/// Specifies the internal length in bytes of the new type's internal representation.
2477/// The default assumption is that it is variable-length.
2478///
2479/// # PostgreSQL Documentation
2480/// See: <https://www.postgresql.org/docs/current/sql-createtype.html>
2481///
2482/// # Examples
2483/// ```sql
2484/// CREATE TYPE mytype (
2485///     INPUT = in_func,
2486///     OUTPUT = out_func,
2487///     INTERNALLENGTH = 16  -- Fixed 16-byte length
2488/// );
2489///
2490/// CREATE TYPE mytype2 (
2491///     INPUT = in_func,
2492///     OUTPUT = out_func,
2493///     INTERNALLENGTH = VARIABLE  -- Variable length
2494/// );
2495/// ```
2496#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2497#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2498#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2499pub enum UserDefinedTypeInternalLength {
2500    /// Fixed internal length: `INTERNALLENGTH = <number>`
2501    Fixed(u64),
2502    /// Variable internal length: `INTERNALLENGTH = VARIABLE`
2503    Variable,
2504}
2505
2506impl fmt::Display for UserDefinedTypeInternalLength {
2507    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2508        match self {
2509            UserDefinedTypeInternalLength::Fixed(n) => write!(f, "{}", n),
2510            UserDefinedTypeInternalLength::Variable => write!(f, "VARIABLE"),
2511        }
2512    }
2513}
2514
2515/// Alignment specification for PostgreSQL user-defined base types.
2516///
2517/// Specifies the storage alignment requirement for values of the data type.
2518/// The allowed values equate to alignment on 1, 2, 4, or 8 byte boundaries.
2519/// Note that variable-length types must have an alignment of at least 4, since
2520/// they necessarily contain an int4 as their first component.
2521///
2522/// # PostgreSQL Documentation
2523/// See: <https://www.postgresql.org/docs/current/sql-createtype.html>
2524///
2525/// # Examples
2526/// ```sql
2527/// CREATE TYPE mytype (
2528///     INPUT = in_func,
2529///     OUTPUT = out_func,
2530///     ALIGNMENT = int4  -- 4-byte alignment
2531/// );
2532/// ```
2533#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2534#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2535#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2536pub enum Alignment {
2537    /// Single-byte alignment: `ALIGNMENT = char`
2538    Char,
2539    /// 2-byte alignment: `ALIGNMENT = int2`
2540    Int2,
2541    /// 4-byte alignment: `ALIGNMENT = int4`
2542    Int4,
2543    /// 8-byte alignment: `ALIGNMENT = double`
2544    Double,
2545}
2546
2547impl fmt::Display for Alignment {
2548    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2549        match self {
2550            Alignment::Char => write!(f, "char"),
2551            Alignment::Int2 => write!(f, "int2"),
2552            Alignment::Int4 => write!(f, "int4"),
2553            Alignment::Double => write!(f, "double"),
2554        }
2555    }
2556}
2557
2558/// Storage specification for PostgreSQL user-defined base types.
2559///
2560/// Specifies the storage strategy for values of the data type:
2561/// - `plain`: Prevents compression and out-of-line storage (for fixed-length types)
2562/// - `external`: Allows out-of-line storage but not compression
2563/// - `extended`: Allows both compression and out-of-line storage (default for most types)
2564/// - `main`: Allows compression but discourages out-of-line storage
2565///
2566/// # PostgreSQL Documentation
2567/// See: <https://www.postgresql.org/docs/current/sql-createtype.html>
2568///
2569/// # Examples
2570/// ```sql
2571/// CREATE TYPE mytype (
2572///     INPUT = in_func,
2573///     OUTPUT = out_func,
2574///     STORAGE = plain
2575/// );
2576/// ```
2577#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2578#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2579#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2580pub enum UserDefinedTypeStorage {
2581    /// No compression or out-of-line storage: `STORAGE = plain`
2582    Plain,
2583    /// Out-of-line storage allowed, no compression: `STORAGE = external`
2584    External,
2585    /// Both compression and out-of-line storage allowed: `STORAGE = extended`
2586    Extended,
2587    /// Compression allowed, out-of-line discouraged: `STORAGE = main`
2588    Main,
2589}
2590
2591impl fmt::Display for UserDefinedTypeStorage {
2592    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2593        match self {
2594            UserDefinedTypeStorage::Plain => write!(f, "plain"),
2595            UserDefinedTypeStorage::External => write!(f, "external"),
2596            UserDefinedTypeStorage::Extended => write!(f, "extended"),
2597            UserDefinedTypeStorage::Main => write!(f, "main"),
2598        }
2599    }
2600}
2601
2602/// Options for PostgreSQL `CREATE TYPE ... AS RANGE` statement.
2603///
2604/// Range types are data types representing a range of values of some element type
2605/// (called the range's subtype). These options configure the behavior of the range type.
2606///
2607/// # PostgreSQL Documentation
2608/// See: <https://www.postgresql.org/docs/current/sql-createtype.html>
2609///
2610/// # Examples
2611/// ```sql
2612/// CREATE TYPE int4range AS RANGE (
2613///     SUBTYPE = int4,
2614///     SUBTYPE_OPCLASS = int4_ops,
2615///     CANONICAL = int4range_canonical,
2616///     SUBTYPE_DIFF = int4range_subdiff
2617/// );
2618/// ```
2619#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2620#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2621#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2622pub enum UserDefinedTypeRangeOption {
2623    /// The element type that the range type will represent: `SUBTYPE = subtype`
2624    Subtype(DataType),
2625    /// The operator class for the subtype: `SUBTYPE_OPCLASS = subtype_operator_class`
2626    SubtypeOpClass(ObjectName),
2627    /// Collation to use for ordering the subtype: `COLLATION = collation`
2628    Collation(ObjectName),
2629    /// Function to convert range values to canonical form: `CANONICAL = canonical_function`
2630    Canonical(ObjectName),
2631    /// Function to compute the difference between two subtype values: `SUBTYPE_DIFF = subtype_diff_function`
2632    SubtypeDiff(ObjectName),
2633    /// Name of the corresponding multirange type: `MULTIRANGE_TYPE_NAME = multirange_type_name`
2634    MultirangeTypeName(ObjectName),
2635}
2636
2637impl fmt::Display for UserDefinedTypeRangeOption {
2638    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2639        match self {
2640            UserDefinedTypeRangeOption::Subtype(dt) => write!(f, "SUBTYPE = {}", dt),
2641            UserDefinedTypeRangeOption::SubtypeOpClass(name) => {
2642                write!(f, "SUBTYPE_OPCLASS = {}", name)
2643            }
2644            UserDefinedTypeRangeOption::Collation(name) => write!(f, "COLLATION = {}", name),
2645            UserDefinedTypeRangeOption::Canonical(name) => write!(f, "CANONICAL = {}", name),
2646            UserDefinedTypeRangeOption::SubtypeDiff(name) => write!(f, "SUBTYPE_DIFF = {}", name),
2647            UserDefinedTypeRangeOption::MultirangeTypeName(name) => {
2648                write!(f, "MULTIRANGE_TYPE_NAME = {}", name)
2649            }
2650        }
2651    }
2652}
2653
2654/// Options for PostgreSQL `CREATE TYPE ... (<options>)` statement (base type definition).
2655///
2656/// Base types are the lowest-level data types in PostgreSQL. To define a new base type,
2657/// you must specify functions that convert it to and from text representation, and optionally
2658/// binary representation and other properties.
2659///
2660/// Note: This syntax uses parentheses directly after the type name, without the `AS` keyword.
2661///
2662/// # PostgreSQL Documentation
2663/// See: <https://www.postgresql.org/docs/current/sql-createtype.html>
2664///
2665/// # Examples
2666/// ```sql
2667/// CREATE TYPE complex (
2668///     INPUT = complex_in,
2669///     OUTPUT = complex_out,
2670///     INTERNALLENGTH = 16,
2671///     ALIGNMENT = double
2672/// );
2673/// ```
2674#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2675#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2676#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2677pub enum UserDefinedTypeSqlDefinitionOption {
2678    /// Function to convert from external text representation to internal: `INPUT = input_function`
2679    Input(ObjectName),
2680    /// Function to convert from internal to external text representation: `OUTPUT = output_function`
2681    Output(ObjectName),
2682    /// Function to convert from external binary representation to internal: `RECEIVE = receive_function`
2683    Receive(ObjectName),
2684    /// Function to convert from internal to external binary representation: `SEND = send_function`
2685    Send(ObjectName),
2686    /// Function to convert type modifiers from text array to internal form: `TYPMOD_IN = type_modifier_input_function`
2687    TypmodIn(ObjectName),
2688    /// Function to convert type modifiers from internal to text form: `TYPMOD_OUT = type_modifier_output_function`
2689    TypmodOut(ObjectName),
2690    /// Function to compute statistics for the data type: `ANALYZE = analyze_function`
2691    Analyze(ObjectName),
2692    /// Function to handle subscripting operations: `SUBSCRIPT = subscript_function`
2693    Subscript(ObjectName),
2694    /// Internal storage size in bytes, or VARIABLE for variable-length: `INTERNALLENGTH = { internallength | VARIABLE }`
2695    InternalLength(UserDefinedTypeInternalLength),
2696    /// Indicates values are passed by value rather than by reference: `PASSEDBYVALUE`
2697    PassedByValue,
2698    /// Storage alignment requirement (1, 2, 4, or 8 bytes): `ALIGNMENT = alignment`
2699    Alignment(Alignment),
2700    /// Storage strategy for varlena types: `STORAGE = storage`
2701    Storage(UserDefinedTypeStorage),
2702    /// Copy properties from an existing type: `LIKE = like_type`
2703    Like(ObjectName),
2704    /// Type category for implicit casting rules (single char): `CATEGORY = category`
2705    Category(char),
2706    /// Whether this type is preferred within its category: `PREFERRED = preferred`
2707    Preferred(bool),
2708    /// Default value for the type: `DEFAULT = default`
2709    Default(Expr),
2710    /// Element type for array types: `ELEMENT = element`
2711    Element(DataType),
2712    /// Delimiter character for array value display: `DELIMITER = delimiter`
2713    Delimiter(String),
2714    /// Whether the type supports collation: `COLLATABLE = collatable`
2715    Collatable(bool),
2716}
2717
2718impl fmt::Display for UserDefinedTypeSqlDefinitionOption {
2719    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2720        match self {
2721            UserDefinedTypeSqlDefinitionOption::Input(name) => write!(f, "INPUT = {}", name),
2722            UserDefinedTypeSqlDefinitionOption::Output(name) => write!(f, "OUTPUT = {}", name),
2723            UserDefinedTypeSqlDefinitionOption::Receive(name) => write!(f, "RECEIVE = {}", name),
2724            UserDefinedTypeSqlDefinitionOption::Send(name) => write!(f, "SEND = {}", name),
2725            UserDefinedTypeSqlDefinitionOption::TypmodIn(name) => write!(f, "TYPMOD_IN = {}", name),
2726            UserDefinedTypeSqlDefinitionOption::TypmodOut(name) => {
2727                write!(f, "TYPMOD_OUT = {}", name)
2728            }
2729            UserDefinedTypeSqlDefinitionOption::Analyze(name) => write!(f, "ANALYZE = {}", name),
2730            UserDefinedTypeSqlDefinitionOption::Subscript(name) => {
2731                write!(f, "SUBSCRIPT = {}", name)
2732            }
2733            UserDefinedTypeSqlDefinitionOption::InternalLength(len) => {
2734                write!(f, "INTERNALLENGTH = {}", len)
2735            }
2736            UserDefinedTypeSqlDefinitionOption::PassedByValue => write!(f, "PASSEDBYVALUE"),
2737            UserDefinedTypeSqlDefinitionOption::Alignment(align) => {
2738                write!(f, "ALIGNMENT = {}", align)
2739            }
2740            UserDefinedTypeSqlDefinitionOption::Storage(storage) => {
2741                write!(f, "STORAGE = {}", storage)
2742            }
2743            UserDefinedTypeSqlDefinitionOption::Like(name) => write!(f, "LIKE = {}", name),
2744            UserDefinedTypeSqlDefinitionOption::Category(c) => write!(f, "CATEGORY = '{}'", c),
2745            UserDefinedTypeSqlDefinitionOption::Preferred(b) => write!(f, "PREFERRED = {}", b),
2746            UserDefinedTypeSqlDefinitionOption::Default(expr) => write!(f, "DEFAULT = {}", expr),
2747            UserDefinedTypeSqlDefinitionOption::Element(dt) => write!(f, "ELEMENT = {}", dt),
2748            UserDefinedTypeSqlDefinitionOption::Delimiter(s) => {
2749                write!(f, "DELIMITER = '{}'", escape_single_quote_string(s))
2750            }
2751            UserDefinedTypeSqlDefinitionOption::Collatable(b) => write!(f, "COLLATABLE = {}", b),
2752        }
2753    }
2754}
2755
2756/// PARTITION statement used in ALTER TABLE et al. such as in Hive and ClickHouse SQL.
2757/// For example, ClickHouse's OPTIMIZE TABLE supports syntax like PARTITION ID 'partition_id' and PARTITION expr.
2758/// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/optimize)
2759#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2760#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2761#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2762pub enum Partition {
2763    /// ClickHouse supports PARTITION ID 'partition_id' syntax.
2764    Identifier(Ident),
2765    /// ClickHouse supports PARTITION expr syntax.
2766    Expr(Expr),
2767    /// ClickHouse supports PART expr which represents physical partition in disk.
2768    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/partition#attach-partitionpart)
2769    Part(Expr),
2770    /// Hive supports multiple partitions in PARTITION (part1, part2, ...) syntax.
2771    Partitions(Vec<Expr>),
2772}
2773
2774impl fmt::Display for Partition {
2775    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2776        match self {
2777            Partition::Identifier(id) => write!(f, "PARTITION ID {id}"),
2778            Partition::Expr(expr) => write!(f, "PARTITION {expr}"),
2779            Partition::Part(expr) => write!(f, "PART {expr}"),
2780            Partition::Partitions(partitions) => {
2781                write!(f, "PARTITION ({})", display_comma_separated(partitions))
2782            }
2783        }
2784    }
2785}
2786
2787/// DEDUPLICATE statement used in OPTIMIZE TABLE et al. such as in ClickHouse SQL
2788/// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/optimize)
2789#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2790#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2791#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2792pub enum Deduplicate {
2793    /// DEDUPLICATE ALL
2794    All,
2795    /// DEDUPLICATE BY expr
2796    ByExpression(Expr),
2797}
2798
2799impl fmt::Display for Deduplicate {
2800    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2801        match self {
2802            Deduplicate::All => write!(f, "DEDUPLICATE"),
2803            Deduplicate::ByExpression(expr) => write!(f, "DEDUPLICATE BY {expr}"),
2804        }
2805    }
2806}
2807
2808/// Hive supports `CLUSTERED BY` statement in `CREATE TABLE`.
2809/// Syntax: `CLUSTERED BY (col_name, ...) [SORTED BY (col_name [ASC|DESC], ...)] INTO num_buckets BUCKETS`
2810///
2811/// [Hive](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-CreateTable)
2812#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2813#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2814#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2815pub struct ClusteredBy {
2816    /// columns used for clustering
2817    pub columns: Vec<Ident>,
2818    /// optional sorted by expressions
2819    pub sorted_by: Option<Vec<OrderByExpr>>,
2820    /// number of buckets
2821    pub num_buckets: Value,
2822}
2823
2824impl fmt::Display for ClusteredBy {
2825    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2826        write!(
2827            f,
2828            "CLUSTERED BY ({})",
2829            display_comma_separated(&self.columns)
2830        )?;
2831        if let Some(ref sorted_by) = self.sorted_by {
2832            write!(f, " SORTED BY ({})", display_comma_separated(sorted_by))?;
2833        }
2834        write!(f, " INTO {} BUCKETS", self.num_buckets)
2835    }
2836}
2837
2838/// CREATE INDEX statement.
2839#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2840#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2841#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2842pub struct CreateIndex {
2843    /// index name
2844    pub name: Option<ObjectName>,
2845    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2846    /// table name
2847    pub table_name: ObjectName,
2848    /// Index type used in the statement. Can also be found inside [`CreateIndex::index_options`]
2849    /// depending on the position of the option within the statement.
2850    pub using: Option<IndexType>,
2851    /// columns included in the index
2852    pub columns: Vec<IndexColumn>,
2853    /// whether the index is unique
2854    pub unique: bool,
2855    /// whether the index is created concurrently
2856    pub concurrently: bool,
2857    /// whether the index is created asynchronously ([DSQL]).
2858    ///
2859    /// [DSQL]: https://docs.aws.amazon.com/aurora-dsql/latest/userguide/working-with-create-index-async.html
2860    pub r#async: bool,
2861    /// IF NOT EXISTS clause
2862    pub if_not_exists: bool,
2863    /// INCLUDE clause: <https://www.postgresql.org/docs/current/sql-createindex.html>
2864    pub include: Vec<Ident>,
2865    /// NULLS DISTINCT / NOT DISTINCT clause: <https://www.postgresql.org/docs/current/sql-createindex.html>
2866    pub nulls_distinct: Option<bool>,
2867    /// WITH clause: <https://www.postgresql.org/docs/current/sql-createindex.html>
2868    pub with: Vec<Expr>,
2869    /// WHERE clause: <https://www.postgresql.org/docs/current/sql-createindex.html>
2870    pub predicate: Option<Expr>,
2871    /// Index options: <https://www.postgresql.org/docs/current/sql-createindex.html>
2872    pub index_options: Vec<IndexOption>,
2873    /// [MySQL] allows a subset of options normally used for `ALTER TABLE`:
2874    ///
2875    /// - `ALGORITHM`
2876    /// - `LOCK`
2877    ///
2878    /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/create-index.html
2879    pub alter_options: Vec<AlterTableOperation>,
2880}
2881
2882impl fmt::Display for CreateIndex {
2883    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2884        write!(
2885            f,
2886            "CREATE {unique}INDEX {concurrently}{async_}{if_not_exists}",
2887            unique = if self.unique { "UNIQUE " } else { "" },
2888            concurrently = if self.concurrently {
2889                "CONCURRENTLY "
2890            } else {
2891                ""
2892            },
2893            async_ = if self.r#async { "ASYNC " } else { "" },
2894            if_not_exists = if self.if_not_exists {
2895                "IF NOT EXISTS "
2896            } else {
2897                ""
2898            },
2899        )?;
2900        if let Some(value) = &self.name {
2901            write!(f, "{value} ")?;
2902        }
2903        write!(f, "ON {}", self.table_name)?;
2904        if let Some(value) = &self.using {
2905            write!(f, " USING {value} ")?;
2906        }
2907        write!(f, "({})", display_comma_separated(&self.columns))?;
2908        if !self.include.is_empty() {
2909            write!(f, " INCLUDE ({})", display_comma_separated(&self.include))?;
2910        }
2911        if let Some(value) = self.nulls_distinct {
2912            if value {
2913                write!(f, " NULLS DISTINCT")?;
2914            } else {
2915                write!(f, " NULLS NOT DISTINCT")?;
2916            }
2917        }
2918        if !self.with.is_empty() {
2919            write!(f, " WITH ({})", display_comma_separated(&self.with))?;
2920        }
2921        if let Some(predicate) = &self.predicate {
2922            write!(f, " WHERE {predicate}")?;
2923        }
2924        if !self.index_options.is_empty() {
2925            write!(f, " {}", display_separated(&self.index_options, " "))?;
2926        }
2927        if !self.alter_options.is_empty() {
2928            write!(f, " {}", display_separated(&self.alter_options, " "))?;
2929        }
2930        Ok(())
2931    }
2932}
2933
2934/// CREATE TABLE statement.
2935#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2936#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2937#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2938pub struct CreateTable {
2939    /// `OR REPLACE` clause
2940    pub or_replace: bool,
2941    /// `TEMP` or `TEMPORARY` clause
2942    pub temporary: bool,
2943    /// `EXTERNAL` clause
2944    pub external: bool,
2945    /// `DYNAMIC` clause
2946    pub dynamic: bool,
2947    /// `GLOBAL` clause
2948    pub global: Option<bool>,
2949    /// `IF NOT EXISTS` clause
2950    pub if_not_exists: bool,
2951    /// `TRANSIENT` clause
2952    pub transient: bool,
2953    /// `VOLATILE` clause
2954    pub volatile: bool,
2955    /// `ICEBERG` clause
2956    pub iceberg: bool,
2957    /// `SNAPSHOT` clause
2958    /// <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_snapshot_table_statement>
2959    pub snapshot: bool,
2960    /// Table name
2961    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2962    pub name: ObjectName,
2963    /// Column definitions
2964    pub columns: Vec<ColumnDef>,
2965    /// Table constraints
2966    pub constraints: Vec<TableConstraint>,
2967    /// Hive-specific distribution style
2968    pub hive_distribution: HiveDistributionStyle,
2969    /// Hive-specific formats like `ROW FORMAT DELIMITED` or `ROW FORMAT SERDE 'serde_class' WITH SERDEPROPERTIES (...)`
2970    pub hive_formats: Option<HiveFormat>,
2971    /// Table options
2972    pub table_options: CreateTableOptions,
2973    /// General comment for the table
2974    pub file_format: Option<FileFormat>,
2975    /// Location of the table data
2976    pub location: Option<String>,
2977    /// Query used to populate the table
2978    pub query: Option<Box<Query>>,
2979    /// If the table should be created without a rowid (SQLite)
2980    pub without_rowid: bool,
2981    /// `LIKE` clause
2982    pub like: Option<CreateTableLikeKind>,
2983    /// `CLONE` clause
2984    pub clone: Option<ObjectName>,
2985    /// Table version (for systems that support versioned tables)
2986    pub version: Option<TableVersion>,
2987    /// For Hive dialect, the table comment is after the column definitions without `=`,
2988    /// so the `comment` field is optional and different than the comment field in the general options list.
2989    /// [Hive](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-CreateTable)
2990    pub comment: Option<CommentDef>,
2991    /// ClickHouse "ON COMMIT" clause:
2992    /// <https://clickhouse.com/docs/en/sql-reference/statements/create/table/>
2993    pub on_commit: Option<OnCommit>,
2994    /// ClickHouse "ON CLUSTER" clause:
2995    /// <https://clickhouse.com/docs/en/sql-reference/distributed-ddl/>
2996    pub on_cluster: Option<Ident>,
2997    /// ClickHouse "PRIMARY KEY " clause.
2998    /// <https://clickhouse.com/docs/en/sql-reference/statements/create/table/>
2999    pub primary_key: Option<Box<Expr>>,
3000    /// ClickHouse "ORDER BY " clause. Note that omitted ORDER BY is different
3001    /// than empty (represented as ()), the latter meaning "no sorting".
3002    /// <https://clickhouse.com/docs/en/sql-reference/statements/create/table/>
3003    pub order_by: Option<OneOrManyWithParens<Expr>>,
3004    /// BigQuery: A partition expression for the table.
3005    /// <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#partition_expression>
3006    pub partition_by: Option<Box<Expr>>,
3007    /// BigQuery: Table clustering column list.
3008    /// <https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#table_option_list>
3009    /// Snowflake: Table clustering list which contains base column, expressions on base columns.
3010    /// <https://docs.snowflake.com/en/user-guide/tables-clustering-keys#defining-a-clustering-key-for-a-table>
3011    pub cluster_by: Option<WrappedCollection<Vec<Expr>>>,
3012    /// Hive: Table clustering column list.
3013    /// <https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-CreateTable>
3014    pub clustered_by: Option<ClusteredBy>,
3015    /// Postgres `INHERITs` clause, which contains the list of tables from which
3016    /// the new table inherits.
3017    /// <https://www.postgresql.org/docs/current/ddl-inherit.html>
3018    /// <https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-PARMS-INHERITS>
3019    pub inherits: Option<Vec<ObjectName>>,
3020    /// PostgreSQL `PARTITION OF` clause to create a partition of a parent table.
3021    /// Contains the parent table name.
3022    /// <https://www.postgresql.org/docs/current/sql-createtable.html>
3023    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3024    pub partition_of: Option<ObjectName>,
3025    /// PostgreSQL partition bound specification for PARTITION OF.
3026    /// <https://www.postgresql.org/docs/current/sql-createtable.html>
3027    pub for_values: Option<ForValues>,
3028    /// SQLite "STRICT" clause.
3029    /// if the "STRICT" table-option keyword is added to the end, after the closing ")",
3030    /// then strict typing rules apply to that table.
3031    pub strict: bool,
3032    /// Snowflake "COPY GRANTS" clause
3033    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
3034    pub copy_grants: bool,
3035    /// Snowflake "ENABLE_SCHEMA_EVOLUTION" clause
3036    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
3037    pub enable_schema_evolution: Option<bool>,
3038    /// Snowflake "CHANGE_TRACKING" clause
3039    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
3040    pub change_tracking: Option<bool>,
3041    /// Snowflake "DATA_RETENTION_TIME_IN_DAYS" clause
3042    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
3043    pub data_retention_time_in_days: Option<u64>,
3044    /// Snowflake "MAX_DATA_EXTENSION_TIME_IN_DAYS" clause
3045    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
3046    pub max_data_extension_time_in_days: Option<u64>,
3047    /// Snowflake "DEFAULT_DDL_COLLATION" clause
3048    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
3049    pub default_ddl_collation: Option<String>,
3050    /// Snowflake "WITH AGGREGATION POLICY" clause
3051    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
3052    pub with_aggregation_policy: Option<ObjectName>,
3053    /// Snowflake "WITH ROW ACCESS POLICY" clause
3054    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
3055    pub with_row_access_policy: Option<RowAccessPolicy>,
3056    /// Snowflake `WITH STORAGE LIFECYCLE POLICY` clause
3057    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
3058    pub with_storage_lifecycle_policy: Option<StorageLifecyclePolicy>,
3059    /// Snowflake "WITH TAG" clause
3060    /// <https://docs.snowflake.com/en/sql-reference/sql/create-table>
3061    pub with_tags: Option<Vec<Tag>>,
3062    /// Snowflake "EXTERNAL_VOLUME" clause for Iceberg tables
3063    /// <https://docs.snowflake.com/en/sql-reference/sql/create-iceberg-table>
3064    pub external_volume: Option<String>,
3065    /// `WITH CONNECTION` clause.
3066    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_external_table_statement)
3067    pub with_connection: Option<ObjectName>,
3068    /// Snowflake "BASE_LOCATION" clause for Iceberg tables
3069    /// <https://docs.snowflake.com/en/sql-reference/sql/create-iceberg-table>
3070    pub base_location: Option<String>,
3071    /// Snowflake "CATALOG" clause for Iceberg tables
3072    /// <https://docs.snowflake.com/en/sql-reference/sql/create-iceberg-table>
3073    pub catalog: Option<String>,
3074    /// Snowflake "CATALOG_SYNC" clause for Iceberg tables
3075    /// <https://docs.snowflake.com/en/sql-reference/sql/create-iceberg-table>
3076    pub catalog_sync: Option<String>,
3077    /// Snowflake "STORAGE_SERIALIZATION_POLICY" clause for Iceberg tables
3078    /// <https://docs.snowflake.com/en/sql-reference/sql/create-iceberg-table>
3079    pub storage_serialization_policy: Option<StorageSerializationPolicy>,
3080    /// Snowflake "TARGET_LAG" clause for dybamic tables
3081    /// <https://docs.snowflake.com/en/sql-reference/sql/create-dynamic-table>
3082    pub target_lag: Option<String>,
3083    /// Snowflake "WAREHOUSE" clause for dybamic tables
3084    /// <https://docs.snowflake.com/en/sql-reference/sql/create-dynamic-table>
3085    pub warehouse: Option<Ident>,
3086    /// Snowflake "REFRESH_MODE" clause for dybamic tables
3087    /// <https://docs.snowflake.com/en/sql-reference/sql/create-dynamic-table>
3088    pub refresh_mode: Option<RefreshModeKind>,
3089    /// Snowflake "INITIALIZE" clause for dybamic tables
3090    /// <https://docs.snowflake.com/en/sql-reference/sql/create-dynamic-table>
3091    pub initialize: Option<InitializeKind>,
3092    /// Snowflake "REQUIRE USER" clause for dybamic tables
3093    /// <https://docs.snowflake.com/en/sql-reference/sql/create-dynamic-table>
3094    pub require_user: bool,
3095    /// Redshift `DISTSTYLE` option
3096    /// <https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html>
3097    pub diststyle: Option<DistStyle>,
3098    /// Redshift `DISTKEY` option
3099    /// <https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html>
3100    pub distkey: Option<Expr>,
3101    /// Redshift `SORTKEY` option
3102    /// <https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html>
3103    pub sortkey: Option<Vec<Expr>>,
3104    /// Redshift `BACKUP` option: `BACKUP { YES | NO }`
3105    /// <https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html>
3106    pub backup: Option<bool>,
3107    /// `MULTISET | SET` table-kind prefix.
3108    /// `Some(true)` => `MULTISET`, `Some(false)` => `SET`.
3109    ///
3110    /// [Teradata](https://docs.teradata.com/r/Enterprise_IntelliFlex_VMware/SQL-Data-Definition-Language-Syntax-and-Examples/Table-Statements/CREATE-TABLE-and-CREATE-TABLE-AS/Syntax-Elements/MULTISET-or-SET)
3111    pub multiset: Option<bool>,
3112    /// `FALLBACK` clause.
3113    /// `Some(true)` => `FALLBACK`, `Some(false)` => `NO FALLBACK`
3114    ///
3115    /// [Teradata](https://docs.teradata.com/r/Enterprise_IntelliFlex_VMware/SQL-Data-Definition-Language-Syntax-and-Examples/Table-Statements/CREATE-TABLE-and-CREATE-TABLE-AS/Syntax-Elements/FALLBACK-or-NO-FALLBACK)
3116    pub fallback: Option<bool>,
3117    /// `WITH DATA` clause on a `CREATE TABLE ... AS` statement.
3118    ///
3119    /// [Teradata](https://docs.teradata.com/r/Enterprise_IntelliFlex_VMware/SQL-Data-Definition-Language-Syntax-and-Examples/Table-Statements/CREATE-TABLE-and-CREATE-TABLE-AS/Syntax-Elements/AS_clause/WITH-Clause-Phrase)
3120    pub with_data: Option<WithData>,
3121}
3122
3123impl fmt::Display for CreateTable {
3124    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3125        // We want to allow the following options
3126        // Empty column list, allowed by PostgreSQL:
3127        //   `CREATE TABLE t ()`
3128        // No columns provided for CREATE TABLE AS:
3129        //   `CREATE TABLE t AS SELECT a from t2`
3130        // Columns provided for CREATE TABLE AS:
3131        //   `CREATE TABLE t (a INT) AS SELECT a from t2`
3132        write!(
3133            f,
3134            "CREATE {or_replace}{external}{global}{multiset}{temporary}{transient}{volatile}{dynamic}{iceberg}{snapshot}TABLE {if_not_exists}{name}",
3135            or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3136            external = if self.external { "EXTERNAL " } else { "" },
3137            snapshot = if self.snapshot { "SNAPSHOT " } else { "" },
3138            global = self.global
3139                .map(|global| {
3140                    if global {
3141                        "GLOBAL "
3142                    } else {
3143                        "LOCAL "
3144                    }
3145                })
3146                .unwrap_or(""),
3147            if_not_exists = if self.if_not_exists { "IF NOT EXISTS " } else { "" },
3148            multiset = self
3149                .multiset
3150                .map(|m| if m { "MULTISET " } else { "SET " })
3151                .unwrap_or(""),
3152            temporary = if self.temporary { "TEMPORARY " } else { "" },
3153            transient = if self.transient { "TRANSIENT " } else { "" },
3154            volatile = if self.volatile { "VOLATILE " } else { "" },
3155            iceberg = if self.iceberg { "ICEBERG " } else { "" },
3156            dynamic = if self.dynamic { "DYNAMIC " } else { "" },
3157            name = self.name,
3158        )?;
3159        if let Some(fallback) = self.fallback {
3160            write!(f, ", {}", if fallback { "FALLBACK" } else { "NO FALLBACK" })?;
3161        }
3162        if let Some(partition_of) = &self.partition_of {
3163            write!(f, " PARTITION OF {partition_of}")?;
3164        }
3165        if let Some(on_cluster) = &self.on_cluster {
3166            write!(f, " ON CLUSTER {on_cluster}")?;
3167        }
3168        if !self.columns.is_empty() || !self.constraints.is_empty() {
3169            f.write_str(" (")?;
3170            NewLine.fmt(f)?;
3171            Indent(DisplayCommaSeparated(&self.columns)).fmt(f)?;
3172            if !self.columns.is_empty() && !self.constraints.is_empty() {
3173                f.write_str(",")?;
3174                SpaceOrNewline.fmt(f)?;
3175            }
3176            Indent(DisplayCommaSeparated(&self.constraints)).fmt(f)?;
3177            NewLine.fmt(f)?;
3178            f.write_str(")")?;
3179        } else if self.query.is_none()
3180            && self.like.is_none()
3181            && self.clone.is_none()
3182            && self.partition_of.is_none()
3183        {
3184            // PostgreSQL allows `CREATE TABLE t ();`, but requires empty parens
3185            f.write_str(" ()")?;
3186        } else if let Some(CreateTableLikeKind::Parenthesized(like_in_columns_list)) = &self.like {
3187            write!(f, " ({like_in_columns_list})")?;
3188        }
3189        if let Some(for_values) = &self.for_values {
3190            write!(f, " {for_values}")?;
3191        }
3192
3193        // Hive table comment should be after column definitions, please refer to:
3194        // [Hive](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-CreateTable)
3195        if let Some(comment) = &self.comment {
3196            write!(f, " COMMENT '{comment}'")?;
3197        }
3198
3199        // Only for SQLite
3200        if self.without_rowid {
3201            write!(f, " WITHOUT ROWID")?;
3202        }
3203
3204        if let Some(CreateTableLikeKind::Plain(like)) = &self.like {
3205            write!(f, " {like}")?;
3206        }
3207
3208        if let Some(c) = &self.clone {
3209            write!(f, " CLONE {c}")?;
3210        }
3211
3212        if let Some(version) = &self.version {
3213            write!(f, " {version}")?;
3214        }
3215
3216        match &self.hive_distribution {
3217            HiveDistributionStyle::PARTITIONED { columns } => {
3218                write!(f, " PARTITIONED BY ({})", display_comma_separated(columns))?;
3219            }
3220            HiveDistributionStyle::SKEWED {
3221                columns,
3222                on,
3223                stored_as_directories,
3224            } => {
3225                write!(
3226                    f,
3227                    " SKEWED BY ({})) ON ({})",
3228                    display_comma_separated(columns),
3229                    display_comma_separated(on)
3230                )?;
3231                if *stored_as_directories {
3232                    write!(f, " STORED AS DIRECTORIES")?;
3233                }
3234            }
3235            _ => (),
3236        }
3237
3238        if let Some(clustered_by) = &self.clustered_by {
3239            write!(f, " {clustered_by}")?;
3240        }
3241
3242        if let Some(HiveFormat {
3243            row_format,
3244            serde_properties,
3245            storage,
3246            location,
3247        }) = &self.hive_formats
3248        {
3249            match row_format {
3250                Some(HiveRowFormat::SERDE { class }) => write!(f, " ROW FORMAT SERDE '{class}'")?,
3251                Some(HiveRowFormat::DELIMITED { delimiters }) => {
3252                    write!(f, " ROW FORMAT DELIMITED")?;
3253                    if !delimiters.is_empty() {
3254                        write!(f, " {}", display_separated(delimiters, " "))?;
3255                    }
3256                }
3257                None => (),
3258            }
3259            match storage {
3260                Some(HiveIOFormat::IOF {
3261                    input_format,
3262                    output_format,
3263                }) => write!(
3264                    f,
3265                    " STORED AS INPUTFORMAT {input_format} OUTPUTFORMAT {output_format}"
3266                )?,
3267                Some(HiveIOFormat::FileFormat { format }) if !self.external => {
3268                    write!(f, " STORED AS {format}")?
3269                }
3270                Some(HiveIOFormat::Using { format }) => write!(f, " USING {format}")?,
3271                _ => (),
3272            }
3273            if let Some(serde_properties) = serde_properties.as_ref() {
3274                write!(
3275                    f,
3276                    " WITH SERDEPROPERTIES ({})",
3277                    display_comma_separated(serde_properties)
3278                )?;
3279            }
3280            if !self.external {
3281                if let Some(loc) = location {
3282                    write!(f, " LOCATION '{loc}'")?;
3283                }
3284            }
3285        }
3286        if self.external {
3287            if let Some(file_format) = self.file_format {
3288                write!(f, " STORED AS {file_format}")?;
3289            }
3290            if let Some(location) = &self.location {
3291                write!(f, " LOCATION '{location}'")?;
3292            }
3293        }
3294
3295        match &self.table_options {
3296            options @ CreateTableOptions::With(_)
3297            | options @ CreateTableOptions::Plain(_)
3298            | options @ CreateTableOptions::TableProperties(_) => write!(f, " {options}")?,
3299            _ => (),
3300        }
3301
3302        if let Some(primary_key) = &self.primary_key {
3303            write!(f, " PRIMARY KEY {primary_key}")?;
3304        }
3305        if let Some(order_by) = &self.order_by {
3306            write!(f, " ORDER BY {order_by}")?;
3307        }
3308        if let Some(inherits) = &self.inherits {
3309            write!(f, " INHERITS ({})", display_comma_separated(inherits))?;
3310        }
3311        if let Some(partition_by) = self.partition_by.as_ref() {
3312            write!(f, " PARTITION BY {partition_by}")?;
3313        }
3314        if let Some(cluster_by) = self.cluster_by.as_ref() {
3315            write!(f, " CLUSTER BY {cluster_by}")?;
3316        }
3317        if let Some(with_connection) = &self.with_connection {
3318            write!(f, " WITH CONNECTION {with_connection}")?;
3319        }
3320        if let options @ CreateTableOptions::Options(_) = &self.table_options {
3321            write!(f, " {options}")?;
3322        }
3323        if let Some(external_volume) = self.external_volume.as_ref() {
3324            write!(f, " EXTERNAL_VOLUME='{external_volume}'")?;
3325        }
3326
3327        if let Some(catalog) = self.catalog.as_ref() {
3328            write!(f, " CATALOG='{catalog}'")?;
3329        }
3330
3331        if self.iceberg {
3332            if let Some(base_location) = self.base_location.as_ref() {
3333                write!(f, " BASE_LOCATION='{base_location}'")?;
3334            }
3335        }
3336
3337        if let Some(catalog_sync) = self.catalog_sync.as_ref() {
3338            write!(f, " CATALOG_SYNC='{catalog_sync}'")?;
3339        }
3340
3341        if let Some(storage_serialization_policy) = self.storage_serialization_policy.as_ref() {
3342            write!(
3343                f,
3344                " STORAGE_SERIALIZATION_POLICY={storage_serialization_policy}"
3345            )?;
3346        }
3347
3348        if self.copy_grants {
3349            write!(f, " COPY GRANTS")?;
3350        }
3351
3352        if let Some(is_enabled) = self.enable_schema_evolution {
3353            write!(
3354                f,
3355                " ENABLE_SCHEMA_EVOLUTION={}",
3356                if is_enabled { "TRUE" } else { "FALSE" }
3357            )?;
3358        }
3359
3360        if let Some(is_enabled) = self.change_tracking {
3361            write!(
3362                f,
3363                " CHANGE_TRACKING={}",
3364                if is_enabled { "TRUE" } else { "FALSE" }
3365            )?;
3366        }
3367
3368        if let Some(data_retention_time_in_days) = self.data_retention_time_in_days {
3369            write!(
3370                f,
3371                " DATA_RETENTION_TIME_IN_DAYS={data_retention_time_in_days}",
3372            )?;
3373        }
3374
3375        if let Some(max_data_extension_time_in_days) = self.max_data_extension_time_in_days {
3376            write!(
3377                f,
3378                " MAX_DATA_EXTENSION_TIME_IN_DAYS={max_data_extension_time_in_days}",
3379            )?;
3380        }
3381
3382        if let Some(default_ddl_collation) = &self.default_ddl_collation {
3383            write!(f, " DEFAULT_DDL_COLLATION='{default_ddl_collation}'",)?;
3384        }
3385
3386        if let Some(with_aggregation_policy) = &self.with_aggregation_policy {
3387            write!(f, " WITH AGGREGATION POLICY {with_aggregation_policy}",)?;
3388        }
3389
3390        if let Some(row_access_policy) = &self.with_row_access_policy {
3391            write!(f, " {row_access_policy}",)?;
3392        }
3393
3394        if let Some(storage_lifecycle_policy) = &self.with_storage_lifecycle_policy {
3395            write!(f, " {storage_lifecycle_policy}",)?;
3396        }
3397
3398        if let Some(tag) = &self.with_tags {
3399            write!(f, " WITH TAG ({})", display_comma_separated(tag.as_slice()))?;
3400        }
3401
3402        if let Some(target_lag) = &self.target_lag {
3403            write!(f, " TARGET_LAG='{target_lag}'")?;
3404        }
3405
3406        if let Some(warehouse) = &self.warehouse {
3407            write!(f, " WAREHOUSE={warehouse}")?;
3408        }
3409
3410        if let Some(refresh_mode) = &self.refresh_mode {
3411            write!(f, " REFRESH_MODE={refresh_mode}")?;
3412        }
3413
3414        if let Some(initialize) = &self.initialize {
3415            write!(f, " INITIALIZE={initialize}")?;
3416        }
3417
3418        if self.require_user {
3419            write!(f, " REQUIRE USER")?;
3420        }
3421
3422        if self.on_commit.is_some() {
3423            let on_commit = match self.on_commit {
3424                Some(OnCommit::DeleteRows) => "ON COMMIT DELETE ROWS",
3425                Some(OnCommit::PreserveRows) => "ON COMMIT PRESERVE ROWS",
3426                Some(OnCommit::Drop) => "ON COMMIT DROP",
3427                None => "",
3428            };
3429            write!(f, " {on_commit}")?;
3430        }
3431        if self.strict {
3432            write!(f, " STRICT")?;
3433        }
3434        if let Some(backup) = self.backup {
3435            write!(f, " BACKUP {}", if backup { "YES" } else { "NO" })?;
3436        }
3437        if let Some(diststyle) = &self.diststyle {
3438            write!(f, " DISTSTYLE {diststyle}")?;
3439        }
3440        if let Some(distkey) = &self.distkey {
3441            write!(f, " DISTKEY({distkey})")?;
3442        }
3443        if let Some(sortkey) = &self.sortkey {
3444            write!(f, " SORTKEY({})", display_comma_separated(sortkey))?;
3445        }
3446        if let Some(query) = &self.query {
3447            write!(f, " AS {query}")?;
3448        }
3449        if let Some(with_data) = &self.with_data {
3450            write!(f, " {with_data}")?;
3451        }
3452        Ok(())
3453    }
3454}
3455
3456/// `WITH DATA` clause on `CREATE TABLE ... AS` statement.
3457///
3458/// [Teradata](https://docs.teradata.com/r/Enterprise_IntelliFlex_VMware/SQL-Data-Definition-Language-Syntax-and-Examples/Table-Statements/CREATE-TABLE-and-CREATE-TABLE-AS/Syntax-Elements/AS_clause/WITH-Clause-Phrase)
3459#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
3460#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3461#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3462pub struct WithData {
3463    /// `true` for `WITH DATA`, `false` for `WITH NO DATA`.
3464    pub data: bool,
3465    /// `Some(true)` for `AND STATISTICS`, `Some(false)` for `AND NO STATISTICS`,
3466    /// `None` if the `AND [NO] STATISTICS` sub-clause is omitted.
3467    pub statistics: Option<bool>,
3468}
3469
3470impl fmt::Display for WithData {
3471    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3472        f.write_str("WITH ")?;
3473        if !self.data {
3474            f.write_str("NO ")?;
3475        }
3476        f.write_str("DATA")?;
3477        if let Some(stats) = self.statistics {
3478            f.write_str(" AND ")?;
3479            if !stats {
3480                f.write_str("NO ")?;
3481            }
3482            f.write_str("STATISTICS")?;
3483        }
3484        Ok(())
3485    }
3486}
3487
3488/// PostgreSQL partition bound specification for `PARTITION OF`.
3489///
3490/// Specifies partition bounds for a child partition table.
3491///
3492/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtable.html)
3493#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3494#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3495#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3496pub enum ForValues {
3497    /// `FOR VALUES IN (expr, ...)`
3498    In(Vec<Expr>),
3499    /// `FOR VALUES FROM (expr|MINVALUE|MAXVALUE, ...) TO (expr|MINVALUE|MAXVALUE, ...)`
3500    From {
3501        /// The lower bound values for the partition.
3502        from: Vec<PartitionBoundValue>,
3503        /// The upper bound values for the partition.
3504        to: Vec<PartitionBoundValue>,
3505    },
3506    /// `FOR VALUES WITH (MODULUS n, REMAINDER r)`
3507    With {
3508        /// The modulus value for hash partitioning.
3509        modulus: u64,
3510        /// The remainder value for hash partitioning.
3511        remainder: u64,
3512    },
3513    /// `DEFAULT`
3514    Default,
3515}
3516
3517impl fmt::Display for ForValues {
3518    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3519        match self {
3520            ForValues::In(values) => {
3521                write!(f, "FOR VALUES IN ({})", display_comma_separated(values))
3522            }
3523            ForValues::From { from, to } => {
3524                write!(
3525                    f,
3526                    "FOR VALUES FROM ({}) TO ({})",
3527                    display_comma_separated(from),
3528                    display_comma_separated(to)
3529                )
3530            }
3531            ForValues::With { modulus, remainder } => {
3532                write!(
3533                    f,
3534                    "FOR VALUES WITH (MODULUS {modulus}, REMAINDER {remainder})"
3535                )
3536            }
3537            ForValues::Default => write!(f, "DEFAULT"),
3538        }
3539    }
3540}
3541
3542/// A value in a partition bound specification.
3543///
3544/// Used in RANGE partition bounds where values can be expressions,
3545/// MINVALUE (negative infinity), or MAXVALUE (positive infinity).
3546#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3547#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3548#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3549pub enum PartitionBoundValue {
3550    /// An expression representing a partition bound value.
3551    Expr(Expr),
3552    /// Represents negative infinity in partition bounds.
3553    MinValue,
3554    /// Represents positive infinity in partition bounds.
3555    MaxValue,
3556}
3557
3558impl fmt::Display for PartitionBoundValue {
3559    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3560        match self {
3561            PartitionBoundValue::Expr(expr) => write!(f, "{expr}"),
3562            PartitionBoundValue::MinValue => write!(f, "MINVALUE"),
3563            PartitionBoundValue::MaxValue => write!(f, "MAXVALUE"),
3564        }
3565    }
3566}
3567
3568/// Redshift distribution style for `CREATE TABLE`.
3569///
3570/// See [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html)
3571#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3572#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3573#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3574pub enum DistStyle {
3575    /// `DISTSTYLE AUTO`
3576    Auto,
3577    /// `DISTSTYLE EVEN`
3578    Even,
3579    /// `DISTSTYLE KEY`
3580    Key,
3581    /// `DISTSTYLE ALL`
3582    All,
3583}
3584
3585impl fmt::Display for DistStyle {
3586    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3587        match self {
3588            DistStyle::Auto => write!(f, "AUTO"),
3589            DistStyle::Even => write!(f, "EVEN"),
3590            DistStyle::Key => write!(f, "KEY"),
3591            DistStyle::All => write!(f, "ALL"),
3592        }
3593    }
3594}
3595
3596#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3597#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3598#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3599/// ```sql
3600/// CREATE DOMAIN name [ AS ] data_type
3601///         [ COLLATE collation ]
3602///         [ DEFAULT expression ]
3603///         [ domain_constraint [ ... ] ]
3604///
3605///     where domain_constraint is:
3606///
3607///     [ CONSTRAINT constraint_name ]
3608///     { NOT NULL | NULL | CHECK (expression) }
3609/// ```
3610/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createdomain.html)
3611pub struct CreateDomain {
3612    /// The name of the domain to be created.
3613    pub name: ObjectName,
3614    /// The data type of the domain.
3615    pub data_type: DataType,
3616    /// The collation of the domain.
3617    pub collation: Option<Ident>,
3618    /// The default value of the domain.
3619    pub default: Option<Expr>,
3620    /// The constraints of the domain.
3621    pub constraints: Vec<TableConstraint>,
3622}
3623
3624impl fmt::Display for CreateDomain {
3625    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3626        write!(
3627            f,
3628            "CREATE DOMAIN {name} AS {data_type}",
3629            name = self.name,
3630            data_type = self.data_type
3631        )?;
3632        if let Some(collation) = &self.collation {
3633            write!(f, " COLLATE {collation}")?;
3634        }
3635        if let Some(default) = &self.default {
3636            write!(f, " DEFAULT {default}")?;
3637        }
3638        if !self.constraints.is_empty() {
3639            write!(f, " {}", display_separated(&self.constraints, " "))?;
3640        }
3641        Ok(())
3642    }
3643}
3644
3645/// The return type of a `CREATE FUNCTION` statement.
3646#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3647#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3648#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3649pub enum FunctionReturnType {
3650    /// `RETURNS <type>`
3651    DataType(DataType),
3652    /// `RETURNS SETOF <type>`
3653    ///
3654    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
3655    SetOf(DataType),
3656}
3657
3658impl fmt::Display for FunctionReturnType {
3659    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3660        match self {
3661            FunctionReturnType::DataType(data_type) => write!(f, "{data_type}"),
3662            FunctionReturnType::SetOf(data_type) => write!(f, "SETOF {data_type}"),
3663        }
3664    }
3665}
3666
3667#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3668#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3669#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3670/// CREATE FUNCTION statement
3671pub struct CreateFunction {
3672    /// True if this is a `CREATE OR ALTER FUNCTION` statement
3673    ///
3674    /// [MsSql](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-function-transact-sql?view=sql-server-ver16#or-alter)
3675    pub or_alter: bool,
3676    /// True if this is a `CREATE OR REPLACE FUNCTION` statement
3677    pub or_replace: bool,
3678    /// True if this is a `CREATE TEMPORARY FUNCTION` statement
3679    pub temporary: bool,
3680    /// True if this is a `CREATE IF NOT EXISTS FUNCTION` statement
3681    pub if_not_exists: bool,
3682    /// Name of the function to be created.
3683    pub name: ObjectName,
3684    /// List of arguments for the function.
3685    pub args: Option<Vec<OperateFunctionArg>>,
3686    /// The return type of the function.
3687    pub return_type: Option<FunctionReturnType>,
3688    /// The expression that defines the function.
3689    ///
3690    /// Examples:
3691    /// ```sql
3692    /// AS ((SELECT 1))
3693    /// AS "console.log();"
3694    /// ```
3695    pub function_body: Option<CreateFunctionBody>,
3696    /// Behavior attribute for the function
3697    ///
3698    /// IMMUTABLE | STABLE | VOLATILE
3699    ///
3700    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
3701    pub behavior: Option<FunctionBehavior>,
3702    /// CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT
3703    ///
3704    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
3705    pub called_on_null: Option<FunctionCalledOnNull>,
3706    /// PARALLEL { UNSAFE | RESTRICTED | SAFE }
3707    ///
3708    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
3709    pub parallel: Option<FunctionParallel>,
3710    /// SECURITY { DEFINER | INVOKER }
3711    ///
3712    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
3713    pub security: Option<FunctionSecurity>,
3714    /// SET configuration_parameter clauses
3715    ///
3716    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createfunction.html)
3717    pub set_params: Vec<FunctionDefinitionSetParam>,
3718    /// USING ... (Hive only)
3719    pub using: Option<CreateFunctionUsing>,
3720    /// Language used in a UDF definition.
3721    ///
3722    /// Example:
3723    /// ```sql
3724    /// CREATE FUNCTION foo() LANGUAGE js AS "console.log();"
3725    /// ```
3726    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_a_javascript_udf)
3727    pub language: Option<Ident>,
3728    /// Determinism keyword used for non-sql UDF definitions.
3729    ///
3730    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#syntax_11)
3731    pub determinism_specifier: Option<FunctionDeterminismSpecifier>,
3732    /// List of options for creating the function.
3733    ///
3734    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#syntax_11)
3735    pub options: Option<Vec<SqlOption>>,
3736    /// Connection resource for a remote function.
3737    ///
3738    /// Example:
3739    /// ```sql
3740    /// CREATE FUNCTION foo()
3741    /// RETURNS FLOAT64
3742    /// REMOTE WITH CONNECTION us.myconnection
3743    /// ```
3744    /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_a_remote_function)
3745    pub remote_connection: Option<ObjectName>,
3746}
3747
3748impl fmt::Display for CreateFunction {
3749    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3750        write!(
3751            f,
3752            "CREATE {or_alter}{or_replace}{temp}FUNCTION {if_not_exists}{name}",
3753            name = self.name,
3754            temp = if self.temporary { "TEMPORARY " } else { "" },
3755            or_alter = if self.or_alter { "OR ALTER " } else { "" },
3756            or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3757            if_not_exists = if self.if_not_exists {
3758                "IF NOT EXISTS "
3759            } else {
3760                ""
3761            },
3762        )?;
3763        if let Some(args) = &self.args {
3764            write!(f, "({})", display_comma_separated(args))?;
3765        }
3766        if let Some(return_type) = &self.return_type {
3767            write!(f, " RETURNS {return_type}")?;
3768        }
3769        if let Some(determinism_specifier) = &self.determinism_specifier {
3770            write!(f, " {determinism_specifier}")?;
3771        }
3772        if let Some(language) = &self.language {
3773            write!(f, " LANGUAGE {language}")?;
3774        }
3775        if let Some(behavior) = &self.behavior {
3776            write!(f, " {behavior}")?;
3777        }
3778        if let Some(called_on_null) = &self.called_on_null {
3779            write!(f, " {called_on_null}")?;
3780        }
3781        if let Some(parallel) = &self.parallel {
3782            write!(f, " {parallel}")?;
3783        }
3784        if let Some(security) = &self.security {
3785            write!(f, " {security}")?;
3786        }
3787        for set_param in &self.set_params {
3788            write!(f, " {set_param}")?;
3789        }
3790        if let Some(remote_connection) = &self.remote_connection {
3791            write!(f, " REMOTE WITH CONNECTION {remote_connection}")?;
3792        }
3793        if let Some(CreateFunctionBody::AsBeforeOptions { body, link_symbol }) = &self.function_body
3794        {
3795            write!(f, " AS {body}")?;
3796            if let Some(link_symbol) = link_symbol {
3797                write!(f, ", {link_symbol}")?;
3798            }
3799        }
3800        if let Some(CreateFunctionBody::Return(function_body)) = &self.function_body {
3801            write!(f, " RETURN {function_body}")?;
3802        }
3803        if let Some(CreateFunctionBody::AsReturnExpr(function_body)) = &self.function_body {
3804            write!(f, " AS RETURN {function_body}")?;
3805        }
3806        if let Some(CreateFunctionBody::AsReturnSelect(function_body)) = &self.function_body {
3807            write!(f, " AS RETURN {function_body}")?;
3808        }
3809        if let Some(using) = &self.using {
3810            write!(f, " {using}")?;
3811        }
3812        if let Some(options) = &self.options {
3813            write!(
3814                f,
3815                " OPTIONS({})",
3816                display_comma_separated(options.as_slice())
3817            )?;
3818        }
3819        if let Some(CreateFunctionBody::AsAfterOptions(function_body)) = &self.function_body {
3820            write!(f, " AS {function_body}")?;
3821        }
3822        if let Some(CreateFunctionBody::AsBeginEnd(bes)) = &self.function_body {
3823            write!(f, " AS {bes}")?;
3824        }
3825        Ok(())
3826    }
3827}
3828
3829/// ```sql
3830/// CREATE CONNECTOR [IF NOT EXISTS] connector_name
3831/// [TYPE datasource_type]
3832/// [URL datasource_url]
3833/// [COMMENT connector_comment]
3834/// [WITH DCPROPERTIES(property_name=property_value, ...)]
3835/// ```
3836///
3837/// [Hive](https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=27362034#LanguageManualDDL-CreateDataConnectorCreateConnector)
3838#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3839#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3840#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3841pub struct CreateConnector {
3842    /// The name of the connector to be created.
3843    pub name: Ident,
3844    /// Whether `IF NOT EXISTS` was specified.
3845    pub if_not_exists: bool,
3846    /// The type of the connector.
3847    pub connector_type: Option<String>,
3848    /// The URL of the connector.
3849    pub url: Option<String>,
3850    /// The comment for the connector.
3851    pub comment: Option<CommentDef>,
3852    /// The DC properties for the connector.
3853    pub with_dcproperties: Option<Vec<SqlOption>>,
3854}
3855
3856impl fmt::Display for CreateConnector {
3857    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3858        write!(
3859            f,
3860            "CREATE CONNECTOR {if_not_exists}{name}",
3861            if_not_exists = if self.if_not_exists {
3862                "IF NOT EXISTS "
3863            } else {
3864                ""
3865            },
3866            name = self.name,
3867        )?;
3868
3869        if let Some(connector_type) = &self.connector_type {
3870            write!(f, " TYPE '{connector_type}'")?;
3871        }
3872
3873        if let Some(url) = &self.url {
3874            write!(f, " URL '{url}'")?;
3875        }
3876
3877        if let Some(comment) = &self.comment {
3878            write!(f, " COMMENT = '{comment}'")?;
3879        }
3880
3881        if let Some(with_dcproperties) = &self.with_dcproperties {
3882            write!(
3883                f,
3884                " WITH DCPROPERTIES({})",
3885                display_comma_separated(with_dcproperties)
3886            )?;
3887        }
3888
3889        Ok(())
3890    }
3891}
3892
3893/// An `ALTER SCHEMA` (`Statement::AlterSchema`) operation.
3894///
3895/// See [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#alter_schema_collate_statement)
3896/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-alterschema.html)
3897#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3898#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3899#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3900pub enum AlterSchemaOperation {
3901    /// Set the default collation for the schema.
3902    SetDefaultCollate {
3903        /// The collation to set as default.
3904        collate: Expr,
3905    },
3906    /// Add a replica to the schema.
3907    AddReplica {
3908        /// The replica to add.
3909        replica: Ident,
3910        /// Optional options for the replica.
3911        options: Option<Vec<SqlOption>>,
3912    },
3913    /// Drop a replica from the schema.
3914    DropReplica {
3915        /// The replica to drop.
3916        replica: Ident,
3917    },
3918    /// Set options for the schema.
3919    SetOptionsParens {
3920        /// The options to set.
3921        options: Vec<SqlOption>,
3922    },
3923    /// Rename the schema.
3924    Rename {
3925        /// The new name for the schema.
3926        name: ObjectName,
3927    },
3928    /// Change the owner of the schema.
3929    OwnerTo {
3930        /// The new owner of the schema.
3931        owner: Owner,
3932    },
3933}
3934
3935impl fmt::Display for AlterSchemaOperation {
3936    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3937        match self {
3938            AlterSchemaOperation::SetDefaultCollate { collate } => {
3939                write!(f, "SET DEFAULT COLLATE {collate}")
3940            }
3941            AlterSchemaOperation::AddReplica { replica, options } => {
3942                write!(f, "ADD REPLICA {replica}")?;
3943                if let Some(options) = options {
3944                    write!(f, " OPTIONS ({})", display_comma_separated(options))?;
3945                }
3946                Ok(())
3947            }
3948            AlterSchemaOperation::DropReplica { replica } => write!(f, "DROP REPLICA {replica}"),
3949            AlterSchemaOperation::SetOptionsParens { options } => {
3950                write!(f, "SET OPTIONS ({})", display_comma_separated(options))
3951            }
3952            AlterSchemaOperation::Rename { name } => write!(f, "RENAME TO {name}"),
3953            AlterSchemaOperation::OwnerTo { owner } => write!(f, "OWNER TO {owner}"),
3954        }
3955    }
3956}
3957/// `RenameTableNameKind` is the kind used in an `ALTER TABLE _ RENAME` statement.
3958///
3959/// Note: [MySQL] is the only database that supports the AS keyword for this operation.
3960///
3961/// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/alter-table.html
3962#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3963#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3964#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3965pub enum RenameTableNameKind {
3966    /// `AS new_table_name`
3967    As(ObjectName),
3968    /// `TO new_table_name`
3969    To(ObjectName),
3970}
3971
3972impl fmt::Display for RenameTableNameKind {
3973    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3974        match self {
3975            RenameTableNameKind::As(name) => write!(f, "AS {name}"),
3976            RenameTableNameKind::To(name) => write!(f, "TO {name}"),
3977        }
3978    }
3979}
3980
3981#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3982#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3983#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3984/// An `ALTER SCHEMA` (`Statement::AlterSchema`) statement.
3985pub struct AlterSchema {
3986    /// The schema name to alter.
3987    pub name: ObjectName,
3988    /// Whether `IF EXISTS` was specified.
3989    pub if_exists: bool,
3990    /// The list of operations to perform on the schema.
3991    pub operations: Vec<AlterSchemaOperation>,
3992}
3993
3994impl fmt::Display for AlterSchema {
3995    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3996        write!(f, "ALTER SCHEMA ")?;
3997        if self.if_exists {
3998            write!(f, "IF EXISTS ")?;
3999        }
4000        write!(f, "{}", self.name)?;
4001        for operation in &self.operations {
4002            write!(f, " {operation}")?;
4003        }
4004
4005        Ok(())
4006    }
4007}
4008
4009impl Spanned for RenameTableNameKind {
4010    fn span(&self) -> Span {
4011        match self {
4012            RenameTableNameKind::As(name) => name.span(),
4013            RenameTableNameKind::To(name) => name.span(),
4014        }
4015    }
4016}
4017
4018#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
4019#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4020#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4021/// Whether the syntax used for the trigger object (ROW or STATEMENT) is `FOR` or `FOR EACH`.
4022pub enum TriggerObjectKind {
4023    /// The `FOR` syntax is used.
4024    For(TriggerObject),
4025    /// The `FOR EACH` syntax is used.
4026    ForEach(TriggerObject),
4027}
4028
4029impl Display for TriggerObjectKind {
4030    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4031        match self {
4032            TriggerObjectKind::For(obj) => write!(f, "FOR {obj}"),
4033            TriggerObjectKind::ForEach(obj) => write!(f, "FOR EACH {obj}"),
4034        }
4035    }
4036}
4037
4038#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4039#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4040#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4041/// CREATE TRIGGER
4042///
4043/// Examples:
4044///
4045/// ```sql
4046/// CREATE TRIGGER trigger_name
4047/// BEFORE INSERT ON table_name
4048/// FOR EACH ROW
4049/// EXECUTE FUNCTION trigger_function();
4050/// ```
4051///
4052/// Postgres: <https://www.postgresql.org/docs/current/sql-createtrigger.html>
4053/// SQL Server: <https://learn.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql>
4054pub struct CreateTrigger {
4055    /// True if this is a `CREATE OR ALTER TRIGGER` statement
4056    ///
4057    /// [MsSql](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql?view=sql-server-ver16#arguments)
4058    pub or_alter: bool,
4059    /// True if this is a temporary trigger.
4060    ///
4061    /// Examples:
4062    ///
4063    /// ```sql
4064    /// CREATE TEMP TRIGGER trigger_name
4065    /// ```
4066    ///
4067    /// or
4068    ///
4069    /// ```sql
4070    /// CREATE TEMPORARY TRIGGER trigger_name;
4071    /// CREATE TEMP TRIGGER trigger_name;
4072    /// ```
4073    ///
4074    /// [SQLite](https://sqlite.org/lang_createtrigger.html#temp_triggers_on_non_temp_tables)
4075    pub temporary: bool,
4076    /// The `OR REPLACE` clause is used to re-create the trigger if it already exists.
4077    ///
4078    /// Example:
4079    /// ```sql
4080    /// CREATE OR REPLACE TRIGGER trigger_name
4081    /// AFTER INSERT ON table_name
4082    /// FOR EACH ROW
4083    /// EXECUTE FUNCTION trigger_function();
4084    /// ```
4085    pub or_replace: bool,
4086    /// The `CONSTRAINT` keyword is used to create a trigger as a constraint.
4087    pub is_constraint: bool,
4088    /// The name of the trigger to be created.
4089    pub name: ObjectName,
4090    /// Determines whether the function is called before, after, or instead of the event.
4091    ///
4092    /// Example of BEFORE:
4093    ///
4094    /// ```sql
4095    /// CREATE TRIGGER trigger_name
4096    /// BEFORE INSERT ON table_name
4097    /// FOR EACH ROW
4098    /// EXECUTE FUNCTION trigger_function();
4099    /// ```
4100    ///
4101    /// Example of AFTER:
4102    ///
4103    /// ```sql
4104    /// CREATE TRIGGER trigger_name
4105    /// AFTER INSERT ON table_name
4106    /// FOR EACH ROW
4107    /// EXECUTE FUNCTION trigger_function();
4108    /// ```
4109    ///
4110    /// Example of INSTEAD OF:
4111    ///
4112    /// ```sql
4113    /// CREATE TRIGGER trigger_name
4114    /// INSTEAD OF INSERT ON table_name
4115    /// FOR EACH ROW
4116    /// EXECUTE FUNCTION trigger_function();
4117    /// ```
4118    pub period: Option<TriggerPeriod>,
4119    /// Whether the trigger period was specified before the target table name.
4120    /// This does not refer to whether the period is BEFORE, AFTER, or INSTEAD OF,
4121    /// but rather the position of the period clause in relation to the table name.
4122    ///
4123    /// ```sql
4124    /// -- period_before_table == true: Postgres, MySQL, and standard SQL
4125    /// CREATE TRIGGER t BEFORE INSERT ON table_name ...;
4126    /// -- period_before_table == false: MSSQL
4127    /// CREATE TRIGGER t ON table_name BEFORE INSERT ...;
4128    /// ```
4129    pub period_before_table: bool,
4130    /// Multiple events can be specified using OR, such as `INSERT`, `UPDATE`, `DELETE`, or `TRUNCATE`.
4131    pub events: Vec<TriggerEvent>,
4132    /// The table on which the trigger is to be created.
4133    pub table_name: ObjectName,
4134    /// The optional referenced table name that can be referenced via
4135    /// the `FROM` keyword.
4136    pub referenced_table_name: Option<ObjectName>,
4137    /// This keyword immediately precedes the declaration of one or two relation names that provide access to the transition relations of the triggering statement.
4138    pub referencing: Vec<TriggerReferencing>,
4139    /// This specifies whether the trigger function should be fired once for
4140    /// every row affected by the trigger event, or just once per SQL statement.
4141    /// This is optional in some SQL dialects, such as SQLite, and if not specified, in
4142    /// those cases, the implied default is `FOR EACH ROW`.
4143    pub trigger_object: Option<TriggerObjectKind>,
4144    ///  Triggering conditions
4145    pub condition: Option<Expr>,
4146    /// Execute logic block
4147    pub exec_body: Option<TriggerExecBody>,
4148    /// For MSSQL and dialects where statements are preceded by `AS`
4149    pub statements_as: bool,
4150    /// For SQL dialects with statement(s) for a body
4151    pub statements: Option<ConditionalStatements>,
4152    /// The characteristic of the trigger, which include whether the trigger is `DEFERRABLE`, `INITIALLY DEFERRED`, or `INITIALLY IMMEDIATE`,
4153    pub characteristics: Option<ConstraintCharacteristics>,
4154}
4155
4156impl Display for CreateTrigger {
4157    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4158        let CreateTrigger {
4159            or_alter,
4160            temporary,
4161            or_replace,
4162            is_constraint,
4163            name,
4164            period_before_table,
4165            period,
4166            events,
4167            table_name,
4168            referenced_table_name,
4169            referencing,
4170            trigger_object,
4171            condition,
4172            exec_body,
4173            statements_as,
4174            statements,
4175            characteristics,
4176        } = self;
4177        write!(
4178            f,
4179            "CREATE {temporary}{or_alter}{or_replace}{is_constraint}TRIGGER {name} ",
4180            temporary = if *temporary { "TEMPORARY " } else { "" },
4181            or_alter = if *or_alter { "OR ALTER " } else { "" },
4182            or_replace = if *or_replace { "OR REPLACE " } else { "" },
4183            is_constraint = if *is_constraint { "CONSTRAINT " } else { "" },
4184        )?;
4185
4186        if *period_before_table {
4187            if let Some(p) = period {
4188                write!(f, "{p} ")?;
4189            }
4190            if !events.is_empty() {
4191                write!(f, "{} ", display_separated(events, " OR "))?;
4192            }
4193            write!(f, "ON {table_name}")?;
4194        } else {
4195            write!(f, "ON {table_name} ")?;
4196            if let Some(p) = period {
4197                write!(f, "{p}")?;
4198            }
4199            if !events.is_empty() {
4200                write!(f, " {}", display_separated(events, ", "))?;
4201            }
4202        }
4203
4204        if let Some(referenced_table_name) = referenced_table_name {
4205            write!(f, " FROM {referenced_table_name}")?;
4206        }
4207
4208        if let Some(characteristics) = characteristics {
4209            write!(f, " {characteristics}")?;
4210        }
4211
4212        if !referencing.is_empty() {
4213            write!(f, " REFERENCING {}", display_separated(referencing, " "))?;
4214        }
4215
4216        if let Some(trigger_object) = trigger_object {
4217            write!(f, " {trigger_object}")?;
4218        }
4219        if let Some(condition) = condition {
4220            write!(f, " WHEN {condition}")?;
4221        }
4222        if let Some(exec_body) = exec_body {
4223            write!(f, " EXECUTE {exec_body}")?;
4224        }
4225        if let Some(statements) = statements {
4226            if *statements_as {
4227                write!(f, " AS")?;
4228            }
4229            write!(f, " {statements}")?;
4230        }
4231        Ok(())
4232    }
4233}
4234
4235#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4236#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4237#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4238/// DROP TRIGGER
4239///
4240/// ```sql
4241/// DROP TRIGGER [ IF EXISTS ] name ON table_name [ CASCADE | RESTRICT ]
4242/// ```
4243///
4244pub struct DropTrigger {
4245    /// Whether to include the `IF EXISTS` clause.
4246    pub if_exists: bool,
4247    /// The name of the trigger to be dropped.
4248    pub trigger_name: ObjectName,
4249    /// The name of the table from which the trigger is to be dropped.
4250    pub table_name: Option<ObjectName>,
4251    /// `CASCADE` or `RESTRICT`
4252    pub option: Option<ReferentialAction>,
4253}
4254
4255impl fmt::Display for DropTrigger {
4256    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4257        let DropTrigger {
4258            if_exists,
4259            trigger_name,
4260            table_name,
4261            option,
4262        } = self;
4263        write!(f, "DROP TRIGGER")?;
4264        if *if_exists {
4265            write!(f, " IF EXISTS")?;
4266        }
4267        match &table_name {
4268            Some(table_name) => write!(f, " {trigger_name} ON {table_name}")?,
4269            None => write!(f, " {trigger_name}")?,
4270        };
4271        if let Some(option) = option {
4272            write!(f, " {option}")?;
4273        }
4274        Ok(())
4275    }
4276}
4277
4278/// A `TRUNCATE` statement.
4279///
4280/// ```sql
4281/// TRUNCATE TABLE [IF EXISTS] table_names [PARTITION (partitions)] [RESTART IDENTITY | CONTINUE IDENTITY] [CASCADE | RESTRICT] [ON CLUSTER cluster_name]
4282/// ```
4283#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4284#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4285#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4286pub struct Truncate {
4287    /// Table names to truncate
4288    pub table_names: Vec<super::TruncateTableTarget>,
4289    /// Optional partition specification
4290    pub partitions: Option<Vec<Expr>>,
4291    /// TABLE - optional keyword
4292    pub table: bool,
4293    /// Snowflake/Redshift-specific option: [ IF EXISTS ]
4294    pub if_exists: bool,
4295    /// Postgres-specific option: [ RESTART IDENTITY | CONTINUE IDENTITY ]
4296    pub identity: Option<super::TruncateIdentityOption>,
4297    /// Postgres-specific option: [ CASCADE | RESTRICT ]
4298    pub cascade: Option<super::CascadeOption>,
4299    /// ClickHouse-specific option: [ ON CLUSTER cluster_name ]
4300    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/truncate/)
4301    pub on_cluster: Option<Ident>,
4302}
4303
4304impl fmt::Display for Truncate {
4305    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4306        let table = if self.table { "TABLE " } else { "" };
4307        let if_exists = if self.if_exists { "IF EXISTS " } else { "" };
4308
4309        write!(
4310            f,
4311            "TRUNCATE {table}{if_exists}{table_names}",
4312            table_names = display_comma_separated(&self.table_names)
4313        )?;
4314
4315        if let Some(identity) = &self.identity {
4316            match identity {
4317                super::TruncateIdentityOption::Restart => write!(f, " RESTART IDENTITY")?,
4318                super::TruncateIdentityOption::Continue => write!(f, " CONTINUE IDENTITY")?,
4319            }
4320        }
4321        if let Some(cascade) = &self.cascade {
4322            match cascade {
4323                super::CascadeOption::Cascade => write!(f, " CASCADE")?,
4324                super::CascadeOption::Restrict => write!(f, " RESTRICT")?,
4325            }
4326        }
4327
4328        if let Some(ref parts) = &self.partitions {
4329            if !parts.is_empty() {
4330                write!(f, " PARTITION ({})", display_comma_separated(parts))?;
4331            }
4332        }
4333        if let Some(on_cluster) = &self.on_cluster {
4334            write!(f, " ON CLUSTER {on_cluster}")?;
4335        }
4336        Ok(())
4337    }
4338}
4339
4340impl Spanned for Truncate {
4341    fn span(&self) -> Span {
4342        Span::union_iter(
4343            self.table_names.iter().map(|i| i.name.span()).chain(
4344                self.partitions
4345                    .iter()
4346                    .flat_map(|i| i.iter().map(|k| k.span())),
4347            ),
4348        )
4349    }
4350}
4351
4352/// An `MSCK` statement.
4353///
4354/// ```sql
4355/// MSCK [REPAIR] TABLE table_name [ADD|DROP|SYNC PARTITIONS]
4356/// ```
4357/// MSCK (Hive) - MetaStore Check command
4358#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4359#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4360#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4361pub struct Msck {
4362    /// Table name to check
4363    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4364    pub table_name: ObjectName,
4365    /// Whether to repair the table
4366    pub repair: bool,
4367    /// Partition action (ADD, DROP, or SYNC)
4368    pub partition_action: Option<super::AddDropSync>,
4369}
4370
4371impl fmt::Display for Msck {
4372    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4373        write!(
4374            f,
4375            "MSCK {repair}TABLE {table}",
4376            repair = if self.repair { "REPAIR " } else { "" },
4377            table = self.table_name
4378        )?;
4379        if let Some(pa) = &self.partition_action {
4380            write!(f, " {pa}")?;
4381        }
4382        Ok(())
4383    }
4384}
4385
4386impl Spanned for Msck {
4387    fn span(&self) -> Span {
4388        self.table_name.span()
4389    }
4390}
4391
4392/// CREATE VIEW statement.
4393#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4394#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4395#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4396pub struct CreateView {
4397    /// True if this is a `CREATE OR ALTER VIEW` statement
4398    ///
4399    /// [MsSql](https://learn.microsoft.com/en-us/sql/t-sql/statements/create-view-transact-sql)
4400    pub or_alter: bool,
4401    /// The `OR REPLACE` clause is used to re-create the view if it already exists.
4402    pub or_replace: bool,
4403    /// if true, has MATERIALIZED view modifier
4404    pub materialized: bool,
4405    /// Snowflake: SECURE view modifier
4406    /// <https://docs.snowflake.com/en/sql-reference/sql/create-view#syntax>
4407    pub secure: bool,
4408    /// View name
4409    pub name: ObjectName,
4410    /// If `if_not_exists` is true, this flag is set to true if the view name comes before the `IF NOT EXISTS` clause.
4411    /// Example:
4412    /// ```sql
4413    /// CREATE VIEW myview IF NOT EXISTS AS SELECT 1`
4414    ///  ```
4415    /// Otherwise, the flag is set to false if the view name comes after the clause
4416    /// Example:
4417    /// ```sql
4418    /// CREATE VIEW IF NOT EXISTS myview AS SELECT 1`
4419    ///  ```
4420    pub name_before_not_exists: bool,
4421    /// Optional column definitions
4422    pub columns: Vec<ViewColumnDef>,
4423    /// The query that defines the view.
4424    pub query: Box<Query>,
4425    /// Table options (e.g., WITH (..), OPTIONS (...))
4426    pub options: CreateTableOptions,
4427    /// BigQuery: CLUSTER BY columns
4428    pub cluster_by: Vec<Ident>,
4429    /// Snowflake: Views can have comments in Snowflake.
4430    /// <https://docs.snowflake.com/en/sql-reference/sql/create-view#syntax>
4431    pub comment: Option<String>,
4432    /// if true, has RedShift [`WITH NO SCHEMA BINDING`] clause <https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_VIEW.html>
4433    pub with_no_schema_binding: bool,
4434    /// if true, has SQLite `IF NOT EXISTS` clause <https://www.sqlite.org/lang_createview.html>
4435    pub if_not_exists: bool,
4436    /// if true, has SQLite `TEMP` or `TEMPORARY` clause <https://www.sqlite.org/lang_createview.html>
4437    pub temporary: bool,
4438    /// Snowflake: `COPY GRANTS` clause
4439    /// <https://docs.snowflake.com/en/sql-reference/sql/create-view>
4440    pub copy_grants: bool,
4441    /// if not None, has Clickhouse `TO` clause, specify the table into which to insert results
4442    /// <https://clickhouse.com/docs/en/sql-reference/statements/create/view#materialized-view>
4443    pub to: Option<ObjectName>,
4444    /// MySQL: Optional parameters for the view algorithm, definer, and security context
4445    pub params: Option<CreateViewParams>,
4446}
4447
4448impl fmt::Display for CreateView {
4449    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4450        write!(
4451            f,
4452            "CREATE {or_alter}{or_replace}",
4453            or_alter = if self.or_alter { "OR ALTER " } else { "" },
4454            or_replace = if self.or_replace { "OR REPLACE " } else { "" },
4455        )?;
4456        if let Some(ref params) = self.params {
4457            params.fmt(f)?;
4458        }
4459        write!(
4460            f,
4461            "{secure}{materialized}{temporary}VIEW {if_not_and_name}{to}",
4462            if_not_and_name = if self.if_not_exists {
4463                if self.name_before_not_exists {
4464                    format!("{} IF NOT EXISTS", self.name)
4465                } else {
4466                    format!("IF NOT EXISTS {}", self.name)
4467                }
4468            } else {
4469                format!("{}", self.name)
4470            },
4471            secure = if self.secure { "SECURE " } else { "" },
4472            materialized = if self.materialized {
4473                "MATERIALIZED "
4474            } else {
4475                ""
4476            },
4477            temporary = if self.temporary { "TEMPORARY " } else { "" },
4478            to = self
4479                .to
4480                .as_ref()
4481                .map(|to| format!(" TO {to}"))
4482                .unwrap_or_default()
4483        )?;
4484        if self.copy_grants {
4485            write!(f, " COPY GRANTS")?;
4486        }
4487        if !self.columns.is_empty() {
4488            write!(f, " ({})", display_comma_separated(&self.columns))?;
4489        }
4490        if matches!(self.options, CreateTableOptions::With(_)) {
4491            write!(f, " {}", self.options)?;
4492        }
4493        if let Some(ref comment) = self.comment {
4494            write!(f, " COMMENT = '{}'", escape_single_quote_string(comment))?;
4495        }
4496        if !self.cluster_by.is_empty() {
4497            write!(
4498                f,
4499                " CLUSTER BY ({})",
4500                display_comma_separated(&self.cluster_by)
4501            )?;
4502        }
4503        if matches!(self.options, CreateTableOptions::Options(_)) {
4504            write!(f, " {}", self.options)?;
4505        }
4506        f.write_str(" AS")?;
4507        SpaceOrNewline.fmt(f)?;
4508        self.query.fmt(f)?;
4509        if self.with_no_schema_binding {
4510            write!(f, " WITH NO SCHEMA BINDING")?;
4511        }
4512        Ok(())
4513    }
4514}
4515
4516/// CREATE EXTENSION statement
4517/// Note: this is a PostgreSQL-specific statement
4518#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4519#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4520#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4521pub struct CreateExtension {
4522    /// Extension name
4523    pub name: Ident,
4524    /// Whether `IF NOT EXISTS` was specified for the CREATE EXTENSION.
4525    pub if_not_exists: bool,
4526    /// Whether `CASCADE` was specified for the CREATE EXTENSION.
4527    pub cascade: bool,
4528    /// Optional schema name for the extension.
4529    pub schema: Option<Ident>,
4530    /// Optional version for the extension.
4531    pub version: Option<Ident>,
4532}
4533
4534impl fmt::Display for CreateExtension {
4535    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4536        write!(
4537            f,
4538            "CREATE EXTENSION {if_not_exists}{name}",
4539            if_not_exists = if self.if_not_exists {
4540                "IF NOT EXISTS "
4541            } else {
4542                ""
4543            },
4544            name = self.name
4545        )?;
4546        if self.cascade || self.schema.is_some() || self.version.is_some() {
4547            write!(f, " WITH")?;
4548
4549            if let Some(name) = &self.schema {
4550                write!(f, " SCHEMA {name}")?;
4551            }
4552            if let Some(version) = &self.version {
4553                write!(f, " VERSION {version}")?;
4554            }
4555            if self.cascade {
4556                write!(f, " CASCADE")?;
4557            }
4558        }
4559
4560        Ok(())
4561    }
4562}
4563
4564impl Spanned for CreateExtension {
4565    fn span(&self) -> Span {
4566        Span::empty()
4567    }
4568}
4569
4570/// DROP EXTENSION statement
4571/// Note: this is a PostgreSQL-specific statement
4572///
4573/// # References
4574///
4575/// PostgreSQL Documentation:
4576/// <https://www.postgresql.org/docs/current/sql-dropextension.html>
4577#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4578#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4579#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4580pub struct DropExtension {
4581    /// One or more extension names to drop
4582    pub names: Vec<Ident>,
4583    /// Whether `IF EXISTS` was specified for the DROP EXTENSION.
4584    pub if_exists: bool,
4585    /// `CASCADE` or `RESTRICT` behaviour for the drop.
4586    pub cascade_or_restrict: Option<ReferentialAction>,
4587}
4588
4589impl fmt::Display for DropExtension {
4590    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4591        write!(f, "DROP EXTENSION")?;
4592        if self.if_exists {
4593            write!(f, " IF EXISTS")?;
4594        }
4595        write!(f, " {}", display_comma_separated(&self.names))?;
4596        if let Some(cascade_or_restrict) = &self.cascade_or_restrict {
4597            write!(f, " {cascade_or_restrict}")?;
4598        }
4599        Ok(())
4600    }
4601}
4602
4603impl Spanned for DropExtension {
4604    fn span(&self) -> Span {
4605        Span::empty()
4606    }
4607}
4608
4609/// CREATE COLLATION statement.
4610/// Note: this is a PostgreSQL-specific statement.
4611#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4612#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4613#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4614pub struct CreateCollation {
4615    /// Whether `IF NOT EXISTS` was specified.
4616    pub if_not_exists: bool,
4617    /// Name of the collation being created.
4618    pub name: ObjectName,
4619    /// Source definition for the collation.
4620    pub definition: CreateCollationDefinition,
4621}
4622
4623/// Definition forms supported by `CREATE COLLATION`.
4624#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4625#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4626#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4627pub enum CreateCollationDefinition {
4628    /// Create from an existing collation.
4629    ///
4630    /// ```sql
4631    /// CREATE COLLATION name FROM existing_collation
4632    /// ```
4633    From(ObjectName),
4634    /// Create with an option list.
4635    ///
4636    /// ```sql
4637    /// CREATE COLLATION name (key = value, ...)
4638    /// ```
4639    Options(Vec<SqlOption>),
4640}
4641
4642impl fmt::Display for CreateCollation {
4643    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4644        write!(
4645            f,
4646            "CREATE COLLATION {if_not_exists}{name}",
4647            if_not_exists = if self.if_not_exists {
4648                "IF NOT EXISTS "
4649            } else {
4650                ""
4651            },
4652            name = self.name
4653        )?;
4654        match &self.definition {
4655            CreateCollationDefinition::From(existing_collation) => {
4656                write!(f, " FROM {existing_collation}")
4657            }
4658            CreateCollationDefinition::Options(options) => {
4659                write!(f, " ({})", display_comma_separated(options))
4660            }
4661        }
4662    }
4663}
4664
4665impl Spanned for CreateCollation {
4666    fn span(&self) -> Span {
4667        Span::empty()
4668    }
4669}
4670
4671/// ALTER COLLATION statement.
4672/// Note: this is a PostgreSQL-specific statement.
4673#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4674#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4675#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4676pub struct AlterCollation {
4677    /// Name of the collation being altered.
4678    pub name: ObjectName,
4679    /// The operation to perform on the collation.
4680    pub operation: AlterCollationOperation,
4681}
4682
4683/// Operations supported by `ALTER COLLATION`.
4684#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4685#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4686#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4687pub enum AlterCollationOperation {
4688    /// Rename the collation.
4689    ///
4690    /// ```sql
4691    /// ALTER COLLATION name RENAME TO new_name
4692    /// ```
4693    RenameTo {
4694        /// New collation name.
4695        new_name: Ident,
4696    },
4697    /// Change the collation owner.
4698    ///
4699    /// ```sql
4700    /// ALTER COLLATION name OWNER TO role_name
4701    /// ```
4702    OwnerTo(Owner),
4703    /// Move the collation to another schema.
4704    ///
4705    /// ```sql
4706    /// ALTER COLLATION name SET SCHEMA new_schema
4707    /// ```
4708    SetSchema {
4709        /// Target schema name.
4710        schema_name: ObjectName,
4711    },
4712    /// Refresh collation version metadata.
4713    ///
4714    /// ```sql
4715    /// ALTER COLLATION name REFRESH VERSION
4716    /// ```
4717    RefreshVersion,
4718}
4719
4720impl fmt::Display for AlterCollationOperation {
4721    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4722        match self {
4723            AlterCollationOperation::RenameTo { new_name } => write!(f, "RENAME TO {new_name}"),
4724            AlterCollationOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
4725            AlterCollationOperation::SetSchema { schema_name } => {
4726                write!(f, "SET SCHEMA {schema_name}")
4727            }
4728            AlterCollationOperation::RefreshVersion => write!(f, "REFRESH VERSION"),
4729        }
4730    }
4731}
4732
4733impl fmt::Display for AlterCollation {
4734    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4735        write!(f, "ALTER COLLATION {} {}", self.name, self.operation)
4736    }
4737}
4738
4739impl Spanned for AlterCollation {
4740    fn span(&self) -> Span {
4741        Span::empty()
4742    }
4743}
4744
4745/// Table type for ALTER TABLE statements.
4746/// Used to distinguish between regular tables, Iceberg tables, and Dynamic tables.
4747#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4748#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4749#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4750pub enum AlterTableType {
4751    /// Iceberg table type
4752    /// <https://docs.snowflake.com/en/sql-reference/sql/alter-iceberg-table>
4753    Iceberg,
4754    /// Dynamic table type
4755    /// <https://docs.snowflake.com/en/sql-reference/sql/alter-dynamic-table>
4756    Dynamic,
4757    /// External table type
4758    /// <https://docs.snowflake.com/en/sql-reference/sql/alter-external-table>
4759    External,
4760}
4761
4762/// ALTER TABLE statement
4763#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4764#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4765#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4766pub struct AlterTable {
4767    /// Table name
4768    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4769    pub name: ObjectName,
4770    /// Whether the `ASYNC` keyword was specified ([DSQL]). `ALTER TABLE ASYNC`
4771    /// runs the operation as an asynchronous DDL job, e.g.
4772    /// `ALTER TABLE ASYNC t VALIDATE CONSTRAINT c`.
4773    ///
4774    /// [DSQL]: https://docs.aws.amazon.com/aurora-dsql/latest/userguide/working-with-postgresql-compatibility.html
4775    pub r#async: bool,
4776    /// Whether `IF EXISTS` was specified for the `ALTER TABLE`.
4777    pub if_exists: bool,
4778    /// Whether the `ONLY` keyword was used (restrict scope to the named table).
4779    pub only: bool,
4780    /// List of `ALTER TABLE` operations to apply.
4781    pub operations: Vec<AlterTableOperation>,
4782    /// Optional Hive `SET LOCATION` clause for the alter operation.
4783    pub location: Option<HiveSetLocation>,
4784    /// ClickHouse dialect supports `ON CLUSTER` clause for ALTER TABLE
4785    /// For example: `ALTER TABLE table_name ON CLUSTER cluster_name ADD COLUMN c UInt32`
4786    /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/update)
4787    pub on_cluster: Option<Ident>,
4788    /// Table type: None for regular tables, Some(AlterTableType) for Iceberg or Dynamic tables
4789    pub table_type: Option<AlterTableType>,
4790    /// Token that represents the end of the statement (semicolon or EOF)
4791    pub end_token: AttachedToken,
4792}
4793
4794impl fmt::Display for AlterTable {
4795    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4796        match &self.table_type {
4797            Some(AlterTableType::Iceberg) => write!(f, "ALTER ICEBERG TABLE ")?,
4798            Some(AlterTableType::Dynamic) => write!(f, "ALTER DYNAMIC TABLE ")?,
4799            Some(AlterTableType::External) => write!(f, "ALTER EXTERNAL TABLE ")?,
4800            None => write!(f, "ALTER TABLE ")?,
4801        }
4802
4803        if self.r#async {
4804            write!(f, "ASYNC ")?;
4805        }
4806        if self.if_exists {
4807            write!(f, "IF EXISTS ")?;
4808        }
4809        if self.only {
4810            write!(f, "ONLY ")?;
4811        }
4812        write!(f, "{} ", self.name)?;
4813        if let Some(cluster) = &self.on_cluster {
4814            write!(f, "ON CLUSTER {cluster} ")?;
4815        }
4816        write!(f, "{}", display_comma_separated(&self.operations))?;
4817        if let Some(loc) = &self.location {
4818            write!(f, " {loc}")?
4819        }
4820        Ok(())
4821    }
4822}
4823
4824/// DROP FUNCTION statement
4825#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4826#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4827#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4828pub struct DropFunction {
4829    /// Whether to include the `IF EXISTS` clause.
4830    pub if_exists: bool,
4831    /// One or more functions to drop
4832    pub func_desc: Vec<FunctionDesc>,
4833    /// `CASCADE` or `RESTRICT`
4834    pub drop_behavior: Option<DropBehavior>,
4835}
4836
4837impl fmt::Display for DropFunction {
4838    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4839        write!(
4840            f,
4841            "DROP FUNCTION{} {}",
4842            if self.if_exists { " IF EXISTS" } else { "" },
4843            display_comma_separated(&self.func_desc),
4844        )?;
4845        if let Some(op) = &self.drop_behavior {
4846            write!(f, " {op}")?;
4847        }
4848        Ok(())
4849    }
4850}
4851
4852impl Spanned for DropFunction {
4853    fn span(&self) -> Span {
4854        Span::empty()
4855    }
4856}
4857
4858/// CREATE OPERATOR statement
4859/// See <https://www.postgresql.org/docs/current/sql-createoperator.html>
4860#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4861#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4862#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4863pub struct CreateOperator {
4864    /// Operator name (can be schema-qualified)
4865    pub name: ObjectName,
4866    /// FUNCTION or PROCEDURE parameter (function name)
4867    pub function: ObjectName,
4868    /// Whether PROCEDURE keyword was used (vs FUNCTION)
4869    pub is_procedure: bool,
4870    /// LEFTARG parameter (left operand type)
4871    pub left_arg: Option<DataType>,
4872    /// RIGHTARG parameter (right operand type)
4873    pub right_arg: Option<DataType>,
4874    /// Operator options (COMMUTATOR, NEGATOR, RESTRICT, JOIN, HASHES, MERGES)
4875    pub options: Vec<OperatorOption>,
4876}
4877
4878/// CREATE OPERATOR FAMILY statement
4879/// See <https://www.postgresql.org/docs/current/sql-createopfamily.html>
4880#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4881#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4882#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4883pub struct CreateOperatorFamily {
4884    /// Operator family name (can be schema-qualified)
4885    pub name: ObjectName,
4886    /// Index method (btree, hash, gist, gin, etc.)
4887    pub using: Ident,
4888}
4889
4890/// CREATE OPERATOR CLASS statement
4891/// See <https://www.postgresql.org/docs/current/sql-createopclass.html>
4892#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4893#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4894#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4895pub struct CreateOperatorClass {
4896    /// Operator class name (can be schema-qualified)
4897    pub name: ObjectName,
4898    /// Whether this is the default operator class for the type
4899    pub default: bool,
4900    /// The data type
4901    pub for_type: DataType,
4902    /// Index method (btree, hash, gist, gin, etc.)
4903    pub using: Ident,
4904    /// Optional operator family name
4905    pub family: Option<ObjectName>,
4906    /// List of operator class items (operators, functions, storage)
4907    pub items: Vec<OperatorClassItem>,
4908}
4909
4910impl fmt::Display for CreateOperator {
4911    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4912        write!(f, "CREATE OPERATOR {} (", self.name)?;
4913
4914        let function_keyword = if self.is_procedure {
4915            "PROCEDURE"
4916        } else {
4917            "FUNCTION"
4918        };
4919        let mut params = vec![format!("{} = {}", function_keyword, self.function)];
4920
4921        if let Some(left_arg) = &self.left_arg {
4922            params.push(format!("LEFTARG = {}", left_arg));
4923        }
4924        if let Some(right_arg) = &self.right_arg {
4925            params.push(format!("RIGHTARG = {}", right_arg));
4926        }
4927
4928        for option in &self.options {
4929            params.push(option.to_string());
4930        }
4931
4932        write!(f, "{}", params.join(", "))?;
4933        write!(f, ")")
4934    }
4935}
4936
4937impl fmt::Display for CreateOperatorFamily {
4938    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4939        write!(
4940            f,
4941            "CREATE OPERATOR FAMILY {} USING {}",
4942            self.name, self.using
4943        )
4944    }
4945}
4946
4947impl fmt::Display for CreateOperatorClass {
4948    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4949        write!(f, "CREATE OPERATOR CLASS {}", self.name)?;
4950        if self.default {
4951            write!(f, " DEFAULT")?;
4952        }
4953        write!(f, " FOR TYPE {} USING {}", self.for_type, self.using)?;
4954        if let Some(family) = &self.family {
4955            write!(f, " FAMILY {}", family)?;
4956        }
4957        write!(f, " AS {}", display_comma_separated(&self.items))
4958    }
4959}
4960
4961/// Operator argument types for CREATE OPERATOR CLASS
4962#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4963#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4964#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4965pub struct OperatorArgTypes {
4966    /// Left-hand operand data type for the operator.
4967    pub left: DataType,
4968    /// Right-hand operand data type for the operator.
4969    pub right: DataType,
4970}
4971
4972impl fmt::Display for OperatorArgTypes {
4973    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4974        write!(f, "{}, {}", self.left, self.right)
4975    }
4976}
4977
4978/// An item in a CREATE OPERATOR CLASS statement
4979#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4980#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4981#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4982pub enum OperatorClassItem {
4983    /// `OPERATOR` clause describing a specific operator implementation.
4984    Operator {
4985        /// Strategy number identifying the operator position in the opclass.
4986        strategy_number: u64,
4987        /// The operator name referenced by this clause.
4988        operator_name: ObjectName,
4989        /// Optional operator argument types.
4990        op_types: Option<OperatorArgTypes>,
4991        /// Optional purpose such as `FOR SEARCH` or `FOR ORDER BY`.
4992        purpose: Option<OperatorPurpose>,
4993    },
4994    /// `FUNCTION` clause describing a support function for the operator class.
4995    Function {
4996        /// Support function number for this entry.
4997        support_number: u64,
4998        /// Optional function argument types for the operator class.
4999        op_types: Option<Vec<DataType>>,
5000        /// The function name implementing the support function.
5001        function_name: ObjectName,
5002        /// Function argument types for the support function.
5003        argument_types: Vec<DataType>,
5004    },
5005    /// `STORAGE` clause specifying the storage type.
5006    Storage {
5007        /// The storage data type.
5008        storage_type: DataType,
5009    },
5010}
5011
5012/// Purpose of an operator in an operator class
5013#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5014#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5015#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5016pub enum OperatorPurpose {
5017    /// Purpose: used for index/search operations.
5018    ForSearch,
5019    /// Purpose: used for ORDER BY; optionally includes a sort family name.
5020    ForOrderBy {
5021        /// Optional sort family object name.
5022        sort_family: ObjectName,
5023    },
5024}
5025
5026impl fmt::Display for OperatorClassItem {
5027    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5028        match self {
5029            OperatorClassItem::Operator {
5030                strategy_number,
5031                operator_name,
5032                op_types,
5033                purpose,
5034            } => {
5035                write!(f, "OPERATOR {strategy_number} {operator_name}")?;
5036                if let Some(types) = op_types {
5037                    write!(f, " ({types})")?;
5038                }
5039                if let Some(purpose) = purpose {
5040                    write!(f, " {purpose}")?;
5041                }
5042                Ok(())
5043            }
5044            OperatorClassItem::Function {
5045                support_number,
5046                op_types,
5047                function_name,
5048                argument_types,
5049            } => {
5050                write!(f, "FUNCTION {support_number}")?;
5051                if let Some(types) = op_types {
5052                    write!(f, " ({})", display_comma_separated(types))?;
5053                }
5054                write!(f, " {function_name}")?;
5055                if !argument_types.is_empty() {
5056                    write!(f, "({})", display_comma_separated(argument_types))?;
5057                }
5058                Ok(())
5059            }
5060            OperatorClassItem::Storage { storage_type } => {
5061                write!(f, "STORAGE {storage_type}")
5062            }
5063        }
5064    }
5065}
5066
5067impl fmt::Display for OperatorPurpose {
5068    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5069        match self {
5070            OperatorPurpose::ForSearch => write!(f, "FOR SEARCH"),
5071            OperatorPurpose::ForOrderBy { sort_family } => {
5072                write!(f, "FOR ORDER BY {sort_family}")
5073            }
5074        }
5075    }
5076}
5077
5078/// `DROP OPERATOR` statement
5079/// See <https://www.postgresql.org/docs/current/sql-dropoperator.html>
5080#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5081#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5082#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5083pub struct DropOperator {
5084    /// `IF EXISTS` clause
5085    pub if_exists: bool,
5086    /// One or more operators to drop with their signatures
5087    pub operators: Vec<DropOperatorSignature>,
5088    /// `CASCADE or RESTRICT`
5089    pub drop_behavior: Option<DropBehavior>,
5090}
5091
5092/// Operator signature for a `DROP OPERATOR` statement
5093#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5094#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5095#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5096pub struct DropOperatorSignature {
5097    /// Operator name
5098    pub name: ObjectName,
5099    /// Left operand type
5100    pub left_type: Option<DataType>,
5101    /// Right operand type
5102    pub right_type: DataType,
5103}
5104
5105impl fmt::Display for DropOperatorSignature {
5106    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5107        write!(f, "{} (", self.name)?;
5108        if let Some(left_type) = &self.left_type {
5109            write!(f, "{}", left_type)?;
5110        } else {
5111            write!(f, "NONE")?;
5112        }
5113        write!(f, ", {})", self.right_type)
5114    }
5115}
5116
5117impl fmt::Display for DropOperator {
5118    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5119        write!(f, "DROP OPERATOR")?;
5120        if self.if_exists {
5121            write!(f, " IF EXISTS")?;
5122        }
5123        write!(f, " {}", display_comma_separated(&self.operators))?;
5124        if let Some(drop_behavior) = &self.drop_behavior {
5125            write!(f, " {}", drop_behavior)?;
5126        }
5127        Ok(())
5128    }
5129}
5130
5131impl Spanned for DropOperator {
5132    fn span(&self) -> Span {
5133        Span::empty()
5134    }
5135}
5136
5137/// `DROP OPERATOR FAMILY` statement
5138/// See <https://www.postgresql.org/docs/current/sql-dropopfamily.html>
5139#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5140#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5141#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5142pub struct DropOperatorFamily {
5143    /// `IF EXISTS` clause
5144    pub if_exists: bool,
5145    /// One or more operator families to drop
5146    pub names: Vec<ObjectName>,
5147    /// Index method (btree, hash, gist, gin, etc.)
5148    pub using: Ident,
5149    /// `CASCADE or RESTRICT`
5150    pub drop_behavior: Option<DropBehavior>,
5151}
5152
5153impl fmt::Display for DropOperatorFamily {
5154    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5155        write!(f, "DROP OPERATOR FAMILY")?;
5156        if self.if_exists {
5157            write!(f, " IF EXISTS")?;
5158        }
5159        write!(f, " {}", display_comma_separated(&self.names))?;
5160        write!(f, " USING {}", self.using)?;
5161        if let Some(drop_behavior) = &self.drop_behavior {
5162            write!(f, " {}", drop_behavior)?;
5163        }
5164        Ok(())
5165    }
5166}
5167
5168impl Spanned for DropOperatorFamily {
5169    fn span(&self) -> Span {
5170        Span::empty()
5171    }
5172}
5173
5174/// `DROP OPERATOR CLASS` statement
5175/// See <https://www.postgresql.org/docs/current/sql-dropopclass.html>
5176#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5177#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5178#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5179pub struct DropOperatorClass {
5180    /// `IF EXISTS` clause
5181    pub if_exists: bool,
5182    /// One or more operator classes to drop
5183    pub names: Vec<ObjectName>,
5184    /// Index method (btree, hash, gist, gin, etc.)
5185    pub using: Ident,
5186    /// `CASCADE or RESTRICT`
5187    pub drop_behavior: Option<DropBehavior>,
5188}
5189
5190impl fmt::Display for DropOperatorClass {
5191    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5192        write!(f, "DROP OPERATOR CLASS")?;
5193        if self.if_exists {
5194            write!(f, " IF EXISTS")?;
5195        }
5196        write!(f, " {}", display_comma_separated(&self.names))?;
5197        write!(f, " USING {}", self.using)?;
5198        if let Some(drop_behavior) = &self.drop_behavior {
5199            write!(f, " {}", drop_behavior)?;
5200        }
5201        Ok(())
5202    }
5203}
5204
5205impl Spanned for DropOperatorClass {
5206    fn span(&self) -> Span {
5207        Span::empty()
5208    }
5209}
5210
5211/// An item in an ALTER OPERATOR FAMILY ADD statement
5212#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5213#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5214#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5215pub enum OperatorFamilyItem {
5216    /// `OPERATOR` clause in an operator family modification.
5217    Operator {
5218        /// Strategy number for the operator.
5219        strategy_number: u64,
5220        /// Operator name referenced by this entry.
5221        operator_name: ObjectName,
5222        /// Operator argument types.
5223        op_types: Vec<DataType>,
5224        /// Optional purpose such as `FOR SEARCH` or `FOR ORDER BY`.
5225        purpose: Option<OperatorPurpose>,
5226    },
5227    /// `FUNCTION` clause in an operator family modification.
5228    Function {
5229        /// Support function number.
5230        support_number: u64,
5231        /// Optional operator argument types for the function.
5232        op_types: Option<Vec<DataType>>,
5233        /// Function name for the support function.
5234        function_name: ObjectName,
5235        /// Function argument types.
5236        argument_types: Vec<DataType>,
5237    },
5238}
5239
5240/// An item in an ALTER OPERATOR FAMILY DROP statement
5241#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5242#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5243#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5244pub enum OperatorFamilyDropItem {
5245    /// `OPERATOR` clause for DROP within an operator family.
5246    Operator {
5247        /// Strategy number for the operator.
5248        strategy_number: u64,
5249        /// Operator argument types.
5250        op_types: Vec<DataType>,
5251    },
5252    /// `FUNCTION` clause for DROP within an operator family.
5253    Function {
5254        /// Support function number.
5255        support_number: u64,
5256        /// Operator argument types for the function.
5257        op_types: Vec<DataType>,
5258    },
5259}
5260
5261impl fmt::Display for OperatorFamilyItem {
5262    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5263        match self {
5264            OperatorFamilyItem::Operator {
5265                strategy_number,
5266                operator_name,
5267                op_types,
5268                purpose,
5269            } => {
5270                write!(
5271                    f,
5272                    "OPERATOR {strategy_number} {operator_name} ({})",
5273                    display_comma_separated(op_types)
5274                )?;
5275                if let Some(purpose) = purpose {
5276                    write!(f, " {purpose}")?;
5277                }
5278                Ok(())
5279            }
5280            OperatorFamilyItem::Function {
5281                support_number,
5282                op_types,
5283                function_name,
5284                argument_types,
5285            } => {
5286                write!(f, "FUNCTION {support_number}")?;
5287                if let Some(types) = op_types {
5288                    write!(f, " ({})", display_comma_separated(types))?;
5289                }
5290                write!(f, " {function_name}")?;
5291                if !argument_types.is_empty() {
5292                    write!(f, "({})", display_comma_separated(argument_types))?;
5293                }
5294                Ok(())
5295            }
5296        }
5297    }
5298}
5299
5300impl fmt::Display for OperatorFamilyDropItem {
5301    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5302        match self {
5303            OperatorFamilyDropItem::Operator {
5304                strategy_number,
5305                op_types,
5306            } => {
5307                write!(
5308                    f,
5309                    "OPERATOR {strategy_number} ({})",
5310                    display_comma_separated(op_types)
5311                )
5312            }
5313            OperatorFamilyDropItem::Function {
5314                support_number,
5315                op_types,
5316            } => {
5317                write!(
5318                    f,
5319                    "FUNCTION {support_number} ({})",
5320                    display_comma_separated(op_types)
5321                )
5322            }
5323        }
5324    }
5325}
5326
5327/// `ALTER OPERATOR FAMILY` statement
5328/// See <https://www.postgresql.org/docs/current/sql-alteropfamily.html>
5329#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5330#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5331#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5332pub struct AlterOperatorFamily {
5333    /// Operator family name (can be schema-qualified)
5334    pub name: ObjectName,
5335    /// Index method (btree, hash, gist, gin, etc.)
5336    pub using: Ident,
5337    /// The operation to perform
5338    pub operation: AlterOperatorFamilyOperation,
5339}
5340
5341/// An [AlterOperatorFamily] operation
5342#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5343#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5344#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5345pub enum AlterOperatorFamilyOperation {
5346    /// `ADD { OPERATOR ... | FUNCTION ... } [, ...]`
5347    Add {
5348        /// List of operator family items to add
5349        items: Vec<OperatorFamilyItem>,
5350    },
5351    /// `DROP { OPERATOR ... | FUNCTION ... } [, ...]`
5352    Drop {
5353        /// List of operator family items to drop
5354        items: Vec<OperatorFamilyDropItem>,
5355    },
5356    /// `RENAME TO new_name`
5357    RenameTo {
5358        /// The new name for the operator family.
5359        new_name: ObjectName,
5360    },
5361    /// `OWNER TO { new_owner | CURRENT_ROLE | CURRENT_USER | SESSION_USER }`
5362    OwnerTo(Owner),
5363    /// `SET SCHEMA new_schema`
5364    SetSchema {
5365        /// The target schema name.
5366        schema_name: ObjectName,
5367    },
5368}
5369
5370impl fmt::Display for AlterOperatorFamily {
5371    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5372        write!(
5373            f,
5374            "ALTER OPERATOR FAMILY {} USING {}",
5375            self.name, self.using
5376        )?;
5377        write!(f, " {}", self.operation)
5378    }
5379}
5380
5381impl fmt::Display for AlterOperatorFamilyOperation {
5382    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5383        match self {
5384            AlterOperatorFamilyOperation::Add { items } => {
5385                write!(f, "ADD {}", display_comma_separated(items))
5386            }
5387            AlterOperatorFamilyOperation::Drop { items } => {
5388                write!(f, "DROP {}", display_comma_separated(items))
5389            }
5390            AlterOperatorFamilyOperation::RenameTo { new_name } => {
5391                write!(f, "RENAME TO {new_name}")
5392            }
5393            AlterOperatorFamilyOperation::OwnerTo(owner) => {
5394                write!(f, "OWNER TO {owner}")
5395            }
5396            AlterOperatorFamilyOperation::SetSchema { schema_name } => {
5397                write!(f, "SET SCHEMA {schema_name}")
5398            }
5399        }
5400    }
5401}
5402
5403impl Spanned for AlterOperatorFamily {
5404    fn span(&self) -> Span {
5405        Span::empty()
5406    }
5407}
5408
5409/// `ALTER OPERATOR CLASS` statement
5410/// See <https://www.postgresql.org/docs/current/sql-alteropclass.html>
5411#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5412#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5413#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5414pub struct AlterOperatorClass {
5415    /// Operator class name (can be schema-qualified)
5416    pub name: ObjectName,
5417    /// Index method (btree, hash, gist, gin, etc.)
5418    pub using: Ident,
5419    /// The operation to perform
5420    pub operation: AlterOperatorClassOperation,
5421}
5422
5423/// An [AlterOperatorClass] operation
5424#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5425#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5426#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5427pub enum AlterOperatorClassOperation {
5428    /// `RENAME TO new_name`
5429    /// Rename the operator class to a new name.
5430    RenameTo {
5431        /// The new name for the operator class.
5432        new_name: ObjectName,
5433    },
5434    /// `OWNER TO { new_owner | CURRENT_ROLE | CURRENT_USER | SESSION_USER }`
5435    OwnerTo(Owner),
5436    /// `SET SCHEMA new_schema`
5437    /// Set the schema for the operator class.
5438    SetSchema {
5439        /// The target schema name.
5440        schema_name: ObjectName,
5441    },
5442}
5443
5444impl fmt::Display for AlterOperatorClass {
5445    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5446        write!(f, "ALTER OPERATOR CLASS {} USING {}", self.name, self.using)?;
5447        write!(f, " {}", self.operation)
5448    }
5449}
5450
5451impl fmt::Display for AlterOperatorClassOperation {
5452    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5453        match self {
5454            AlterOperatorClassOperation::RenameTo { new_name } => {
5455                write!(f, "RENAME TO {new_name}")
5456            }
5457            AlterOperatorClassOperation::OwnerTo(owner) => {
5458                write!(f, "OWNER TO {owner}")
5459            }
5460            AlterOperatorClassOperation::SetSchema { schema_name } => {
5461                write!(f, "SET SCHEMA {schema_name}")
5462            }
5463        }
5464    }
5465}
5466
5467impl Spanned for AlterOperatorClass {
5468    fn span(&self) -> Span {
5469        Span::empty()
5470    }
5471}
5472
5473/// `ALTER FUNCTION` / `ALTER AGGREGATE` statement.
5474#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5475#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5476#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5477pub struct AlterFunction {
5478    /// Object type being altered.
5479    pub kind: AlterFunctionKind,
5480    /// Function or aggregate signature.
5481    pub function: FunctionDesc,
5482    /// `ORDER BY` argument list for aggregate signatures.
5483    ///
5484    /// This is only used for `ALTER AGGREGATE`.
5485    pub aggregate_order_by: Option<Vec<OperateFunctionArg>>,
5486    /// Whether the aggregate signature uses `*`.
5487    ///
5488    /// This is only used for `ALTER AGGREGATE`.
5489    pub aggregate_star: bool,
5490    /// Operation applied to the object.
5491    pub operation: AlterFunctionOperation,
5492}
5493
5494/// Function-like object type used by [`AlterFunction`].
5495#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5496#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5497#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5498pub enum AlterFunctionKind {
5499    /// `FUNCTION`
5500    Function,
5501    /// `AGGREGATE`
5502    Aggregate,
5503}
5504
5505impl fmt::Display for AlterFunctionKind {
5506    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5507        match self {
5508            Self::Function => write!(f, "FUNCTION"),
5509            Self::Aggregate => write!(f, "AGGREGATE"),
5510        }
5511    }
5512}
5513
5514/// Operation for `ALTER FUNCTION` / `ALTER AGGREGATE`.
5515#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5516#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5517#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5518pub enum AlterFunctionOperation {
5519    /// `RENAME TO new_name`
5520    RenameTo {
5521        /// New unqualified function or aggregate name.
5522        new_name: Ident,
5523    },
5524    /// `OWNER TO { new_owner | CURRENT_ROLE | CURRENT_USER | SESSION_USER }`
5525    OwnerTo(Owner),
5526    /// `SET SCHEMA schema_name`
5527    SetSchema {
5528        /// The target schema name.
5529        schema_name: ObjectName,
5530    },
5531    /// `[ NO ] DEPENDS ON EXTENSION extension_name`
5532    DependsOnExtension {
5533        /// `true` when `NO DEPENDS ON EXTENSION`.
5534        no: bool,
5535        /// Extension name.
5536        extension_name: ObjectName,
5537    },
5538    /// `action [ ... ] [ RESTRICT ]` (function only).
5539    Actions {
5540        /// One or more function actions.
5541        actions: Vec<AlterFunctionAction>,
5542        /// Whether `RESTRICT` is present.
5543        restrict: bool,
5544    },
5545}
5546
5547/// Function action in `ALTER FUNCTION ... action [ ... ] [ RESTRICT ]`.
5548#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5549#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5550#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5551pub enum AlterFunctionAction {
5552    /// `CALLED ON NULL INPUT` / `RETURNS NULL ON NULL INPUT` / `STRICT`
5553    CalledOnNull(FunctionCalledOnNull),
5554    /// `IMMUTABLE` / `STABLE` / `VOLATILE`
5555    Behavior(FunctionBehavior),
5556    /// `[ NOT ] LEAKPROOF`
5557    Leakproof(bool),
5558    /// `[ EXTERNAL ] SECURITY { DEFINER | INVOKER }`
5559    Security {
5560        /// Whether the optional `EXTERNAL` keyword was present.
5561        external: bool,
5562        /// Security mode.
5563        security: FunctionSecurity,
5564    },
5565    /// `PARALLEL { UNSAFE | RESTRICTED | SAFE }`
5566    Parallel(FunctionParallel),
5567    /// `COST execution_cost`
5568    Cost(Expr),
5569    /// `ROWS result_rows`
5570    Rows(Expr),
5571    /// `SUPPORT support_function`
5572    Support(ObjectName),
5573    /// `SET configuration_parameter { TO | = } { value | DEFAULT }`
5574    /// or `SET configuration_parameter FROM CURRENT`
5575    Set(FunctionDefinitionSetParam),
5576    /// `RESET configuration_parameter` or `RESET ALL`
5577    Reset(ResetConfig),
5578}
5579
5580impl fmt::Display for AlterFunction {
5581    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5582        write!(f, "ALTER {} ", self.kind)?;
5583        match self.kind {
5584            AlterFunctionKind::Function => {
5585                write!(f, "{} ", self.function)?;
5586            }
5587            AlterFunctionKind::Aggregate => {
5588                write!(f, "{}(", self.function.name)?;
5589                if self.aggregate_star {
5590                    write!(f, "*")?;
5591                } else {
5592                    if let Some(args) = &self.function.args {
5593                        write!(f, "{}", display_comma_separated(args))?;
5594                    }
5595                    if let Some(order_by_args) = &self.aggregate_order_by {
5596                        if self
5597                            .function
5598                            .args
5599                            .as_ref()
5600                            .is_some_and(|args| !args.is_empty())
5601                        {
5602                            write!(f, " ")?;
5603                        }
5604                        write!(f, "ORDER BY {}", display_comma_separated(order_by_args))?;
5605                    }
5606                }
5607                write!(f, ") ")?;
5608            }
5609        }
5610        write!(f, "{}", self.operation)
5611    }
5612}
5613
5614impl fmt::Display for AlterFunctionOperation {
5615    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5616        match self {
5617            AlterFunctionOperation::RenameTo { new_name } => {
5618                write!(f, "RENAME TO {new_name}")
5619            }
5620            AlterFunctionOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
5621            AlterFunctionOperation::SetSchema { schema_name } => {
5622                write!(f, "SET SCHEMA {schema_name}")
5623            }
5624            AlterFunctionOperation::DependsOnExtension { no, extension_name } => {
5625                if *no {
5626                    write!(f, "NO DEPENDS ON EXTENSION {extension_name}")
5627                } else {
5628                    write!(f, "DEPENDS ON EXTENSION {extension_name}")
5629                }
5630            }
5631            AlterFunctionOperation::Actions { actions, restrict } => {
5632                write!(f, "{}", display_separated(actions, " "))?;
5633                if *restrict {
5634                    write!(f, " RESTRICT")?;
5635                }
5636                Ok(())
5637            }
5638        }
5639    }
5640}
5641
5642impl fmt::Display for AlterFunctionAction {
5643    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5644        match self {
5645            AlterFunctionAction::CalledOnNull(called_on_null) => write!(f, "{called_on_null}"),
5646            AlterFunctionAction::Behavior(behavior) => write!(f, "{behavior}"),
5647            AlterFunctionAction::Leakproof(leakproof) => {
5648                if *leakproof {
5649                    write!(f, "LEAKPROOF")
5650                } else {
5651                    write!(f, "NOT LEAKPROOF")
5652                }
5653            }
5654            AlterFunctionAction::Security { external, security } => {
5655                if *external {
5656                    write!(f, "EXTERNAL ")?;
5657                }
5658                write!(f, "{security}")
5659            }
5660            AlterFunctionAction::Parallel(parallel) => write!(f, "{parallel}"),
5661            AlterFunctionAction::Cost(execution_cost) => write!(f, "COST {execution_cost}"),
5662            AlterFunctionAction::Rows(result_rows) => write!(f, "ROWS {result_rows}"),
5663            AlterFunctionAction::Support(support_function) => {
5664                write!(f, "SUPPORT {support_function}")
5665            }
5666            AlterFunctionAction::Set(set_param) => write!(f, "{set_param}"),
5667            AlterFunctionAction::Reset(reset_config) => match reset_config {
5668                ResetConfig::ALL => write!(f, "RESET ALL"),
5669                ResetConfig::ConfigName(name) => write!(f, "RESET {name}"),
5670            },
5671        }
5672    }
5673}
5674
5675impl Spanned for AlterFunction {
5676    fn span(&self) -> Span {
5677        Span::empty()
5678    }
5679}
5680
5681/// CREATE POLICY statement.
5682///
5683/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-createpolicy.html)
5684#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5685#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5686#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5687pub struct CreatePolicy {
5688    /// Name of the policy.
5689    pub name: Ident,
5690    /// Table the policy is defined on.
5691    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5692    pub table_name: ObjectName,
5693    /// Optional policy type (e.g., `PERMISSIVE` / `RESTRICTIVE`).
5694    pub policy_type: Option<CreatePolicyType>,
5695    /// Optional command the policy applies to (e.g., `SELECT`).
5696    pub command: Option<CreatePolicyCommand>,
5697    /// Optional list of grantee owners.
5698    pub to: Option<Vec<Owner>>,
5699    /// Optional expression for the `USING` clause.
5700    pub using: Option<Expr>,
5701    /// Optional expression for the `WITH CHECK` clause.
5702    pub with_check: Option<Expr>,
5703}
5704
5705impl fmt::Display for CreatePolicy {
5706    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5707        write!(
5708            f,
5709            "CREATE POLICY {name} ON {table_name}",
5710            name = self.name,
5711            table_name = self.table_name,
5712        )?;
5713        if let Some(ref policy_type) = self.policy_type {
5714            write!(f, " AS {policy_type}")?;
5715        }
5716        if let Some(ref command) = self.command {
5717            write!(f, " FOR {command}")?;
5718        }
5719        if let Some(ref to) = self.to {
5720            write!(f, " TO {}", display_comma_separated(to))?;
5721        }
5722        if let Some(ref using) = self.using {
5723            write!(f, " USING ({using})")?;
5724        }
5725        if let Some(ref with_check) = self.with_check {
5726            write!(f, " WITH CHECK ({with_check})")?;
5727        }
5728        Ok(())
5729    }
5730}
5731
5732/// Policy type for a `CREATE POLICY` statement.
5733/// ```sql
5734/// AS [ PERMISSIVE | RESTRICTIVE ]
5735/// ```
5736/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createpolicy.html)
5737#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5738#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5739#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5740pub enum CreatePolicyType {
5741    /// Policy allows operations unless explicitly denied.
5742    Permissive,
5743    /// Policy denies operations unless explicitly allowed.
5744    Restrictive,
5745}
5746
5747impl fmt::Display for CreatePolicyType {
5748    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5749        match self {
5750            CreatePolicyType::Permissive => write!(f, "PERMISSIVE"),
5751            CreatePolicyType::Restrictive => write!(f, "RESTRICTIVE"),
5752        }
5753    }
5754}
5755
5756/// Command that a policy can apply to (FOR clause).
5757/// ```sql
5758/// FOR [ALL | SELECT | INSERT | UPDATE | DELETE]
5759/// ```
5760/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createpolicy.html)
5761#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5762#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5763#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5764pub enum CreatePolicyCommand {
5765    /// Applies to all commands.
5766    All,
5767    /// Applies to SELECT.
5768    Select,
5769    /// Applies to INSERT.
5770    Insert,
5771    /// Applies to UPDATE.
5772    Update,
5773    /// Applies to DELETE.
5774    Delete,
5775}
5776
5777impl fmt::Display for CreatePolicyCommand {
5778    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5779        match self {
5780            CreatePolicyCommand::All => write!(f, "ALL"),
5781            CreatePolicyCommand::Select => write!(f, "SELECT"),
5782            CreatePolicyCommand::Insert => write!(f, "INSERT"),
5783            CreatePolicyCommand::Update => write!(f, "UPDATE"),
5784            CreatePolicyCommand::Delete => write!(f, "DELETE"),
5785        }
5786    }
5787}
5788
5789/// DROP POLICY statement.
5790///
5791/// See [PostgreSQL](https://www.postgresql.org/docs/current/sql-droppolicy.html)
5792#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5793#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5794#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5795pub struct DropPolicy {
5796    /// `true` when `IF EXISTS` was present.
5797    pub if_exists: bool,
5798    /// Name of the policy to drop.
5799    pub name: Ident,
5800    /// Name of the table the policy applies to.
5801    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5802    pub table_name: ObjectName,
5803    /// Optional drop behavior (`CASCADE` or `RESTRICT`).
5804    pub drop_behavior: Option<DropBehavior>,
5805}
5806
5807impl fmt::Display for DropPolicy {
5808    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5809        write!(
5810            f,
5811            "DROP POLICY {if_exists}{name} ON {table_name}",
5812            if_exists = if self.if_exists { "IF EXISTS " } else { "" },
5813            name = self.name,
5814            table_name = self.table_name
5815        )?;
5816        if let Some(ref behavior) = self.drop_behavior {
5817            write!(f, " {behavior}")?;
5818        }
5819        Ok(())
5820    }
5821}
5822
5823impl From<CreatePolicy> for crate::ast::Statement {
5824    fn from(v: CreatePolicy) -> Self {
5825        crate::ast::Statement::CreatePolicy(v)
5826    }
5827}
5828
5829impl From<DropPolicy> for crate::ast::Statement {
5830    fn from(v: DropPolicy) -> Self {
5831        crate::ast::Statement::DropPolicy(v)
5832    }
5833}
5834
5835/// ALTER POLICY statement.
5836///
5837/// ```sql
5838/// ALTER POLICY <NAME> ON <TABLE NAME> [<OPERATION>]
5839/// ```
5840/// (Postgresql-specific)
5841#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5842#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5843#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5844pub struct AlterPolicy {
5845    /// Policy name to alter.
5846    pub name: Ident,
5847    /// Target table name the policy is defined on.
5848    #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5849    pub table_name: ObjectName,
5850    /// Optional operation specific to the policy alteration.
5851    pub operation: AlterPolicyOperation,
5852}
5853
5854impl fmt::Display for AlterPolicy {
5855    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5856        write!(
5857            f,
5858            "ALTER POLICY {name} ON {table_name}{operation}",
5859            name = self.name,
5860            table_name = self.table_name,
5861            operation = self.operation
5862        )
5863    }
5864}
5865
5866impl From<AlterPolicy> for crate::ast::Statement {
5867    fn from(v: AlterPolicy) -> Self {
5868        crate::ast::Statement::AlterPolicy(v)
5869    }
5870}