-
Notifications
You must be signed in to change notification settings - Fork 711
Expand file tree
/
Copy pathddl.rs
More file actions
5889 lines (5583 loc) · 211 KB
/
ddl.rs
File metadata and controls
5889 lines (5583 loc) · 211 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! AST types specific to CREATE/ALTER variants of [`Statement`](crate::ast::Statement)
//! (commonly referred to as Data Definition Language, or DDL)
#[cfg(not(feature = "std"))]
use alloc::{
boxed::Box,
format,
string::{String, ToString},
vec,
vec::Vec,
};
use core::fmt::{self, Display, Write};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "visitor")]
use sqlparser_derive::{Visit, VisitMut};
use crate::ast::value::escape_single_quote_string;
use crate::ast::{
display_comma_separated, display_separated,
table_constraints::{
CheckConstraint, ForeignKeyConstraint, PrimaryKeyConstraint, TableConstraint,
UniqueConstraint,
},
ArgMode, AttachedToken, CommentDef, ConditionalStatements, CreateFunctionBody,
CreateFunctionUsing, CreateTableLikeKind, CreateTableOptions, CreateViewParams, DataType, Expr,
FileFormat, FunctionBehavior, FunctionCalledOnNull, FunctionDefinitionSetParam, FunctionDesc,
FunctionDeterminismSpecifier, FunctionParallel, FunctionSecurity, HiveDistributionStyle,
HiveFormat, HiveIOFormat, HiveRowFormat, HiveSetLocation, Ident, InitializeKind,
MySQLColumnPosition, ObjectName, OnCommit, OneOrManyWithParens, OperateFunctionArg,
OrderByExpr, ProjectionSelect, Query, RefreshModeKind, ResetConfig, RowAccessPolicy,
SequenceOptions, Spanned, SqlOption, StorageLifecyclePolicy, StorageSerializationPolicy,
TableVersion, Tag, TriggerEvent, TriggerExecBody, TriggerObject, TriggerPeriod,
TriggerReferencing, Value, ValueWithSpan, WrappedCollection,
};
use crate::display_utils::{DisplayCommaSeparated, Indent, NewLine, SpaceOrNewline};
use crate::keywords::Keyword;
use crate::tokenizer::{Span, Token};
/// Index column type.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct IndexColumn {
/// The indexed column expression.
pub column: OrderByExpr,
/// Optional operator class (index operator name).
pub operator_class: Option<ObjectName>,
}
impl From<Ident> for IndexColumn {
fn from(c: Ident) -> Self {
Self {
column: OrderByExpr::from(c),
operator_class: None,
}
}
}
impl<'a> From<&'a str> for IndexColumn {
fn from(c: &'a str) -> Self {
let ident = Ident::new(c);
ident.into()
}
}
impl fmt::Display for IndexColumn {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.column)?;
if let Some(operator_class) = &self.operator_class {
write!(f, " {operator_class}")?;
}
Ok(())
}
}
/// ALTER TABLE operation REPLICA IDENTITY values
/// See [Postgres ALTER TABLE docs](https://www.postgresql.org/docs/current/sql-altertable.html)
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum ReplicaIdentity {
/// No replica identity (`REPLICA IDENTITY NOTHING`).
Nothing,
/// Full replica identity (`REPLICA IDENTITY FULL`).
Full,
/// Default replica identity (`REPLICA IDENTITY DEFAULT`).
Default,
/// Use the given index as replica identity (`REPLICA IDENTITY USING INDEX`).
Index(Ident),
}
impl fmt::Display for ReplicaIdentity {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ReplicaIdentity::Nothing => f.write_str("NOTHING"),
ReplicaIdentity::Full => f.write_str("FULL"),
ReplicaIdentity::Default => f.write_str("DEFAULT"),
ReplicaIdentity::Index(idx) => write!(f, "USING INDEX {idx}"),
}
}
}
/// An `ALTER TABLE` (`Statement::AlterTable`) operation
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum AlterTableOperation {
/// `ADD <table_constraint> [NOT VALID]`
AddConstraint {
/// The table constraint to add.
constraint: TableConstraint,
/// Whether the constraint should be marked `NOT VALID`.
not_valid: bool,
},
/// `ADD [COLUMN] [IF NOT EXISTS] <column_def>`
AddColumn {
/// `[COLUMN]`.
column_keyword: bool,
/// `[IF NOT EXISTS]`
if_not_exists: bool,
/// <column_def>.
column_def: ColumnDef,
/// MySQL `ALTER TABLE` only [FIRST | AFTER column_name]
column_position: Option<MySQLColumnPosition>,
},
/// `ADD PROJECTION [IF NOT EXISTS] name ( SELECT <COLUMN LIST EXPR> [GROUP BY] [ORDER BY])`
///
/// Note: this is a ClickHouse-specific operation.
/// Please refer to [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/projection#add-projection)
AddProjection {
/// Whether `IF NOT EXISTS` was specified.
if_not_exists: bool,
/// Name of the projection to add.
name: Ident,
/// The projection's select clause.
select: ProjectionSelect,
},
/// `DROP PROJECTION [IF EXISTS] name`
///
/// Note: this is a ClickHouse-specific operation.
/// Please refer to [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/projection#drop-projection)
DropProjection {
/// Whether `IF EXISTS` was specified.
if_exists: bool,
/// Name of the projection to drop.
name: Ident,
},
/// `MATERIALIZE PROJECTION [IF EXISTS] name [IN PARTITION partition_name]`
///
/// Note: this is a ClickHouse-specific operation.
/// Please refer to [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/projection#materialize-projection)
MaterializeProjection {
/// Whether `IF EXISTS` was specified.
if_exists: bool,
/// Name of the projection to materialize.
name: Ident,
/// Optional partition name to operate on.
partition: Option<Ident>,
},
/// `CLEAR PROJECTION [IF EXISTS] name [IN PARTITION partition_name]`
///
/// Note: this is a ClickHouse-specific operation.
/// Please refer to [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/projection#clear-projection)
ClearProjection {
/// Whether `IF EXISTS` was specified.
if_exists: bool,
/// Name of the projection to clear.
name: Ident,
/// Optional partition name to operate on.
partition: Option<Ident>,
},
/// `DISABLE ROW LEVEL SECURITY`
///
/// Note: this is a PostgreSQL-specific operation.
/// Please refer to [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-altertable.html)
DisableRowLevelSecurity,
/// `DISABLE RULE rewrite_rule_name`
///
/// Note: this is a PostgreSQL-specific operation.
DisableRule {
/// Name of the rule to disable.
name: Ident,
},
/// `DISABLE TRIGGER [ trigger_name | ALL | USER ]`
///
/// Note: this is a PostgreSQL-specific operation.
DisableTrigger {
/// Name of the trigger to disable (or ALL/USER).
name: Ident,
},
/// `DROP CONSTRAINT [ IF EXISTS ] <name>`
DropConstraint {
/// `IF EXISTS` flag for dropping the constraint.
if_exists: bool,
/// Name of the constraint to drop.
name: Ident,
/// Optional drop behavior (`CASCADE`/`RESTRICT`).
drop_behavior: Option<DropBehavior>,
},
/// `DROP [ COLUMN ] [ IF EXISTS ] <column_name> [ , <column_name>, ... ] [ CASCADE ]`
DropColumn {
/// Whether the `COLUMN` keyword was present.
has_column_keyword: bool,
/// Names of columns to drop.
column_names: Vec<Ident>,
/// Whether `IF EXISTS` was specified for the columns.
if_exists: bool,
/// Optional drop behavior for the column removal.
drop_behavior: Option<DropBehavior>,
},
/// `ATTACH PART|PARTITION <partition_expr>`
/// Note: this is a ClickHouse-specific operation, please refer to
/// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/partition#attach-partitionpart)
AttachPartition {
// PART is not a short form of PARTITION, it's a separate keyword
// which represents a physical file on disk and partition is a logical entity.
/// Partition expression to attach.
partition: Partition,
},
/// `DETACH PART|PARTITION <partition_expr>`
/// Note: this is a ClickHouse-specific operation, please refer to
/// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/partition#detach-partitionpart)
DetachPartition {
// See `AttachPartition` for more details
/// Partition expression to detach.
partition: Partition,
},
/// `FREEZE PARTITION <partition_expr>`
/// Note: this is a ClickHouse-specific operation, please refer to
/// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/partition#freeze-partition)
FreezePartition {
/// Partition to freeze.
partition: Partition,
/// Optional name for the freeze operation.
with_name: Option<Ident>,
},
/// `UNFREEZE PARTITION <partition_expr>`
/// Note: this is a ClickHouse-specific operation, please refer to
/// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/alter/partition#unfreeze-partition)
UnfreezePartition {
/// Partition to unfreeze.
partition: Partition,
/// Optional name associated with the unfreeze operation.
with_name: Option<Ident>,
},
/// `DROP PRIMARY KEY`
///
/// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/alter-table.html)
/// [Snowflake](https://docs.snowflake.com/en/sql-reference/constraints-drop)
DropPrimaryKey {
/// Optional drop behavior for the primary key (`CASCADE`/`RESTRICT`).
drop_behavior: Option<DropBehavior>,
},
/// `DROP FOREIGN KEY <fk_symbol>`
///
/// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/alter-table.html)
/// [Snowflake](https://docs.snowflake.com/en/sql-reference/constraints-drop)
DropForeignKey {
/// Foreign key symbol/name to drop.
name: Ident,
/// Optional drop behavior for the foreign key.
drop_behavior: Option<DropBehavior>,
},
/// `DROP INDEX <index_name>`
///
/// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/alter-table.html
DropIndex {
/// Name of the index to drop.
name: Ident,
},
/// `ENABLE ALWAYS RULE rewrite_rule_name`
///
/// Note: this is a PostgreSQL-specific operation.
EnableAlwaysRule {
/// Name of the rule to enable.
name: Ident,
},
/// `ENABLE ALWAYS TRIGGER trigger_name`
///
/// Note: this is a PostgreSQL-specific operation.
EnableAlwaysTrigger {
/// Name of the trigger to enable.
name: Ident,
},
/// `ENABLE REPLICA RULE rewrite_rule_name`
///
/// Note: this is a PostgreSQL-specific operation.
EnableReplicaRule {
/// Name of the replica rule to enable.
name: Ident,
},
/// `ENABLE REPLICA TRIGGER trigger_name`
///
/// Note: this is a PostgreSQL-specific operation.
EnableReplicaTrigger {
/// Name of the replica trigger to enable.
name: Ident,
},
/// `ENABLE ROW LEVEL SECURITY`
///
/// Note: this is a PostgreSQL-specific operation.
/// Please refer to [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-altertable.html)
EnableRowLevelSecurity,
/// `FORCE ROW LEVEL SECURITY`
///
/// Note: this is a PostgreSQL-specific operation.
/// Please refer to [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-altertable.html)
ForceRowLevelSecurity,
/// `NO FORCE ROW LEVEL SECURITY`
///
/// Note: this is a PostgreSQL-specific operation.
/// Please refer to [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-altertable.html)
NoForceRowLevelSecurity,
/// `ENABLE RULE rewrite_rule_name`
///
/// Note: this is a PostgreSQL-specific operation.
EnableRule {
/// Name of the rule to enable.
name: Ident,
},
/// `ENABLE TRIGGER [ trigger_name | ALL | USER ]`
///
/// Note: this is a PostgreSQL-specific operation.
EnableTrigger {
/// Name of the trigger to enable (or ALL/USER).
name: Ident,
},
/// `RENAME TO PARTITION (partition=val)`
RenamePartitions {
/// Old partition expressions to be renamed.
old_partitions: Vec<Expr>,
/// New partition expressions corresponding to the old ones.
new_partitions: Vec<Expr>,
},
/// REPLICA IDENTITY { DEFAULT | USING INDEX index_name | FULL | NOTHING }
///
/// Note: this is a PostgreSQL-specific operation.
/// Please refer to [PostgreSQL documentation](https://www.postgresql.org/docs/current/sql-altertable.html)
ReplicaIdentity {
/// Replica identity setting to apply.
identity: ReplicaIdentity,
},
/// Add Partitions
AddPartitions {
/// Whether `IF NOT EXISTS` was present when adding partitions.
if_not_exists: bool,
/// New partitions to add.
new_partitions: Vec<Partition>,
},
/// `DROP PARTITIONS ...` / drop partitions from the table.
DropPartitions {
/// Partitions to drop (expressions).
partitions: Vec<Expr>,
/// Whether `IF EXISTS` was specified for dropping partitions.
if_exists: bool,
},
/// `RENAME [ COLUMN ] <old_column_name> TO <new_column_name>`
RenameColumn {
/// Existing column name to rename.
old_column_name: Ident,
/// New column name.
new_column_name: Ident,
},
/// `RENAME TO <table_name>`
RenameTable {
/// The new table name or renaming kind.
table_name: RenameTableNameKind,
},
// CHANGE [ COLUMN ] <old_name> <new_name> <data_type> [ <options> ]
/// Change an existing column's name, type, and options.
ChangeColumn {
/// Old column name.
old_name: Ident,
/// New column name.
new_name: Ident,
/// New data type for the column.
data_type: DataType,
/// Column options to apply after the change.
options: Vec<ColumnOption>,
/// MySQL-specific column position (`FIRST`/`AFTER`).
column_position: Option<MySQLColumnPosition>,
},
// CHANGE [ COLUMN ] <col_name> <data_type> [ <options> ]
/// Modify an existing column's type and options.
ModifyColumn {
/// Column name to modify.
col_name: Ident,
/// New data type for the column.
data_type: DataType,
/// Column options to set.
options: Vec<ColumnOption>,
/// MySQL-specific column position (`FIRST`/`AFTER`).
column_position: Option<MySQLColumnPosition>,
},
/// `RENAME CONSTRAINT <old_constraint_name> TO <new_constraint_name>`
///
/// Note: this is a PostgreSQL-specific operation.
/// Rename a constraint on the table.
RenameConstraint {
/// Existing constraint name.
old_name: Ident,
/// New constraint name.
new_name: Ident,
},
/// `ALTER [ COLUMN ]`
/// Alter a specific column with the provided operation.
AlterColumn {
/// The column to alter.
column_name: Ident,
/// Operation to apply to the column.
op: AlterColumnOperation,
},
/// 'SWAP WITH <table_name>'
///
/// Note: this is Snowflake specific <https://docs.snowflake.com/en/sql-reference/sql/alter-table>
SwapWith {
/// Table name to swap with.
table_name: ObjectName,
},
/// 'SET TBLPROPERTIES ( { property_key [ = ] property_val } [, ...] )'
SetTblProperties {
/// Table properties specified as SQL options.
table_properties: Vec<SqlOption>,
},
/// `OWNER TO { <new_owner> | CURRENT_ROLE | CURRENT_USER | SESSION_USER }`
///
/// Note: this is PostgreSQL-specific <https://www.postgresql.org/docs/current/sql-altertable.html>
OwnerTo {
/// The new owner to assign to the table.
new_owner: Owner,
},
/// Snowflake table clustering options
/// <https://docs.snowflake.com/en/sql-reference/sql/alter-table#clustering-actions-clusteringaction>
ClusterBy {
/// Expressions used for clustering the table.
exprs: Vec<Expr>,
},
/// Remove the clustering key from the table.
DropClusteringKey,
/// Redshift `ALTER SORTKEY (column_list)`
/// <https://docs.aws.amazon.com/redshift/latest/dg/r_ALTER_TABLE.html>
AlterSortKey {
/// Column references in the sort key.
columns: Vec<Expr>,
},
/// Suspend background reclustering operations.
SuspendRecluster,
/// Resume background reclustering operations.
ResumeRecluster,
/// `REFRESH [ '<subpath>' ]`
///
/// Note: this is Snowflake specific for dynamic/external tables
/// <https://docs.snowflake.com/en/sql-reference/sql/alter-dynamic-table>
/// <https://docs.snowflake.com/en/sql-reference/sql/alter-external-table>
Refresh {
/// Optional subpath for external table refresh
subpath: Option<String>,
},
/// `SUSPEND`
///
/// Note: this is Snowflake specific for dynamic tables <https://docs.snowflake.com/en/sql-reference/sql/alter-table>
Suspend,
/// `RESUME`
///
/// Note: this is Snowflake specific for dynamic tables <https://docs.snowflake.com/en/sql-reference/sql/alter-table>
Resume,
/// `ALGORITHM [=] { DEFAULT | INSTANT | INPLACE | COPY }`
///
/// [MySQL]-specific table alter algorithm.
///
/// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/alter-table.html
Algorithm {
/// Whether the `=` sign was used (`ALGORITHM = ...`).
equals: bool,
/// The algorithm to use for the alter operation (MySQL-specific).
algorithm: AlterTableAlgorithm,
},
/// `LOCK [=] { DEFAULT | NONE | SHARED | EXCLUSIVE }`
///
/// [MySQL]-specific table alter lock.
///
/// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/alter-table.html
Lock {
/// Whether the `=` sign was used (`LOCK = ...`).
equals: bool,
/// The locking behavior to apply (MySQL-specific).
lock: AlterTableLock,
},
/// `AUTO_INCREMENT [=] <value>`
///
/// [MySQL]-specific table option for raising current auto increment value.
///
/// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/alter-table.html
AutoIncrement {
/// Whether the `=` sign was used (`AUTO_INCREMENT = ...`).
equals: bool,
/// Value to set for the auto-increment counter.
value: ValueWithSpan,
},
/// `VALIDATE CONSTRAINT <name>`
ValidateConstraint {
/// Name of the constraint to validate.
name: Ident,
},
/// Arbitrary parenthesized `SET` options.
///
/// Example:
/// ```sql
/// SET (scale_factor = 0.01, threshold = 500)`
/// ```
/// [PostgreSQL](https://www.postgresql.org/docs/current/sql-altertable.html)
SetOptionsParens {
/// Parenthesized options supplied to `SET (...)`.
options: Vec<SqlOption>,
},
}
/// An `ALTER Policy` (`Statement::AlterPolicy`) operation
///
/// [PostgreSQL Documentation](https://www.postgresql.org/docs/current/sql-altertable.html)
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum AlterPolicyOperation {
/// Rename the policy to `new_name`.
Rename {
/// The new identifier for the policy.
new_name: Ident,
},
/// Apply/modify policy properties.
Apply {
/// Optional list of owners the policy applies to.
to: Option<Vec<Owner>>,
/// Optional `USING` expression for the policy.
using: Option<Expr>,
/// Optional `WITH CHECK` expression for the policy.
with_check: Option<Expr>,
},
}
impl fmt::Display for AlterPolicyOperation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
AlterPolicyOperation::Rename { new_name } => {
write!(f, " RENAME TO {new_name}")
}
AlterPolicyOperation::Apply {
to,
using,
with_check,
} => {
if let Some(to) = to {
write!(f, " TO {}", display_comma_separated(to))?;
}
if let Some(using) = using {
write!(f, " USING ({using})")?;
}
if let Some(with_check) = with_check {
write!(f, " WITH CHECK ({with_check})")?;
}
Ok(())
}
}
}
}
/// [MySQL] `ALTER TABLE` algorithm.
///
/// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/alter-table.html
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// Algorithm option for `ALTER TABLE` operations (MySQL-specific).
pub enum AlterTableAlgorithm {
/// Default algorithm selection.
Default,
/// `INSTANT` algorithm.
Instant,
/// `INPLACE` algorithm.
Inplace,
/// `COPY` algorithm.
Copy,
}
impl fmt::Display for AlterTableAlgorithm {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match self {
Self::Default => "DEFAULT",
Self::Instant => "INSTANT",
Self::Inplace => "INPLACE",
Self::Copy => "COPY",
})
}
}
/// [MySQL] `ALTER TABLE` lock.
///
/// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/alter-table.html
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// Locking behavior for `ALTER TABLE` (MySQL-specific).
pub enum AlterTableLock {
/// `DEFAULT` lock behavior.
Default,
/// `NONE` lock.
None,
/// `SHARED` lock.
Shared,
/// `EXCLUSIVE` lock.
Exclusive,
}
impl fmt::Display for AlterTableLock {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match self {
Self::Default => "DEFAULT",
Self::None => "NONE",
Self::Shared => "SHARED",
Self::Exclusive => "EXCLUSIVE",
})
}
}
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// New owner specification for `ALTER TABLE ... OWNER TO ...`
pub enum Owner {
/// A specific user/role identifier.
Ident(Ident),
/// `CURRENT_ROLE` keyword.
CurrentRole,
/// `CURRENT_USER` keyword.
CurrentUser,
/// `SESSION_USER` keyword.
SessionUser,
}
impl fmt::Display for Owner {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Owner::Ident(ident) => write!(f, "{ident}"),
Owner::CurrentRole => write!(f, "CURRENT_ROLE"),
Owner::CurrentUser => write!(f, "CURRENT_USER"),
Owner::SessionUser => write!(f, "SESSION_USER"),
}
}
}
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// New connector owner specification for `ALTER CONNECTOR ... OWNER TO ...`
pub enum AlterConnectorOwner {
/// `USER <ident>` connector owner.
User(Ident),
/// `ROLE <ident>` connector owner.
Role(Ident),
}
impl fmt::Display for AlterConnectorOwner {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
AlterConnectorOwner::User(ident) => write!(f, "USER {ident}"),
AlterConnectorOwner::Role(ident) => write!(f, "ROLE {ident}"),
}
}
}
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
/// Alterations that can be applied to an index.
pub enum AlterIndexOperation {
/// Rename the index to `index_name`.
RenameIndex {
/// The new name for the index.
index_name: ObjectName,
},
}
impl fmt::Display for AlterTableOperation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
AlterTableOperation::AddPartitions {
if_not_exists,
new_partitions,
} => write!(
f,
"ADD{ine} {}",
display_separated(new_partitions, " "),
ine = if *if_not_exists { " IF NOT EXISTS" } else { "" }
),
AlterTableOperation::AddConstraint {
not_valid,
constraint,
} => {
write!(f, "ADD {constraint}")?;
if *not_valid {
write!(f, " NOT VALID")?;
}
Ok(())
}
AlterTableOperation::AddColumn {
column_keyword,
if_not_exists,
column_def,
column_position,
} => {
write!(f, "ADD")?;
if *column_keyword {
write!(f, " COLUMN")?;
}
if *if_not_exists {
write!(f, " IF NOT EXISTS")?;
}
write!(f, " {column_def}")?;
if let Some(position) = column_position {
write!(f, " {position}")?;
}
Ok(())
}
AlterTableOperation::AddProjection {
if_not_exists,
name,
select: query,
} => {
write!(f, "ADD PROJECTION")?;
if *if_not_exists {
write!(f, " IF NOT EXISTS")?;
}
write!(f, " {name} ({query})")
}
AlterTableOperation::Algorithm { equals, algorithm } => {
write!(
f,
"ALGORITHM {}{}",
if *equals { "= " } else { "" },
algorithm
)
}
AlterTableOperation::DropProjection { if_exists, name } => {
write!(f, "DROP PROJECTION")?;
if *if_exists {
write!(f, " IF EXISTS")?;
}
write!(f, " {name}")
}
AlterTableOperation::MaterializeProjection {
if_exists,
name,
partition,
} => {
write!(f, "MATERIALIZE PROJECTION")?;
if *if_exists {
write!(f, " IF EXISTS")?;
}
write!(f, " {name}")?;
if let Some(partition) = partition {
write!(f, " IN PARTITION {partition}")?;
}
Ok(())
}
AlterTableOperation::ClearProjection {
if_exists,
name,
partition,
} => {
write!(f, "CLEAR PROJECTION")?;
if *if_exists {
write!(f, " IF EXISTS")?;
}
write!(f, " {name}")?;
if let Some(partition) = partition {
write!(f, " IN PARTITION {partition}")?;
}
Ok(())
}
AlterTableOperation::AlterColumn { column_name, op } => {
write!(f, "ALTER COLUMN {column_name} {op}")
}
AlterTableOperation::DisableRowLevelSecurity => {
write!(f, "DISABLE ROW LEVEL SECURITY")
}
AlterTableOperation::DisableRule { name } => {
write!(f, "DISABLE RULE {name}")
}
AlterTableOperation::DisableTrigger { name } => {
write!(f, "DISABLE TRIGGER {name}")
}
AlterTableOperation::DropPartitions {
partitions,
if_exists,
} => write!(
f,
"DROP{ie} PARTITION ({})",
display_comma_separated(partitions),
ie = if *if_exists { " IF EXISTS" } else { "" }
),
AlterTableOperation::DropConstraint {
if_exists,
name,
drop_behavior,
} => {
write!(
f,
"DROP CONSTRAINT {}{}",
if *if_exists { "IF EXISTS " } else { "" },
name
)?;
if let Some(drop_behavior) = drop_behavior {
write!(f, " {drop_behavior}")?;
}
Ok(())
}
AlterTableOperation::DropPrimaryKey { drop_behavior } => {
write!(f, "DROP PRIMARY KEY")?;
if let Some(drop_behavior) = drop_behavior {
write!(f, " {drop_behavior}")?;
}
Ok(())
}
AlterTableOperation::DropForeignKey {
name,
drop_behavior,
} => {
write!(f, "DROP FOREIGN KEY {name}")?;
if let Some(drop_behavior) = drop_behavior {
write!(f, " {drop_behavior}")?;
}
Ok(())
}
AlterTableOperation::DropIndex { name } => write!(f, "DROP INDEX {name}"),
AlterTableOperation::DropColumn {
has_column_keyword,
column_names: column_name,
if_exists,
drop_behavior,
} => {
write!(
f,
"DROP {}{}{}",
if *has_column_keyword { "COLUMN " } else { "" },
if *if_exists { "IF EXISTS " } else { "" },
display_comma_separated(column_name),
)?;
if let Some(drop_behavior) = drop_behavior {
write!(f, " {drop_behavior}")?;
}
Ok(())
}
AlterTableOperation::AttachPartition { partition } => {
write!(f, "ATTACH {partition}")
}
AlterTableOperation::DetachPartition { partition } => {
write!(f, "DETACH {partition}")
}
AlterTableOperation::EnableAlwaysRule { name } => {
write!(f, "ENABLE ALWAYS RULE {name}")
}
AlterTableOperation::EnableAlwaysTrigger { name } => {
write!(f, "ENABLE ALWAYS TRIGGER {name}")
}
AlterTableOperation::EnableReplicaRule { name } => {
write!(f, "ENABLE REPLICA RULE {name}")
}
AlterTableOperation::EnableReplicaTrigger { name } => {
write!(f, "ENABLE REPLICA TRIGGER {name}")
}
AlterTableOperation::EnableRowLevelSecurity => {
write!(f, "ENABLE ROW LEVEL SECURITY")
}
AlterTableOperation::ForceRowLevelSecurity => {
write!(f, "FORCE ROW LEVEL SECURITY")
}
AlterTableOperation::NoForceRowLevelSecurity => {
write!(f, "NO FORCE ROW LEVEL SECURITY")
}
AlterTableOperation::EnableRule { name } => {
write!(f, "ENABLE RULE {name}")
}
AlterTableOperation::EnableTrigger { name } => {
write!(f, "ENABLE TRIGGER {name}")
}
AlterTableOperation::RenamePartitions {
old_partitions,
new_partitions,
} => write!(
f,
"PARTITION ({}) RENAME TO PARTITION ({})",
display_comma_separated(old_partitions),
display_comma_separated(new_partitions)
),
AlterTableOperation::RenameColumn {
old_column_name,
new_column_name,
} => write!(f, "RENAME COLUMN {old_column_name} TO {new_column_name}"),
AlterTableOperation::RenameTable { table_name } => {
write!(f, "RENAME {table_name}")
}
AlterTableOperation::ChangeColumn {
old_name,
new_name,
data_type,
options,
column_position,
} => {
write!(f, "CHANGE COLUMN {old_name} {new_name} {data_type}")?;
if !options.is_empty() {
write!(f, " {}", display_separated(options, " "))?;
}
if let Some(position) = column_position {
write!(f, " {position}")?;
}
Ok(())
}
AlterTableOperation::ModifyColumn {
col_name,
data_type,
options,
column_position,
} => {
write!(f, "MODIFY COLUMN {col_name} {data_type}")?;
if !options.is_empty() {
write!(f, " {}", display_separated(options, " "))?;
}
if let Some(position) = column_position {
write!(f, " {position}")?;
}
Ok(())
}
AlterTableOperation::RenameConstraint { old_name, new_name } => {
write!(f, "RENAME CONSTRAINT {old_name} TO {new_name}")
}
AlterTableOperation::SwapWith { table_name } => {
write!(f, "SWAP WITH {table_name}")
}
AlterTableOperation::OwnerTo { new_owner } => {
write!(f, "OWNER TO {new_owner}")
}
AlterTableOperation::SetTblProperties { table_properties } => {
write!(
f,
"SET TBLPROPERTIES({})",
display_comma_separated(table_properties)
)
}
AlterTableOperation::FreezePartition {
partition,
with_name,
} => {
write!(f, "FREEZE {partition}")?;
if let Some(name) = with_name {
write!(f, " WITH NAME {name}")?;
}
Ok(())
}
AlterTableOperation::UnfreezePartition {
partition,
with_name,
} => {
write!(f, "UNFREEZE {partition}")?;
if let Some(name) = with_name {
write!(f, " WITH NAME {name}")?;
}
Ok(())
}
AlterTableOperation::ClusterBy { exprs } => {
write!(f, "CLUSTER BY ({})", display_comma_separated(exprs))?;
Ok(())
}
AlterTableOperation::DropClusteringKey => {
write!(f, "DROP CLUSTERING KEY")?;
Ok(())