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