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