Skip to main content

risingwave_sqlparser/ast/
ddl.rs

1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5//     http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12
13//! AST types specific to CREATE/ALTER variants of [`crate::ast::Statement`]
14//! (commonly referred to as Data Definition Language, or DDL)
15
16use std::fmt;
17
18use super::{ConfigParam, FormatEncodeOptions, SqlOption};
19use crate::ast::{
20    DataType, Expr, Ident, ObjectName, Query, SecretRefValue, SetVariableValue, Value,
21    display_comma_separated, display_separated,
22};
23use crate::tokenizer::Token;
24
25#[derive(Debug, Clone, PartialEq, Eq, Hash)]
26pub enum AlterDatabaseOperation {
27    ChangeOwner {
28        new_owner_name: Ident,
29    },
30    RenameDatabase {
31        database_name: ObjectName,
32    },
33    SetParam(ConfigParam),
34    /// `SET RESOURCE_GROUP TO 'RESOURCE GROUP' [ DEFERRED ]`
35    /// `RESET RESOURCE_GROUP [ DEFERRED ]`
36    SetResourceGroup {
37        resource_group: Option<SetVariableValue>,
38        deferred: bool,
39    },
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, Hash)]
43pub enum AlterSchemaOperation {
44    ChangeOwner { new_owner_name: Ident },
45    RenameSchema { schema_name: ObjectName },
46    SwapRenameSchema { target_schema: ObjectName },
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
50pub enum AlterRateLimitType {
51    Source,
52    Backfill,
53    Dml,
54    Sink,
55}
56
57impl AlterRateLimitType {
58    pub fn as_str(self) -> &'static str {
59        match self {
60            AlterRateLimitType::Source => "SOURCE_RATE_LIMIT",
61            AlterRateLimitType::Backfill => "BACKFILL_RATE_LIMIT",
62            AlterRateLimitType::Dml => "DML_RATE_LIMIT",
63            AlterRateLimitType::Sink => "SINK_RATE_LIMIT",
64        }
65    }
66}
67
68impl fmt::Display for AlterRateLimitType {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        f.write_str(self.as_str())
71    }
72}
73
74#[derive(Debug, Clone, PartialEq, Eq, Hash)]
75pub struct AlterRateLimit {
76    pub rate_limit_type: AlterRateLimitType,
77    pub rate_limit: i32,
78}
79
80impl fmt::Display for AlterRateLimit {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        write!(f, "SET {} TO {}", self.rate_limit_type, self.rate_limit)
83    }
84}
85
86/// An `ALTER TABLE` (`Statement::AlterTable`) operation
87#[derive(Debug, Clone, PartialEq, Eq, Hash)]
88pub enum AlterTableOperation {
89    /// `ADD <table_constraint>`
90    AddConstraint(TableConstraint),
91    /// `ADD [ COLUMN ] <column_def>`
92    AddColumn {
93        column_def: ColumnDef,
94    },
95    /// TODO: implement `DROP CONSTRAINT <name>`
96    DropConstraint {
97        name: Ident,
98    },
99    /// `DROP [ COLUMN ] [ IF EXISTS ] <column_name> [ CASCADE ]`
100    DropColumn {
101        column_name: Ident,
102        if_exists: bool,
103        cascade: bool,
104    },
105    /// `RENAME [ COLUMN ] <old_column_name> TO <new_column_name>`
106    RenameColumn {
107        old_column_name: Ident,
108        new_column_name: Ident,
109    },
110    /// `RENAME TO <table_name>`
111    RenameTable {
112        table_name: ObjectName,
113    },
114    // CHANGE [ COLUMN ] <old_name> <new_name> <data_type> [ <options> ]
115    ChangeColumn {
116        old_name: Ident,
117        new_name: Ident,
118        data_type: DataType,
119        options: Vec<ColumnOption>,
120    },
121    /// `RENAME CONSTRAINT <old_constraint_name> TO <new_constraint_name>`
122    ///
123    /// Note: this is a PostgreSQL-specific operation.
124    RenameConstraint {
125        old_name: Ident,
126        new_name: Ident,
127    },
128    /// `ALTER [ COLUMN ]`
129    AlterColumn {
130        column_name: Ident,
131        op: AlterColumnOperation,
132    },
133    /// `ALTER WATERMARK FOR <column> AS <expr> [WITH TTL]`
134    AlterWatermark {
135        column_name: Ident,
136        expr: Expr,
137        with_ttl: bool,
138    },
139    /// `OWNER TO <owner_name>`
140    ChangeOwner {
141        new_owner_name: Ident,
142    },
143    /// `SET SCHEMA <schema_name>`
144    SetSchema {
145        new_schema_name: ObjectName,
146    },
147    /// `SET PARALLELISM TO <parallelism> [ DEFERRED ]`
148    SetParallelism {
149        parallelism: SetVariableValue,
150        deferred: bool,
151    },
152    /// `SET BACKFILL_PARALLELISM TO <parallelism> [ DEFERRED ]`
153    SetBackfillParallelism {
154        parallelism: SetVariableValue,
155        deferred: bool,
156    },
157    /// `SET CONFIG (key = value, ...)`
158    SetConfig {
159        entries: Vec<SqlOption>,
160    },
161    /// `RESET CONFIG (key, ...)`
162    ResetConfig {
163        keys: Vec<ObjectName>,
164    },
165    RefreshSchema,
166    AlterRateLimit(AlterRateLimit),
167    /// `SWAP WITH <table_name>`
168    SwapRenameTable {
169        target_table: ObjectName,
170    },
171    /// `DROP CONNECTOR`
172    DropConnector,
173
174    /// `ALTER CONNECTOR WITH (<connector_props>)`
175    AlterConnectorProps {
176        alter_props: Vec<SqlOption>,
177    },
178}
179
180#[derive(Debug, Clone, PartialEq, Eq, Hash)]
181pub enum AlterIndexOperation {
182    RenameIndex {
183        index_name: ObjectName,
184    },
185    /// `SET PARALLELISM TO <parallelism> [ DEFERRED ]`
186    SetParallelism {
187        parallelism: SetVariableValue,
188        deferred: bool,
189    },
190    /// `SET BACKFILL_PARALLELISM TO <parallelism> [ DEFERRED ]`
191    SetBackfillParallelism {
192        parallelism: SetVariableValue,
193        deferred: bool,
194    },
195    /// `SET RESOURCE_GROUP TO 'RESOURCE GROUP' [ DEFERRED ]`
196    /// `RESET RESOURCE_GROUP [ DEFERRED ]`
197    SetResourceGroup {
198        resource_group: Option<SetVariableValue>,
199        deferred: bool,
200    },
201    /// `SET CONFIG (key = value, ...)`
202    SetConfig {
203        entries: Vec<SqlOption>,
204    },
205    /// `RESET CONFIG (key, ...)`
206    ResetConfig {
207        keys: Vec<ObjectName>,
208    },
209}
210
211#[derive(Debug, Clone, PartialEq, Eq, Hash)]
212pub enum AlterViewOperation {
213    RenameView {
214        view_name: ObjectName,
215    },
216    ChangeOwner {
217        new_owner_name: Ident,
218    },
219    SetSchema {
220        new_schema_name: ObjectName,
221    },
222    /// `SET PARALLELISM TO <parallelism> [ DEFERRED ]`
223    SetParallelism {
224        parallelism: SetVariableValue,
225        deferred: bool,
226    },
227    /// `SET BACKFILL_PARALLELISM TO <parallelism> [ DEFERRED ]`
228    SetBackfillParallelism {
229        parallelism: SetVariableValue,
230        deferred: bool,
231    },
232    /// `SET RESOURCE_GROUP TO 'RESOURCE GROUP' [ DEFERRED ]`
233    /// `RESET RESOURCE_GROUP [ DEFERRED ]`
234    SetResourceGroup {
235        resource_group: Option<SetVariableValue>,
236        deferred: bool,
237    },
238    AlterRateLimit(AlterRateLimit),
239    /// `SWAP WITH <view_name>`
240    SwapRenameView {
241        target_view: ObjectName,
242    },
243    SetStreamingEnableUnalignedJoin {
244        enable: bool,
245    },
246    /// `AS <query>`
247    AsQuery {
248        query: Box<Query>,
249    },
250    /// `SET CONFIG ( streaming.some_config_key = <some_config_value>, .. )`
251    SetConfig {
252        entries: Vec<SqlOption>,
253    },
254    /// `RESET CONFIG ( streaming.some_config_key, .. )`
255    ResetConfig {
256        keys: Vec<ObjectName>,
257    },
258}
259
260#[derive(Debug, Clone, PartialEq, Eq, Hash)]
261pub enum AlterSinkOperation {
262    RenameSink {
263        sink_name: ObjectName,
264    },
265    ChangeOwner {
266        new_owner_name: Ident,
267    },
268    SetSchema {
269        new_schema_name: ObjectName,
270    },
271    /// `SET PARALLELISM TO <parallelism> [ DEFERRED ]`
272    SetParallelism {
273        parallelism: SetVariableValue,
274        deferred: bool,
275    },
276    /// `SET BACKFILL_PARALLELISM TO <parallelism> [ DEFERRED ]`
277    SetBackfillParallelism {
278        parallelism: SetVariableValue,
279        deferred: bool,
280    },
281    /// `SET RESOURCE_GROUP TO 'RESOURCE GROUP' [ DEFERRED ]`
282    /// `RESET RESOURCE_GROUP [ DEFERRED ]`
283    SetResourceGroup {
284        resource_group: Option<SetVariableValue>,
285        deferred: bool,
286    },
287    /// `SET CONFIG (key = value, ...)`
288    SetConfig {
289        entries: Vec<SqlOption>,
290    },
291    /// `RESET CONFIG (key, ...)`
292    ResetConfig {
293        keys: Vec<ObjectName>,
294    },
295    /// `SWAP WITH <sink_name>`
296    SwapRenameSink {
297        target_sink: ObjectName,
298    },
299    AlterRateLimit(AlterRateLimit),
300    AlterConnectorProps {
301        alter_props: Vec<SqlOption>,
302    },
303    SetStreamingEnableUnalignedJoin {
304        enable: bool,
305    },
306}
307
308#[derive(Debug, Clone, PartialEq, Eq, Hash)]
309pub enum AlterSubscriptionOperation {
310    RenameSubscription { subscription_name: ObjectName },
311    ChangeOwner { new_owner_name: Ident },
312    SetSchema { new_schema_name: ObjectName },
313    SetRetention { retention: Value },
314    SwapRenameSubscription { target_subscription: ObjectName },
315}
316
317#[derive(Debug, Clone, PartialEq, Eq, Hash)]
318pub enum AlterSourceOperation {
319    RenameSource {
320        source_name: ObjectName,
321    },
322    AddColumn {
323        column_def: ColumnDef,
324    },
325    ChangeOwner {
326        new_owner_name: Ident,
327    },
328    SetSchema {
329        new_schema_name: ObjectName,
330    },
331    FormatEncode {
332        format_encode: FormatEncodeOptions,
333    },
334    RefreshSchema,
335    AlterRateLimit(AlterRateLimit),
336    SwapRenameSource {
337        target_source: ObjectName,
338    },
339    /// `SET PARALLELISM TO <parallelism> [ DEFERRED ]`
340    SetParallelism {
341        parallelism: SetVariableValue,
342        deferred: bool,
343    },
344    /// `SET BACKFILL_PARALLELISM TO <parallelism> [ DEFERRED ]`
345    SetBackfillParallelism {
346        parallelism: SetVariableValue,
347        deferred: bool,
348    },
349    /// `SET CONFIG (key = value, ...)`
350    SetConfig {
351        entries: Vec<SqlOption>,
352    },
353    /// `RESET CONFIG (key, ...)`
354    ResetConfig {
355        keys: Vec<ObjectName>,
356    },
357    /// `RESET` - Reset CDC source offset to latest
358    ResetSource,
359    AlterConnectorProps {
360        alter_props: Vec<SqlOption>,
361    },
362}
363
364#[derive(Debug, Clone, PartialEq, Eq, Hash)]
365pub enum AlterFunctionOperation {
366    SetSchema { new_schema_name: ObjectName },
367    ChangeOwner { new_owner_name: Ident },
368}
369
370#[derive(Debug, Clone, PartialEq, Eq, Hash)]
371pub enum AlterConnectionOperation {
372    SetSchema { new_schema_name: ObjectName },
373    ChangeOwner { new_owner_name: Ident },
374    AlterConnectorProps { alter_props: Vec<SqlOption> },
375}
376
377#[derive(Debug, Clone, PartialEq, Eq, Hash)]
378pub enum AlterSecretOperation {
379    ChangeCredential {
380        with_options: Vec<SqlOption>,
381        new_credential: Value,
382    },
383    ChangeOwner {
384        new_owner_name: Ident,
385    },
386}
387
388#[derive(Debug, Clone, PartialEq, Eq, Hash)]
389pub enum AlterFragmentOperation {
390    AlterRateLimit(AlterRateLimit),
391    SetParallelism { parallelism: SetVariableValue },
392}
393
394#[derive(Debug, Clone, PartialEq, Eq, Hash)]
395pub enum AlterCompactionGroupOperation {
396    Set { configs: Vec<ConfigParam> },
397}
398
399impl fmt::Display for AlterDatabaseOperation {
400    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
401        match self {
402            AlterDatabaseOperation::ChangeOwner { new_owner_name } => {
403                write!(f, "OWNER TO {}", new_owner_name)
404            }
405            AlterDatabaseOperation::RenameDatabase { database_name } => {
406                write!(f, "RENAME TO {}", database_name)
407            }
408            AlterDatabaseOperation::SetParam(ConfigParam { param, value }) => {
409                write!(f, "SET {} TO {}", param, value)
410            }
411            AlterDatabaseOperation::SetResourceGroup {
412                resource_group,
413                deferred,
414            } => {
415                let deferred = if *deferred { " DEFERRED" } else { "" };
416
417                if let Some(resource_group) = resource_group {
418                    write!(f, "SET RESOURCE_GROUP TO {}{}", resource_group, deferred)
419                } else {
420                    write!(f, "RESET RESOURCE_GROUP{}", deferred)
421                }
422            }
423        }
424    }
425}
426
427impl fmt::Display for AlterSchemaOperation {
428    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
429        match self {
430            AlterSchemaOperation::ChangeOwner { new_owner_name } => {
431                write!(f, "OWNER TO {}", new_owner_name)
432            }
433            AlterSchemaOperation::RenameSchema { schema_name } => {
434                write!(f, "RENAME TO {}", schema_name)
435            }
436            AlterSchemaOperation::SwapRenameSchema { target_schema } => {
437                write!(f, "SWAP WITH {}", target_schema)
438            }
439        }
440    }
441}
442
443impl fmt::Display for AlterTableOperation {
444    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445        match self {
446            AlterTableOperation::AddConstraint(c) => write!(f, "ADD {}", c),
447            AlterTableOperation::AddColumn { column_def } => {
448                write!(f, "ADD COLUMN {}", column_def)
449            }
450            AlterTableOperation::AlterColumn { column_name, op } => {
451                write!(f, "ALTER COLUMN {} {}", column_name, op)
452            }
453            AlterTableOperation::AlterWatermark {
454                column_name,
455                expr,
456                with_ttl,
457            } => {
458                write!(f, "ALTER WATERMARK FOR {} AS {}", column_name, expr)?;
459                if *with_ttl {
460                    write!(f, " WITH TTL")?;
461                }
462                Ok(())
463            }
464            AlterTableOperation::DropConstraint { name } => write!(f, "DROP CONSTRAINT {}", name),
465            AlterTableOperation::DropColumn {
466                column_name,
467                if_exists,
468                cascade,
469            } => write!(
470                f,
471                "DROP COLUMN {}{}{}",
472                if *if_exists { "IF EXISTS " } else { "" },
473                column_name,
474                if *cascade { " CASCADE" } else { "" }
475            ),
476            AlterTableOperation::RenameColumn {
477                old_column_name,
478                new_column_name,
479            } => write!(
480                f,
481                "RENAME COLUMN {} TO {}",
482                old_column_name, new_column_name
483            ),
484            AlterTableOperation::RenameTable { table_name } => {
485                write!(f, "RENAME TO {}", table_name)
486            }
487            AlterTableOperation::ChangeColumn {
488                old_name,
489                new_name,
490                data_type,
491                options,
492            } => {
493                write!(f, "CHANGE COLUMN {} {} {}", old_name, new_name, data_type)?;
494                if options.is_empty() {
495                    Ok(())
496                } else {
497                    write!(f, " {}", display_separated(options, " "))
498                }
499            }
500            AlterTableOperation::RenameConstraint { old_name, new_name } => {
501                write!(f, "RENAME CONSTRAINT {} TO {}", old_name, new_name)
502            }
503            AlterTableOperation::ChangeOwner { new_owner_name } => {
504                write!(f, "OWNER TO {}", new_owner_name)
505            }
506            AlterTableOperation::SetSchema { new_schema_name } => {
507                write!(f, "SET SCHEMA {}", new_schema_name)
508            }
509            AlterTableOperation::SetParallelism {
510                parallelism,
511                deferred,
512            } => {
513                write!(
514                    f,
515                    "SET PARALLELISM TO {}{}",
516                    parallelism,
517                    if *deferred { " DEFERRED" } else { "" }
518                )
519            }
520            AlterTableOperation::SetBackfillParallelism {
521                parallelism,
522                deferred,
523            } => {
524                write!(
525                    f,
526                    "SET BACKFILL_PARALLELISM TO {}{}",
527                    parallelism,
528                    if *deferred { " DEFERRED" } else { "" }
529                )
530            }
531            AlterTableOperation::SetConfig { entries } => {
532                write!(f, "SET CONFIG ({})", display_comma_separated(entries))
533            }
534            AlterTableOperation::ResetConfig { keys } => {
535                write!(f, "RESET CONFIG ({})", display_comma_separated(keys))
536            }
537            AlterTableOperation::RefreshSchema => {
538                write!(f, "REFRESH SCHEMA")
539            }
540            AlterTableOperation::AlterRateLimit(rate_limit) => write!(f, "{rate_limit}"),
541            AlterTableOperation::SwapRenameTable { target_table } => {
542                write!(f, "SWAP WITH {}", target_table)
543            }
544            AlterTableOperation::DropConnector => {
545                write!(f, "DROP CONNECTOR")
546            }
547            AlterTableOperation::AlterConnectorProps { alter_props } => {
548                write!(
549                    f,
550                    "CONNECTOR WITH ({})",
551                    display_comma_separated(alter_props)
552                )
553            }
554        }
555    }
556}
557
558impl fmt::Display for AlterIndexOperation {
559    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
560        match self {
561            AlterIndexOperation::RenameIndex { index_name } => {
562                write!(f, "RENAME TO {index_name}")
563            }
564            AlterIndexOperation::SetParallelism {
565                parallelism,
566                deferred,
567            } => {
568                write!(
569                    f,
570                    "SET PARALLELISM TO {}{}",
571                    parallelism,
572                    if *deferred { " DEFERRED" } else { "" }
573                )
574            }
575            AlterIndexOperation::SetBackfillParallelism {
576                parallelism,
577                deferred,
578            } => {
579                write!(
580                    f,
581                    "SET BACKFILL_PARALLELISM TO {}{}",
582                    parallelism,
583                    if *deferred { " DEFERRED" } else { "" }
584                )
585            }
586            AlterIndexOperation::SetResourceGroup {
587                resource_group,
588                deferred,
589            } => {
590                let deferred = if *deferred { " DEFERRED" } else { "" };
591
592                if let Some(resource_group) = resource_group {
593                    write!(f, "SET RESOURCE_GROUP TO {}{}", resource_group, deferred)
594                } else {
595                    write!(f, "RESET RESOURCE_GROUP{}", deferred)
596                }
597            }
598            AlterIndexOperation::SetConfig { entries } => {
599                write!(f, "SET CONFIG ({})", display_comma_separated(entries))
600            }
601            AlterIndexOperation::ResetConfig { keys } => {
602                write!(f, "RESET CONFIG ({})", display_comma_separated(keys))
603            }
604        }
605    }
606}
607
608impl fmt::Display for AlterViewOperation {
609    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
610        match self {
611            AlterViewOperation::RenameView { view_name } => {
612                write!(f, "RENAME TO {view_name}")
613            }
614            AlterViewOperation::ChangeOwner { new_owner_name } => {
615                write!(f, "OWNER TO {}", new_owner_name)
616            }
617            AlterViewOperation::SetSchema { new_schema_name } => {
618                write!(f, "SET SCHEMA {}", new_schema_name)
619            }
620            AlterViewOperation::SetParallelism {
621                parallelism,
622                deferred,
623            } => {
624                write!(
625                    f,
626                    "SET PARALLELISM TO {}{}",
627                    parallelism,
628                    if *deferred { " DEFERRED" } else { "" }
629                )
630            }
631            AlterViewOperation::SetBackfillParallelism {
632                parallelism,
633                deferred,
634            } => {
635                write!(
636                    f,
637                    "SET BACKFILL_PARALLELISM TO {}{}",
638                    parallelism,
639                    if *deferred { " DEFERRED" } else { "" }
640                )
641            }
642            AlterViewOperation::AlterRateLimit(rate_limit) => write!(f, "{rate_limit}"),
643            AlterViewOperation::SwapRenameView { target_view } => {
644                write!(f, "SWAP WITH {}", target_view)
645            }
646            AlterViewOperation::SetResourceGroup {
647                resource_group,
648                deferred,
649            } => {
650                let deferred = if *deferred { " DEFERRED" } else { "" };
651
652                if let Some(resource_group) = resource_group {
653                    write!(f, "SET RESOURCE_GROUP TO {}{}", resource_group, deferred)
654                } else {
655                    write!(f, "RESET RESOURCE_GROUP{}", deferred)
656                }
657            }
658            AlterViewOperation::SetStreamingEnableUnalignedJoin { enable } => {
659                write!(f, "SET STREAMING_ENABLE_UNALIGNED_JOIN TO {}", enable)
660            }
661            AlterViewOperation::AsQuery { query } => {
662                write!(f, "AS {}", query)
663            }
664            AlterViewOperation::SetConfig { entries } => {
665                write!(f, "SET CONFIG ({})", display_comma_separated(entries))
666            }
667            AlterViewOperation::ResetConfig { keys } => {
668                write!(f, "RESET CONFIG ({})", display_comma_separated(keys))
669            }
670        }
671    }
672}
673
674impl fmt::Display for AlterSinkOperation {
675    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
676        match self {
677            AlterSinkOperation::RenameSink { sink_name } => {
678                write!(f, "RENAME TO {sink_name}")
679            }
680            AlterSinkOperation::ChangeOwner { new_owner_name } => {
681                write!(f, "OWNER TO {}", new_owner_name)
682            }
683            AlterSinkOperation::SetSchema { new_schema_name } => {
684                write!(f, "SET SCHEMA {}", new_schema_name)
685            }
686            AlterSinkOperation::SetParallelism {
687                parallelism,
688                deferred,
689            } => {
690                write!(
691                    f,
692                    "SET PARALLELISM TO {}{}",
693                    parallelism,
694                    if *deferred { " DEFERRED" } else { "" }
695                )
696            }
697            AlterSinkOperation::SetBackfillParallelism {
698                parallelism,
699                deferred,
700            } => {
701                write!(
702                    f,
703                    "SET BACKFILL_PARALLELISM TO {}{}",
704                    parallelism,
705                    if *deferred { " DEFERRED" } else { "" }
706                )
707            }
708            AlterSinkOperation::SetResourceGroup {
709                resource_group,
710                deferred,
711            } => {
712                let deferred = if *deferred { " DEFERRED" } else { "" };
713
714                if let Some(resource_group) = resource_group {
715                    write!(f, "SET RESOURCE_GROUP TO {}{}", resource_group, deferred)
716                } else {
717                    write!(f, "RESET RESOURCE_GROUP{}", deferred)
718                }
719            }
720            AlterSinkOperation::SetConfig { entries } => {
721                write!(f, "SET CONFIG ({})", display_comma_separated(entries))
722            }
723            AlterSinkOperation::ResetConfig { keys } => {
724                write!(f, "RESET CONFIG ({})", display_comma_separated(keys))
725            }
726            AlterSinkOperation::SwapRenameSink { target_sink } => {
727                write!(f, "SWAP WITH {}", target_sink)
728            }
729            AlterSinkOperation::AlterRateLimit(rate_limit) => write!(f, "{rate_limit}"),
730            AlterSinkOperation::AlterConnectorProps {
731                alter_props: changed_props,
732            } => {
733                write!(
734                    f,
735                    "CONNECTOR WITH ({})",
736                    display_comma_separated(changed_props)
737                )
738            }
739            AlterSinkOperation::SetStreamingEnableUnalignedJoin { enable } => {
740                write!(f, "SET STREAMING_ENABLE_UNALIGNED_JOIN TO {}", enable)
741            }
742        }
743    }
744}
745
746impl fmt::Display for AlterSubscriptionOperation {
747    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
748        match self {
749            AlterSubscriptionOperation::RenameSubscription { subscription_name } => {
750                write!(f, "RENAME TO {subscription_name}")
751            }
752            AlterSubscriptionOperation::ChangeOwner { new_owner_name } => {
753                write!(f, "OWNER TO {}", new_owner_name)
754            }
755            AlterSubscriptionOperation::SetSchema { new_schema_name } => {
756                write!(f, "SET SCHEMA {}", new_schema_name)
757            }
758            AlterSubscriptionOperation::SetRetention { retention } => {
759                write!(f, "SET RETENTION TO {}", retention)
760            }
761            AlterSubscriptionOperation::SwapRenameSubscription {
762                target_subscription,
763            } => {
764                write!(f, "SWAP WITH {}", target_subscription)
765            }
766        }
767    }
768}
769
770impl fmt::Display for AlterSourceOperation {
771    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
772        match self {
773            AlterSourceOperation::RenameSource { source_name } => {
774                write!(f, "RENAME TO {source_name}")
775            }
776            AlterSourceOperation::AddColumn { column_def } => {
777                write!(f, "ADD COLUMN {column_def}")
778            }
779            AlterSourceOperation::ChangeOwner { new_owner_name } => {
780                write!(f, "OWNER TO {}", new_owner_name)
781            }
782            AlterSourceOperation::SetSchema { new_schema_name } => {
783                write!(f, "SET SCHEMA {}", new_schema_name)
784            }
785            AlterSourceOperation::FormatEncode { format_encode } => {
786                write!(f, "{format_encode}")
787            }
788            AlterSourceOperation::RefreshSchema => {
789                write!(f, "REFRESH SCHEMA")
790            }
791            AlterSourceOperation::AlterRateLimit(rate_limit) => write!(f, "{rate_limit}"),
792            AlterSourceOperation::SwapRenameSource { target_source } => {
793                write!(f, "SWAP WITH {}", target_source)
794            }
795            AlterSourceOperation::SetParallelism {
796                parallelism,
797                deferred,
798            } => {
799                write!(
800                    f,
801                    "SET PARALLELISM TO {}{}",
802                    parallelism,
803                    if *deferred { " DEFERRED" } else { "" }
804                )
805            }
806            AlterSourceOperation::SetBackfillParallelism {
807                parallelism,
808                deferred,
809            } => {
810                write!(
811                    f,
812                    "SET BACKFILL_PARALLELISM TO {}{}",
813                    parallelism,
814                    if *deferred { " DEFERRED" } else { "" }
815                )
816            }
817            AlterSourceOperation::SetConfig { entries } => {
818                write!(f, "SET CONFIG ({})", display_comma_separated(entries))
819            }
820            AlterSourceOperation::ResetConfig { keys } => {
821                write!(f, "RESET CONFIG ({})", display_comma_separated(keys))
822            }
823            AlterSourceOperation::ResetSource => {
824                write!(f, "RESET")
825            }
826            AlterSourceOperation::AlterConnectorProps { alter_props } => {
827                write!(
828                    f,
829                    "CONNECTOR WITH ({})",
830                    display_comma_separated(alter_props)
831                )
832            }
833        }
834    }
835}
836
837impl fmt::Display for AlterFunctionOperation {
838    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
839        match self {
840            AlterFunctionOperation::SetSchema { new_schema_name } => {
841                write!(f, "SET SCHEMA {new_schema_name}")
842            }
843            AlterFunctionOperation::ChangeOwner { new_owner_name } => {
844                write!(f, "OWNER TO {new_owner_name}")
845            }
846        }
847    }
848}
849
850impl fmt::Display for AlterConnectionOperation {
851    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
852        match self {
853            AlterConnectionOperation::SetSchema { new_schema_name } => {
854                write!(f, "SET SCHEMA {new_schema_name}")
855            }
856            AlterConnectionOperation::ChangeOwner { new_owner_name } => {
857                write!(f, "OWNER TO {new_owner_name}")
858            }
859            AlterConnectionOperation::AlterConnectorProps { alter_props } => {
860                write!(
861                    f,
862                    "CONNECTOR WITH ({})",
863                    display_comma_separated(alter_props)
864                )
865            }
866        }
867    }
868}
869
870impl fmt::Display for AlterSecretOperation {
871    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
872        match self {
873            AlterSecretOperation::ChangeCredential {
874                new_credential,
875                with_options,
876            } => {
877                write!(
878                    f,
879                    "WITH ({}) AS {}",
880                    display_comma_separated(with_options),
881                    new_credential
882                )
883            }
884            AlterSecretOperation::ChangeOwner { new_owner_name } => {
885                write!(f, "OWNER TO {new_owner_name}")
886            }
887        }
888    }
889}
890
891/// An `ALTER COLUMN` (`Statement::AlterTable`) operation
892#[derive(Debug, Clone, PartialEq, Eq, Hash)]
893pub enum AlterColumnOperation {
894    /// `SET NOT NULL`
895    SetNotNull,
896    /// `DROP NOT NULL`
897    DropNotNull,
898    /// `SET DEFAULT <expr>`
899    SetDefault { value: Expr },
900    /// `DROP DEFAULT`
901    DropDefault,
902    /// `[SET DATA] TYPE <data_type> [USING <expr>]`
903    SetDataType {
904        data_type: DataType,
905        /// PostgreSQL specific
906        using: Option<Expr>,
907    },
908}
909
910impl fmt::Display for AlterColumnOperation {
911    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
912        match self {
913            AlterColumnOperation::SetNotNull => write!(f, "SET NOT NULL",),
914            AlterColumnOperation::DropNotNull => write!(f, "DROP NOT NULL",),
915            AlterColumnOperation::SetDefault { value } => {
916                write!(f, "SET DEFAULT {}", value)
917            }
918            AlterColumnOperation::DropDefault => {
919                write!(f, "DROP DEFAULT")
920            }
921            AlterColumnOperation::SetDataType { data_type, using } => {
922                if let Some(expr) = using {
923                    write!(f, "SET DATA TYPE {} USING {}", data_type, expr)
924                } else {
925                    write!(f, "SET DATA TYPE {}", data_type)
926                }
927            }
928        }
929    }
930}
931
932impl fmt::Display for AlterFragmentOperation {
933    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
934        match self {
935            AlterFragmentOperation::AlterRateLimit(rate_limit) => write!(f, "{rate_limit}"),
936            AlterFragmentOperation::SetParallelism { parallelism } => {
937                write!(f, "SET PARALLELISM TO {}", parallelism)
938            }
939        }
940    }
941}
942
943impl fmt::Display for AlterCompactionGroupOperation {
944    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
945        match self {
946            AlterCompactionGroupOperation::Set { configs } => {
947                struct Assign<'a>(&'a ConfigParam);
948
949                impl fmt::Display for Assign<'_> {
950                    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
951                        write!(f, "{} = {}", self.0.param, self.0.value)
952                    }
953                }
954
955                let assigns: Vec<Assign<'_>> = configs.iter().map(Assign).collect();
956                write!(f, "SET {}", display_comma_separated(&assigns))
957            }
958        }
959    }
960}
961
962/// The watermark on source.
963/// `WATERMARK FOR <column> AS (<expr>)`
964#[derive(Debug, Clone, PartialEq, Eq, Hash)]
965pub struct SourceWatermark {
966    pub column: Ident,
967    pub expr: Expr,
968    /// Whether `WITH TTL` is specified.
969    pub with_ttl: bool,
970}
971
972impl fmt::Display for SourceWatermark {
973    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
974        write!(f, "WATERMARK FOR {} AS {}", self.column, self.expr,)?;
975        if self.with_ttl {
976            write!(f, " WITH TTL")?;
977        }
978        Ok(())
979    }
980}
981
982/// A table-level constraint, specified in a `CREATE TABLE` or an
983/// `ALTER TABLE ADD <constraint>` statement.
984#[derive(Debug, Clone, PartialEq, Eq, Hash)]
985pub enum TableConstraint {
986    /// `[ CONSTRAINT <name> ] { PRIMARY KEY | UNIQUE } (<columns>)`
987    Unique {
988        name: Option<Ident>,
989        columns: Vec<Ident>,
990        /// Whether this is a `PRIMARY KEY` or just a `UNIQUE` constraint
991        is_primary: bool,
992    },
993    /// A referential integrity constraint (`[ CONSTRAINT <name> ] FOREIGN KEY (<columns>)
994    /// REFERENCES <foreign_table> (<referred_columns>)
995    /// { [ON DELETE <referential_action>] [ON UPDATE <referential_action>] |
996    ///   [ON UPDATE <referential_action>] [ON DELETE <referential_action>]
997    /// }`).
998    ForeignKey {
999        name: Option<Ident>,
1000        columns: Vec<Ident>,
1001        foreign_table: ObjectName,
1002        referred_columns: Vec<Ident>,
1003        on_delete: Option<ReferentialAction>,
1004        on_update: Option<ReferentialAction>,
1005    },
1006    /// `[ CONSTRAINT <name> ] CHECK (<expr>)`
1007    Check {
1008        name: Option<Ident>,
1009        expr: Box<Expr>,
1010    },
1011}
1012
1013impl fmt::Display for TableConstraint {
1014    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1015        match self {
1016            TableConstraint::Unique {
1017                name,
1018                columns,
1019                is_primary,
1020            } => write!(
1021                f,
1022                "{}{} ({})",
1023                display_constraint_name(name),
1024                if *is_primary { "PRIMARY KEY" } else { "UNIQUE" },
1025                display_comma_separated(columns)
1026            ),
1027            TableConstraint::ForeignKey {
1028                name,
1029                columns,
1030                foreign_table,
1031                referred_columns,
1032                on_delete,
1033                on_update,
1034            } => {
1035                write!(
1036                    f,
1037                    "{}FOREIGN KEY ({}) REFERENCES {}({})",
1038                    display_constraint_name(name),
1039                    display_comma_separated(columns),
1040                    foreign_table,
1041                    display_comma_separated(referred_columns),
1042                )?;
1043                if let Some(action) = on_delete {
1044                    write!(f, " ON DELETE {}", action)?;
1045                }
1046                if let Some(action) = on_update {
1047                    write!(f, " ON UPDATE {}", action)?;
1048                }
1049                Ok(())
1050            }
1051            TableConstraint::Check { name, expr } => {
1052                write!(f, "{}CHECK ({})", display_constraint_name(name), expr)
1053            }
1054        }
1055    }
1056}
1057
1058/// SQL column definition
1059#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1060pub struct ColumnDef {
1061    pub name: Ident,
1062    pub data_type: Option<DataType>,
1063    pub collation: Option<ObjectName>,
1064    pub options: Vec<ColumnOptionDef>,
1065}
1066
1067impl ColumnDef {
1068    pub fn new(
1069        name: Ident,
1070        data_type: DataType,
1071        collation: Option<ObjectName>,
1072        options: Vec<ColumnOptionDef>,
1073    ) -> Self {
1074        ColumnDef {
1075            name,
1076            data_type: Some(data_type),
1077            collation,
1078            options,
1079        }
1080    }
1081
1082    pub fn is_generated(&self) -> bool {
1083        self.options
1084            .iter()
1085            .any(|option| matches!(option.option, ColumnOption::GeneratedColumns(_)))
1086    }
1087}
1088
1089impl fmt::Display for ColumnDef {
1090    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1091        write!(
1092            f,
1093            "{} {}",
1094            self.name,
1095            if let Some(data_type) = &self.data_type {
1096                data_type.to_string()
1097            } else {
1098                "None".to_owned()
1099            }
1100        )?;
1101        for option in &self.options {
1102            write!(f, " {}", option)?;
1103        }
1104        Ok(())
1105    }
1106}
1107
1108/// An optionally-named `ColumnOption`: `[ CONSTRAINT <name> ] <column-option>`.
1109///
1110/// Note that implementations are substantially more permissive than the ANSI
1111/// specification on what order column options can be presented in, and whether
1112/// they are allowed to be named. The specification distinguishes between
1113/// constraints (NOT NULL, UNIQUE, PRIMARY KEY, and CHECK), which can be named
1114/// and can appear in any order, and other options (DEFAULT, GENERATED), which
1115/// cannot be named and must appear in a fixed order. PostgreSQL, however,
1116/// allows preceding any option with `CONSTRAINT <name>`, even those that are
1117/// not really constraints, like NULL and DEFAULT. MSSQL is less permissive,
1118/// allowing DEFAULT, UNIQUE, PRIMARY KEY and CHECK to be named, but not NULL or
1119/// NOT NULL constraints (the last of which is in violation of the spec).
1120///
1121/// For maximum flexibility, we don't distinguish between constraint and
1122/// non-constraint options, lumping them all together under the umbrella of
1123/// "column options," and we allow any column option to be named.
1124#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1125pub struct ColumnOptionDef {
1126    pub name: Option<Ident>,
1127    pub option: ColumnOption,
1128}
1129
1130impl fmt::Display for ColumnOptionDef {
1131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1132        write!(f, "{}{}", display_constraint_name(&self.name), self.option)
1133    }
1134}
1135
1136/// `ColumnOption`s are modifiers that follow a column definition in a `CREATE
1137/// TABLE` statement.
1138#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1139pub enum ColumnOption {
1140    /// `NULL`
1141    Null,
1142    /// `NOT NULL`
1143    NotNull,
1144    /// `DEFAULT <restricted-expr>`
1145    DefaultValue(Expr),
1146    /// Default value from previous bound `DefaultColumnDesc`. Used internally
1147    /// for schema change and should not be specified by users.
1148    DefaultValueInternal {
1149        /// Protobuf encoded `DefaultColumnDesc`.
1150        persisted: Box<[u8]>,
1151        /// Optional AST for unparsing. If `None`, the default value will be
1152        /// shown as `DEFAULT INTERNAL` which is for demonstrating and should
1153        /// not be specified by users.
1154        expr: Option<Expr>,
1155    },
1156    /// `{ PRIMARY KEY | UNIQUE }`
1157    Unique { is_primary: bool },
1158    /// A referential integrity constraint (`[FOREIGN KEY REFERENCES
1159    /// <foreign_table> (<referred_columns>)
1160    /// { [ON DELETE <referential_action>] [ON UPDATE <referential_action>] |
1161    ///   [ON UPDATE <referential_action>] [ON DELETE <referential_action>]
1162    /// }`).
1163    ForeignKey {
1164        foreign_table: ObjectName,
1165        referred_columns: Vec<Ident>,
1166        on_delete: Option<ReferentialAction>,
1167        on_update: Option<ReferentialAction>,
1168    },
1169    /// `CHECK (<expr>)`
1170    Check(Expr),
1171    /// Dialect-specific options, such as:
1172    /// - MySQL's `AUTO_INCREMENT` or SQLite's `AUTOINCREMENT`
1173    /// - ...
1174    DialectSpecific(Vec<Token>),
1175    /// AS ( <generation_expr> )`
1176    GeneratedColumns(Expr),
1177}
1178
1179impl fmt::Display for ColumnOption {
1180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1181        use ColumnOption::*;
1182        match self {
1183            Null => write!(f, "NULL"),
1184            NotNull => write!(f, "NOT NULL"),
1185            DefaultValue(expr) => write!(f, "DEFAULT {}", expr),
1186            DefaultValueInternal { persisted: _, expr } => {
1187                if let Some(expr) = expr {
1188                    write!(f, "DEFAULT {}", expr)
1189                } else {
1190                    write!(f, "DEFAULT INTERNAL")
1191                }
1192            }
1193            Unique { is_primary } => {
1194                write!(f, "{}", if *is_primary { "PRIMARY KEY" } else { "UNIQUE" })
1195            }
1196            ForeignKey {
1197                foreign_table,
1198                referred_columns,
1199                on_delete,
1200                on_update,
1201            } => {
1202                write!(f, "REFERENCES {}", foreign_table)?;
1203                if !referred_columns.is_empty() {
1204                    write!(f, " ({})", display_comma_separated(referred_columns))?;
1205                }
1206                if let Some(action) = on_delete {
1207                    write!(f, " ON DELETE {}", action)?;
1208                }
1209                if let Some(action) = on_update {
1210                    write!(f, " ON UPDATE {}", action)?;
1211                }
1212                Ok(())
1213            }
1214            Check(expr) => write!(f, "CHECK ({})", expr),
1215            DialectSpecific(val) => write!(f, "{}", display_separated(val, " ")),
1216            GeneratedColumns(expr) => write!(f, "AS {}", expr),
1217        }
1218    }
1219}
1220
1221fn display_constraint_name(name: &'_ Option<Ident>) -> impl fmt::Display + '_ {
1222    struct ConstraintName<'a>(&'a Option<Ident>);
1223    impl fmt::Display for ConstraintName<'_> {
1224        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1225            if let Some(name) = self.0 {
1226                write!(f, "CONSTRAINT {} ", name)?;
1227            }
1228            Ok(())
1229        }
1230    }
1231    ConstraintName(name)
1232}
1233
1234/// `<referential_action> =
1235/// { RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT }`
1236///
1237/// Used in foreign key constraints in `ON UPDATE` and `ON DELETE` options.
1238#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1239pub enum ReferentialAction {
1240    Restrict,
1241    Cascade,
1242    SetNull,
1243    NoAction,
1244    SetDefault,
1245}
1246
1247impl fmt::Display for ReferentialAction {
1248    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1249        f.write_str(match self {
1250            ReferentialAction::Restrict => "RESTRICT",
1251            ReferentialAction::Cascade => "CASCADE",
1252            ReferentialAction::SetNull => "SET NULL",
1253            ReferentialAction::NoAction => "NO ACTION",
1254            ReferentialAction::SetDefault => "SET DEFAULT",
1255        })
1256    }
1257}
1258
1259/// secure secret definition for webhook source
1260#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1261pub struct WebhookSourceInfo {
1262    pub secret_ref: Option<SecretRefValue>,
1263    pub signature_expr: Option<Expr>,
1264    pub wait_for_persistence: bool,
1265    pub is_batched: bool,
1266}