1#[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#[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 pub column: OrderByExpr,
67 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#[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 Nothing,
105 Full,
107 Default,
109 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#[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 AddConstraint {
131 constraint: TableConstraint,
133 not_valid: bool,
135 },
136 AddColumn {
138 column_keyword: bool,
140 if_not_exists: bool,
142 column_def: ColumnDef,
144 column_position: Option<MySQLColumnPosition>,
146 },
147 AddProjection {
152 if_not_exists: bool,
154 name: Ident,
156 select: ProjectionSelect,
158 },
159 DropProjection {
164 if_exists: bool,
166 name: Ident,
168 },
169 MaterializeProjection {
174 if_exists: bool,
176 name: Ident,
178 partition: Option<Ident>,
180 },
181 ClearProjection {
186 if_exists: bool,
188 name: Ident,
190 partition: Option<Ident>,
192 },
193 DisableRowLevelSecurity,
198 DisableRule {
202 name: Ident,
204 },
205 DisableTrigger {
209 name: Ident,
211 },
212 DropConstraint {
214 if_exists: bool,
216 name: Ident,
218 drop_behavior: Option<DropBehavior>,
220 },
221 DropColumn {
223 has_column_keyword: bool,
225 column_names: Vec<Ident>,
227 if_exists: bool,
229 drop_behavior: Option<DropBehavior>,
231 },
232 AttachPartition {
236 partition: Partition,
240 },
241 AttachPartitionOf {
245 partition: ObjectName,
247 for_values: ForValues,
249 },
250 DetachPartition {
254 partition: Partition,
257 },
258 DetachPartitionOf {
262 partition: ObjectName,
264 mode: Option<DetachPartitionMode>,
266 },
267 FreezePartition {
271 partition: Partition,
273 with_name: Option<Ident>,
275 },
276 UnfreezePartition {
280 partition: Partition,
282 with_name: Option<Ident>,
284 },
285 DropPrimaryKey {
290 drop_behavior: Option<DropBehavior>,
292 },
293 DropForeignKey {
298 name: Ident,
300 drop_behavior: Option<DropBehavior>,
302 },
303 DropIndex {
307 name: Ident,
309 },
310 EnableAlwaysRule {
314 name: Ident,
316 },
317 EnableAlwaysTrigger {
321 name: Ident,
323 },
324 EnableReplicaRule {
328 name: Ident,
330 },
331 EnableReplicaTrigger {
335 name: Ident,
337 },
338 EnableRowLevelSecurity,
343 ForceRowLevelSecurity,
348 NoForceRowLevelSecurity,
353 EnableRule {
357 name: Ident,
359 },
360 EnableTrigger {
364 name: Ident,
366 },
367 RenamePartitions {
369 old_partitions: Vec<Expr>,
371 new_partitions: Vec<Expr>,
373 },
374 ReplicaIdentity {
379 identity: ReplicaIdentity,
381 },
382 AddPartitions {
384 if_not_exists: bool,
386 new_partitions: Vec<Partition>,
388 },
389 DropPartitions {
391 partitions: Vec<Expr>,
393 if_exists: bool,
395 },
396 RenameColumn {
398 old_column_name: Ident,
400 new_column_name: Ident,
402 },
403 RenameTable {
405 table_name: RenameTableNameKind,
407 },
408 ChangeColumn {
411 old_name: Ident,
413 new_name: Ident,
415 data_type: DataType,
417 options: Vec<ColumnOption>,
419 column_position: Option<MySQLColumnPosition>,
421 },
422 ModifyColumn {
425 col_name: Ident,
427 data_type: DataType,
429 options: Vec<ColumnOption>,
431 column_position: Option<MySQLColumnPosition>,
433 },
434 ModifyOrderBy {
439 order_by: OneOrManyWithParens<Expr>,
441 },
442 RenameConstraint {
447 old_name: Ident,
449 new_name: Ident,
451 },
452 AlterColumn {
455 column_name: Ident,
457 op: AlterColumnOperation,
459 },
460 SwapWith {
464 table_name: ObjectName,
466 },
467 SetTblProperties {
469 table_properties: Vec<SqlOption>,
471 },
472 SetLogged,
476 SetUnlogged,
480 OwnerTo {
484 new_owner: Owner,
486 },
487 ClusterBy {
490 exprs: Vec<Expr>,
492 },
493 DropClusteringKey,
495 AlterSortKey {
498 columns: Vec<Expr>,
500 },
501 SuspendRecluster,
503 ResumeRecluster,
505 Refresh {
511 subpath: Option<String>,
513 },
514 Suspend,
518 Resume,
522 Algorithm {
528 equals: bool,
530 algorithm: AlterTableAlgorithm,
532 },
533
534 Lock {
540 equals: bool,
542 lock: AlterTableLock,
544 },
545 AutoIncrement {
551 equals: bool,
553 value: ValueWithSpan,
555 },
556 ValidateConstraint {
558 name: Ident,
560 },
561 Inherit {
565 parent: ObjectName,
567 },
568 NoInherit {
572 parent: ObjectName,
574 },
575 SetOptionsParens {
583 options: Vec<SqlOption>,
585 },
586 ResetOptions {
593 options: Vec<ObjectName>,
595 },
596 GenericOptions {
601 options: Vec<AlterGenericOption>,
603 },
604}
605
606#[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 {
615 new_name: Ident,
617 },
618 Apply {
620 to: Option<Vec<Owner>>,
622 using: Option<Expr>,
624 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#[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 {
664 new_name: Ident,
666 },
667 DependsOnExtension {
669 no: bool,
671 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#[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))]
698pub enum AlterTableAlgorithm {
700 Default,
702 Instant,
704 Inplace,
706 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#[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))]
727pub enum AlterTableLock {
729 Default,
731 None,
733 Shared,
735 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))]
753pub enum Owner {
755 Ident(Ident),
757 CurrentRole,
759 CurrentUser,
761 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))]
779pub enum AlterConnectorOwner {
781 User(Ident),
783 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))]
799pub enum AlterIndexOperation {
801 RenameIndex {
803 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#[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 pub name: ObjectName,
1202 pub operation: AlterTypeOperation,
1204}
1205
1206#[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(AlterTypeRename),
1213 AddValue(AlterTypeAddValue),
1215 RenameValue(AlterTypeRenameValue),
1217}
1218
1219#[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 pub new_name: Ident,
1226}
1227
1228#[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 pub if_not_exists: bool,
1235 pub value: Ident,
1237 pub position: Option<AlterTypeAddValuePosition>,
1239}
1240
1241#[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 Before(Ident),
1248 After(Ident),
1250}
1251
1252#[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 pub from: Ident,
1259 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#[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 pub name: ObjectName,
1305 pub left_type: Option<DataType>,
1307 pub right_type: DataType,
1309 pub operation: AlterOperatorOperation,
1311}
1312
1313#[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 OwnerTo(Owner),
1320 SetSchema {
1323 schema_name: ObjectName,
1325 },
1326 Set {
1328 options: Vec<OperatorOption>,
1330 },
1331}
1332
1333#[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(Option<ObjectName>),
1340 Join(Option<ObjectName>),
1342 Commutator(ObjectName),
1344 Negator(ObjectName),
1346 Hashes,
1348 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#[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 SetNotNull,
1405 DropNotNull,
1407 SetDefault {
1410 value: Expr,
1412 },
1413 DropDefault,
1415 SetDataType {
1417 data_type: DataType,
1419 using: Option<Expr>,
1421 had_set: bool,
1423 },
1424
1425 AddGenerated {
1429 generated_as: Option<GeneratedAs>,
1431 sequence_options: Option<Vec<SequenceOptions>>,
1433 },
1434 GenericOptions {
1439 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#[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 {
1508 option: CreateServerOption,
1510 add_keyword: bool,
1512 },
1513 Set(CreateServerOption),
1515 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#[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 None,
1550 Key,
1552 Index,
1554}
1555
1556impl KeyOrIndexDisplay {
1557 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#[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 BTree,
1599 Hash,
1601 GIN,
1603 GiST,
1605 SPGiST,
1607 BRIN,
1609 Bloom,
1611 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#[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(IndexType),
1644 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#[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 None,
1666 Distinct,
1668 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))]
1685pub struct ProcedureParam {
1687 pub name: Ident,
1689 pub data_type: DataType,
1691 pub mode: Option<ArgMode>,
1693 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#[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 pub name: Ident,
1720 pub data_type: DataType,
1722 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#[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 pub name: Ident,
1762 pub data_type: Option<DataType>,
1764 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))]
1771pub enum ColumnOptions {
1773 CommaSeparated(Vec<ColumnOption>),
1775 SpaceSeparated(Vec<ColumnOption>),
1777}
1778
1779impl ColumnOptions {
1780 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#[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 pub name: Option<Ident>,
1831 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#[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 Autoincrement(IdentityProperty),
1860 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#[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 pub parameters: Option<IdentityPropertyFormatKind>,
1899 pub order: Option<IdentityPropertyOrder>,
1901}
1902
1903#[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 FunctionCall(IdentityParameters),
1929 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#[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 pub seed: Expr,
1961 pub increment: Expr,
1963}
1964
1965#[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,
1977 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#[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 MaskingPolicy(ColumnPolicyProperty),
2003 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))]
2027pub struct ColumnPolicyProperty {
2029 pub with: bool,
2036 pub policy_name: ObjectName,
2038 pub using_columns: Option<Vec<Ident>>,
2040}
2041
2042#[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 pub with: bool,
2059 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#[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,
2081 NotNull,
2083 Default(Expr),
2085
2086 Materialized(Expr),
2091 Ephemeral(Option<Expr>),
2095 Alias(Expr),
2099
2100 PrimaryKey(PrimaryKeyConstraint),
2102 Unique(UniqueConstraint),
2104 ForeignKey(ForeignKeyConstraint),
2112 Check(CheckConstraint),
2114 DialectSpecific(Vec<Token>),
2118 CharacterSet(ObjectName),
2120 Collation(ObjectName),
2122 Comment(String),
2124 OnUpdate(Expr),
2126 Generated {
2129 generated_as: GeneratedAs,
2131 sequence_options: Option<Vec<SequenceOptions>>,
2133 generation_expr: Option<Expr>,
2135 generation_expr_mode: Option<GeneratedExpressionMode>,
2137 generated_keyword: bool,
2139 },
2140 Options(Vec<SqlOption>),
2148 GenericOptions(Vec<CreateServerOption>),
2153 Identity(IdentityPropertyKind),
2161 OnConflict(Keyword),
2164 Policy(ColumnPolicy),
2172 Tags(TagsColumnOption),
2179 Srid(Box<Expr>),
2186 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 let when = match generated_as {
2303 GeneratedAs::Always => "ALWAYS",
2304 GeneratedAs::ByDefault => "BY DEFAULT",
2305 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#[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 Always,
2360 ByDefault,
2362 ExpStored,
2364}
2365
2366#[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,
2374 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#[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#[must_use]
2418pub(crate) fn display_option_spaced<T: fmt::Display>(option: &Option<T>) -> impl fmt::Display + '_ {
2419 display_option(" ", "", option)
2420}
2421
2422#[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 pub deferrable: Option<bool>,
2431 pub initially: Option<DeferrableInitial>,
2433 pub enforced: Option<bool>,
2435}
2436
2437#[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 Immediate,
2444 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#[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,
2511 Cascade,
2513 SetNull,
2515 NoAction,
2517 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#[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,
2542 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#[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,
2562 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#[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 {
2582 attributes: Vec<UserDefinedTypeCompositeAttributeDef>,
2584 },
2585 Enum {
2590 labels: Vec<Ident>,
2592 },
2593 Range {
2597 options: Vec<UserDefinedTypeRangeOption>,
2599 },
2600 SqlDefinition {
2606 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#[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 pub name: Ident,
2637 pub data_type: DataType,
2639 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#[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(u64),
2681 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#[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 Char,
2718 Int2,
2720 Int4,
2722 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#[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 Plain,
2762 External,
2764 Extended,
2766 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#[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 Subtype(DataType),
2804 SubtypeOpClass(ObjectName),
2806 Collation(ObjectName),
2808 Canonical(ObjectName),
2810 SubtypeDiff(ObjectName),
2812 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#[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 Input(ObjectName),
2859 Output(ObjectName),
2861 Receive(ObjectName),
2863 Send(ObjectName),
2865 TypmodIn(ObjectName),
2867 TypmodOut(ObjectName),
2869 Analyze(ObjectName),
2871 Subscript(ObjectName),
2873 InternalLength(UserDefinedTypeInternalLength),
2875 PassedByValue,
2877 Alignment(Alignment),
2879 Storage(UserDefinedTypeStorage),
2881 Like(ObjectName),
2883 Category(char),
2885 Preferred(bool),
2887 Default(Expr),
2889 Element(DataType),
2891 Delimiter(String),
2893 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#[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 Identifier(Ident),
2944 Expr(Expr),
2946 Part(Expr),
2949 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#[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 All,
2974 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#[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 pub columns: Vec<Ident>,
2997 pub sorted_by: Option<Vec<OrderByExpr>>,
2999 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#[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 pub name: Option<ObjectName>,
3024 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3025 pub table_name: ObjectName,
3027 pub using: Option<IndexType>,
3030 pub columns: Vec<IndexColumn>,
3032 pub unique: bool,
3034 pub concurrently: bool,
3036 pub r#async: bool,
3040 pub if_not_exists: bool,
3042 pub include: Vec<Ident>,
3044 pub nulls_distinct: Option<bool>,
3046 pub with: Vec<Expr>,
3048 pub predicate: Option<Expr>,
3050 pub index_options: Vec<IndexOption>,
3052 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#[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 WithoutRowid,
3123 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#[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 pub leading_comma: bool,
3144 pub options: Vec<SqliteTableOption>,
3146}
3147
3148#[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 pub or_replace: bool,
3155 pub temporary: bool,
3157 pub unlogged: bool,
3159 pub external: bool,
3161 pub dynamic: bool,
3163 pub global: Option<bool>,
3165 pub if_not_exists: bool,
3167 pub transient: bool,
3169 pub volatile: bool,
3171 pub iceberg: bool,
3173 pub snapshot: bool,
3176 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3178 pub name: ObjectName,
3179 pub columns: Vec<ColumnDef>,
3181 pub constraints: Vec<TableConstraint>,
3183 pub hive_distribution: HiveDistributionStyle,
3185 pub hive_formats: Option<HiveFormat>,
3187 pub table_options: CreateTableOptions,
3189 pub file_format: Option<FileFormat>,
3191 pub location: Option<String>,
3193 pub query: Option<Box<Query>>,
3195 pub sqlite_table_options: SqliteTableOptions,
3197 pub like: Option<CreateTableLikeKind>,
3199 pub clone: Option<ObjectName>,
3201 pub version: Option<TableVersion>,
3203 pub comment: Option<CommentDef>,
3207 pub on_commit: Option<OnCommit>,
3210 pub on_cluster: Option<Ident>,
3213 pub primary_key: Option<Box<Expr>>,
3216 pub order_by: Option<OneOrManyWithParens<Expr>>,
3220 pub partition_by: Option<Box<Expr>>,
3223 pub cluster_by: Option<WrappedCollection<Vec<Expr>>>,
3228 pub clustered_by: Option<ClusteredBy>,
3231 pub inherits: Option<Vec<ObjectName>>,
3236 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3240 pub partition_of: Option<ObjectName>,
3241 pub for_values: Option<ForValues>,
3244 pub copy_grants: bool,
3247 pub enable_schema_evolution: Option<bool>,
3250 pub change_tracking: Option<bool>,
3253 pub data_retention_time_in_days: Option<u64>,
3256 pub max_data_extension_time_in_days: Option<u64>,
3259 pub default_ddl_collation: Option<String>,
3262 pub with_aggregation_policy: Option<ObjectName>,
3265 pub with_row_access_policy: Option<RowAccessPolicy>,
3268 pub with_storage_lifecycle_policy: Option<StorageLifecyclePolicy>,
3271 pub with_tags: Option<Vec<Tag>>,
3274 pub external_volume: Option<String>,
3277 pub with_connection: Option<ObjectName>,
3280 pub base_location: Option<String>,
3283 pub catalog: Option<String>,
3286 pub catalog_sync: Option<String>,
3289 pub storage_serialization_policy: Option<StorageSerializationPolicy>,
3292 pub target_lag: Option<String>,
3295 pub warehouse: Option<Ident>,
3298 pub refresh_mode: Option<RefreshModeKind>,
3301 pub initialize: Option<InitializeKind>,
3304 pub require_user: bool,
3307 pub diststyle: Option<DistStyle>,
3310 pub distkey: Option<Expr>,
3313 pub sortkey: Option<Vec<Expr>>,
3316 pub backup: Option<bool>,
3319 pub multiset: Option<bool>,
3324 pub fallback: Option<bool>,
3329 pub with_data: Option<WithData>,
3333}
3334
3335impl fmt::Display for CreateTable {
3336 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3337 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 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 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#[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 pub data: bool,
3681 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#[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 In(Vec<Expr>),
3715 From {
3717 from: Vec<PartitionBoundValue>,
3719 to: Vec<PartitionBoundValue>,
3721 },
3722 With {
3724 modulus: u64,
3726 remainder: u64,
3728 },
3729 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#[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 Expr(Expr),
3768 MinValue,
3770 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#[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 Auto,
3793 Even,
3795 Key,
3797 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))]
3815pub struct CreateDomain {
3828 pub name: ObjectName,
3830 pub data_type: DataType,
3832 pub collation: Option<Ident>,
3834 pub default: Option<Expr>,
3836 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#[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 DataType(DataType),
3868 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))]
3886pub struct CreateFunction {
3888 pub or_alter: bool,
3892 pub or_replace: bool,
3894 pub temporary: bool,
3896 pub if_not_exists: bool,
3898 pub name: ObjectName,
3900 pub args: Option<Vec<OperateFunctionArg>>,
3902 pub return_type: Option<FunctionReturnType>,
3904 pub function_body: Option<CreateFunctionBody>,
3912 pub behavior: Option<FunctionBehavior>,
3918 pub called_on_null: Option<FunctionCalledOnNull>,
3922 pub parallel: Option<FunctionParallel>,
3926 pub security: Option<FunctionSecurity>,
3930 pub set_params: Vec<FunctionDefinitionSetParam>,
3934 pub using: Option<CreateFunctionUsing>,
3936 pub language: Option<Ident>,
3944 pub determinism_specifier: Option<FunctionDeterminismSpecifier>,
3948 pub options: Option<Vec<SqlOption>>,
3952 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#[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 pub name: Ident,
4065 pub if_not_exists: bool,
4067 pub connector_type: Option<String>,
4069 pub url: Option<String>,
4071 pub comment: Option<CommentDef>,
4073 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#[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 SetDefaultCollate {
4124 collate: Expr,
4126 },
4127 AddReplica {
4129 replica: Ident,
4131 options: Option<Vec<SqlOption>>,
4133 },
4134 DropReplica {
4136 replica: Ident,
4138 },
4139 SetOptionsParens {
4141 options: Vec<SqlOption>,
4143 },
4144 Rename {
4146 name: ObjectName,
4148 },
4149 OwnerTo {
4151 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#[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(ObjectName),
4189 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))]
4205pub struct AlterSchema {
4207 pub name: ObjectName,
4209 pub if_exists: bool,
4211 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))]
4242pub enum TriggerObjectKind {
4244 For(TriggerObject),
4246 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))]
4262pub struct CreateTrigger {
4276 pub or_alter: bool,
4280 pub temporary: bool,
4297 pub or_replace: bool,
4307 pub is_constraint: bool,
4309 pub name: ObjectName,
4311 pub period: Option<TriggerPeriod>,
4340 pub period_before_table: bool,
4351 pub events: Vec<TriggerEvent>,
4353 pub table_name: ObjectName,
4355 pub referenced_table_name: Option<ObjectName>,
4358 pub referencing: Vec<TriggerReferencing>,
4360 pub trigger_object: Option<TriggerObjectKind>,
4365 pub condition: Option<Expr>,
4367 pub exec_body: Option<TriggerExecBody>,
4369 pub statements_as: bool,
4371 pub statements: Option<ConditionalStatements>,
4373 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))]
4459pub struct DropTrigger {
4466 pub if_exists: bool,
4468 pub trigger_name: ObjectName,
4470 pub table_name: Option<ObjectName>,
4472 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#[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 pub table_names: Vec<super::TruncateTableTarget>,
4510 pub partitions: Option<Vec<Expr>>,
4512 pub table: bool,
4514 pub if_exists: bool,
4516 pub identity: Option<super::TruncateIdentityOption>,
4518 pub cascade: Option<super::CascadeOption>,
4520 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#[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 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4585 pub table_name: ObjectName,
4586 pub repair: bool,
4588 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#[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 pub or_alter: bool,
4622 pub or_replace: bool,
4624 pub materialized: bool,
4626 pub secure: bool,
4629 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4631 pub name: ObjectName,
4632 pub name_before_not_exists: bool,
4643 pub columns: Vec<ViewColumnDef>,
4645 pub query: Box<Query>,
4647 pub options: CreateTableOptions,
4649 pub cluster_by: Vec<Ident>,
4651 pub comment: Option<String>,
4654 pub with_no_schema_binding: bool,
4656 pub if_not_exists: bool,
4658 pub temporary: bool,
4660 pub copy_grants: bool,
4663 pub to: Option<ObjectName>,
4666 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#[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 pub name: Ident,
4746 pub if_not_exists: bool,
4748 pub with_keyword: bool,
4750 pub cascade: bool,
4752 pub schema: Option<Ident>,
4754 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#[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 pub names: Vec<Ident>,
4806 pub if_exists: bool,
4808 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#[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 pub if_not_exists: bool,
4840 pub name: ObjectName,
4842 pub definition: CreateCollationDefinition,
4844}
4845
4846#[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 From(ObjectName),
4857 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#[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 pub name: ObjectName,
4902 pub operation: AlterCollationOperation,
4904}
4905
4906#[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 RenameTo {
4917 new_name: Ident,
4919 },
4920 OwnerTo(Owner),
4926 SetSchema {
4932 schema_name: ObjectName,
4934 },
4935 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#[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 pub materialized: bool,
4978 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4980 pub name: ObjectName,
4981 pub if_exists: bool,
4983 pub operation: AlterViewOperation,
4985}
4986
4987#[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 As {
5002 columns: Vec<Ident>,
5004 query: Box<Query>,
5006 with_options: Vec<SqlOption>,
5008 },
5009 AlterColumn {
5013 column_name: Ident,
5015 op: AlterColumnOperation,
5017 },
5018 OwnerTo(Owner),
5022 RenameColumn {
5026 old_column_name: Ident,
5028 new_column_name: Ident,
5030 },
5031 RenameTo {
5035 new_name: ObjectName,
5037 },
5038 SetSchema {
5042 schema_name: ObjectName,
5044 },
5045 SetOptions {
5049 options: Vec<SqlOption>,
5051 },
5052 ResetOptions {
5056 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#[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,
5122 Dynamic,
5125 External,
5128 Foreign,
5131}
5132
5133#[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 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5140 pub name: ObjectName,
5141 pub if_exists: bool,
5143 pub only: bool,
5145 pub operations: Vec<AlterTableOperation>,
5147 pub location: Option<HiveSetLocation>,
5149 pub on_cluster: Option<Ident>,
5153 pub table_type: Option<AlterTableType>,
5155 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#[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 pub if_exists: bool,
5194 pub func_desc: Vec<FunctionDesc>,
5196 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#[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 pub name: ObjectName,
5229 pub function: ObjectName,
5231 pub is_procedure: bool,
5233 pub left_arg: Option<DataType>,
5235 pub right_arg: Option<DataType>,
5237 pub options: Vec<OperatorOption>,
5239}
5240
5241#[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 pub name: ObjectName,
5249 pub using: Ident,
5251}
5252
5253#[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 pub name: ObjectName,
5261 pub default: bool,
5263 pub for_type: DataType,
5265 pub using: Ident,
5267 pub family: Option<ObjectName>,
5269 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#[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 pub left: DataType,
5331 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#[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 {
5348 strategy_number: u64,
5350 operator_name: ObjectName,
5352 op_types: Option<OperatorArgTypes>,
5354 purpose: Option<OperatorPurpose>,
5356 },
5357 Function {
5359 support_number: u64,
5361 op_types: Option<Vec<DataType>>,
5363 function_name: ObjectName,
5365 argument_types: Vec<DataType>,
5367 },
5368 Storage {
5370 storage_type: DataType,
5372 },
5373}
5374
5375#[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 ForSearch,
5382 ForOrderBy {
5384 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#[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 pub if_exists: bool,
5445 pub operators: Vec<DropOperatorSignature>,
5447 pub drop_behavior: Option<DropBehavior>,
5449}
5450
5451#[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 pub name: ObjectName,
5458 pub left_type: Option<DataType>,
5460 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#[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 pub if_exists: bool,
5504 pub names: Vec<ObjectName>,
5506 pub using: Ident,
5508 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#[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 pub if_exists: bool,
5541 pub names: Vec<ObjectName>,
5543 pub using: Ident,
5545 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#[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 {
5577 strategy_number: u64,
5579 operator_name: ObjectName,
5581 op_types: Vec<DataType>,
5583 purpose: Option<OperatorPurpose>,
5585 },
5586 Function {
5588 support_number: u64,
5590 op_types: Option<Vec<DataType>>,
5592 function_name: ObjectName,
5594 argument_types: Vec<DataType>,
5596 },
5597}
5598
5599#[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 {
5606 strategy_number: u64,
5608 op_types: Vec<DataType>,
5610 },
5611 Function {
5613 support_number: u64,
5615 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#[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 pub name: ObjectName,
5708 pub using: Ident,
5710 pub operation: AlterOperatorFamilyOperation,
5712}
5713
5714#[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 {
5721 items: Vec<OperatorFamilyItem>,
5723 },
5724 Drop {
5726 items: Vec<OperatorFamilyDropItem>,
5728 },
5729 RenameTo {
5731 new_name: ObjectName,
5733 },
5734 OwnerTo(Owner),
5736 SetSchema {
5738 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#[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 pub name: ObjectName,
5790 pub using: Ident,
5792 pub operation: AlterOperatorClassOperation,
5794}
5795
5796#[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 RenameTo {
5804 new_name: ObjectName,
5806 },
5807 OwnerTo(Owner),
5809 SetSchema {
5812 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#[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 pub kind: AlterFunctionKind,
5853 pub function: FunctionDesc,
5855 pub aggregate_order_by: Option<Vec<OperateFunctionArg>>,
5859 pub aggregate_star: bool,
5863 pub operation: AlterFunctionOperation,
5865}
5866
5867#[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,
5874 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#[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 RenameTo {
5894 new_name: Ident,
5896 },
5897 OwnerTo(Owner),
5899 SetSchema {
5901 schema_name: ObjectName,
5903 },
5904 DependsOnExtension {
5906 no: bool,
5908 extension_name: ObjectName,
5910 },
5911 Actions {
5913 actions: Vec<AlterFunctionAction>,
5915 restrict: bool,
5917 },
5918}
5919
5920#[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 CalledOnNull(FunctionCalledOnNull),
5927 Behavior(FunctionBehavior),
5929 Leakproof(bool),
5931 Security {
5933 external: bool,
5935 security: FunctionSecurity,
5937 },
5938 Parallel(FunctionParallel),
5940 Cost(Expr),
5942 Rows(Expr),
5944 Support(ObjectName),
5946 Set(FunctionDefinitionSetParam),
5949 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#[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,
6063 Configuration,
6065 Template,
6067 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#[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 pub object_type: TextSearchObjectType,
6091 pub name: ObjectName,
6093 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#[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 pub key: Ident,
6124 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#[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 RenameTo {
6146 new_name: Ident,
6148 },
6149 OwnerTo(Owner),
6151 SetSchema {
6153 schema_name: ObjectName,
6155 },
6156 SetOptions {
6158 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#[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 pub object_type: TextSearchObjectType,
6187 pub name: ObjectName,
6189 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#[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 pub name: Ident,
6218 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6220 pub table_name: ObjectName,
6221 pub policy_type: Option<CreatePolicyType>,
6223 pub command: Option<CreatePolicyCommand>,
6225 pub to: Option<Vec<Owner>>,
6227 pub using: Option<Expr>,
6229 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#[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 Permissive,
6271 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#[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 All,
6295 Select,
6297 Insert,
6299 Update,
6301 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#[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 pub if_exists: bool,
6326 pub name: Ident,
6328 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6330 pub table_name: ObjectName,
6331 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#[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 pub name: Ident,
6375 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6377 pub table_name: ObjectName,
6378 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#[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 pub name: Ident,
6414 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6416 pub table_name: ObjectName,
6417 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#[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 pub or_replace: bool,
6454 pub name: Ident,
6456 pub event: CreateRuleEvent,
6458 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6460 pub table_name: ObjectName,
6461 pub condition: Option<Expr>,
6463 pub do_kind: Option<CreateRuleDoKind>,
6465 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#[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 Select,
6501 Insert,
6503 Update,
6505 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#[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 Also,
6531 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#[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,
6555 Statement(Box<Statement>),
6557 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#[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 pub if_exists: bool,
6594 pub name: Ident,
6596 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6598 pub table_name: ObjectName,
6599 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#[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 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6628 pub name: ObjectName,
6629 pub if_not_exists: bool,
6631 pub columns: Vec<ColumnDef>,
6633 pub constraints: Vec<TableConstraint>,
6637 pub inherits: Option<Vec<ObjectName>>,
6639 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6641 pub partition_of: Option<ObjectName>,
6642 pub for_values: Option<ForValues>,
6644 pub server_name: Ident,
6646 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 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#[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(ObjectName),
6694 NoHandler,
6696 Validator(ObjectName),
6698 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#[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 pub name: Ident,
6723 pub routines: Vec<ForeignDataWrapperRoutineClause>,
6726 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#[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 pub or_replace: bool,
6783 pub name: ObjectName,
6785 pub args: CreateAggregateArgs,
6787 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#[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 Legacy,
6823 Star,
6826 List(Vec<OperateFunctionArg>),
6829 OrderedSet {
6831 direct: Vec<OperateFunctionArg>,
6833 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#[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 StateTransitionFunction(ObjectName),
6853 StateDataType(DataType),
6855 StateDataSize(u64),
6857 FinalFunction(ObjectName),
6859 FinalFunctionExtra,
6861 FinalFunctionModify(AggregateModifyKind),
6863 CombineFunction(ObjectName),
6865 SerialFunction(ObjectName),
6867 DeserialFunction(ObjectName),
6869 InitialCondition(ValueWithSpan),
6871 MovingStateTransitionFunction(ObjectName),
6873 MovingInverseTransitionFunction(ObjectName),
6875 MovingStateDataType(DataType),
6877 MovingStateDataSize(u64),
6879 MovingFinalFunction(ObjectName),
6881 MovingFinalFunctionExtra,
6883 MovingFinalFunctionModify(AggregateModifyKind),
6885 MovingInitialCondition(ValueWithSpan),
6887 SortOperator(ObjectName),
6889 Parallel(FunctionParallel),
6891 Hypothetical,
6893 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#[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 ReadOnly,
6938 Shareable,
6940 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#[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 Name(Ident),
6986 User,
6988 CurrentRole,
6990 CurrentUser,
6992 SessionUser,
6994 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#[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 pub if_not_exists: bool,
7020 pub user: UserMappingUser,
7022 pub server_name: Ident,
7024 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}