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,
40 table_constraints::{
41 CheckConstraint, ForeignKeyConstraint, PrimaryKeyConstraint, TableConstraint,
42 UniqueConstraint,
43 },
44 ArgMode, AttachedToken, CommentDef, ConditionalStatements, CreateFunctionBody,
45 CreateFunctionUsing, CreateServerOption, CreateTableLikeKind, CreateTableOptions,
46 CreateViewParams, DataType, Expr, FileFormat, FunctionBehavior, FunctionCalledOnNull,
47 FunctionDefinitionSetParam, FunctionDesc, FunctionDeterminismSpecifier, FunctionParallel,
48 FunctionSecurity, HiveDistributionStyle, HiveFormat, HiveIOFormat, HiveRowFormat,
49 HiveSetLocation, Ident, InitializeKind, MySQLColumnPosition, ObjectName, OnCommit,
50 OneOrManyWithParens, OperateFunctionArg, OrderByExpr, ProjectionSelect, Query, RefreshModeKind,
51 ResetConfig, RowAccessPolicy, SequenceOptions, Spanned, SqlOption, StorageLifecyclePolicy,
52 StorageSerializationPolicy, TableVersion, Tag, TriggerEvent, TriggerExecBody, TriggerObject,
53 TriggerPeriod, TriggerReferencing, Value, ValueWithSpan, WrappedCollection,
54};
55use crate::display_utils::{DisplayCommaSeparated, Indent, NewLine, SpaceOrNewline};
56use crate::keywords::Keyword;
57use crate::tokenizer::{Span, Token};
58
59#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
61#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
62#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
63pub struct IndexColumn {
64 pub column: OrderByExpr,
66 pub operator_class: Option<ObjectName>,
68}
69
70impl From<Ident> for IndexColumn {
71 fn from(c: Ident) -> Self {
72 Self {
73 column: OrderByExpr::from(c),
74 operator_class: None,
75 }
76 }
77}
78
79impl<'a> From<&'a str> for IndexColumn {
80 fn from(c: &'a str) -> Self {
81 let ident = Ident::new(c);
82 ident.into()
83 }
84}
85
86impl fmt::Display for IndexColumn {
87 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
88 write!(f, "{}", self.column)?;
89 if let Some(operator_class) = &self.operator_class {
90 write!(f, " {operator_class}")?;
91 }
92 Ok(())
93 }
94}
95
96#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
99#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
100#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
101pub enum ReplicaIdentity {
102 Nothing,
104 Full,
106 Default,
108 Index(Ident),
110}
111
112impl fmt::Display for ReplicaIdentity {
113 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
114 match self {
115 ReplicaIdentity::Nothing => f.write_str("NOTHING"),
116 ReplicaIdentity::Full => f.write_str("FULL"),
117 ReplicaIdentity::Default => f.write_str("DEFAULT"),
118 ReplicaIdentity::Index(idx) => write!(f, "USING INDEX {idx}"),
119 }
120 }
121}
122
123#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
125#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
126#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
127pub enum AlterTableOperation {
128 AddConstraint {
130 constraint: TableConstraint,
132 not_valid: bool,
134 },
135 AddColumn {
137 column_keyword: bool,
139 if_not_exists: bool,
141 column_def: ColumnDef,
143 column_position: Option<MySQLColumnPosition>,
145 },
146 AddProjection {
151 if_not_exists: bool,
153 name: Ident,
155 select: ProjectionSelect,
157 },
158 DropProjection {
163 if_exists: bool,
165 name: Ident,
167 },
168 MaterializeProjection {
173 if_exists: bool,
175 name: Ident,
177 partition: Option<Ident>,
179 },
180 ClearProjection {
185 if_exists: bool,
187 name: Ident,
189 partition: Option<Ident>,
191 },
192 DisableRowLevelSecurity,
197 DisableRule {
201 name: Ident,
203 },
204 DisableTrigger {
208 name: Ident,
210 },
211 DropConstraint {
213 if_exists: bool,
215 name: Ident,
217 drop_behavior: Option<DropBehavior>,
219 },
220 DropColumn {
222 has_column_keyword: bool,
224 column_names: Vec<Ident>,
226 if_exists: bool,
228 drop_behavior: Option<DropBehavior>,
230 },
231 AttachPartition {
235 partition: Partition,
239 },
240 DetachPartition {
244 partition: Partition,
247 },
248 FreezePartition {
252 partition: Partition,
254 with_name: Option<Ident>,
256 },
257 UnfreezePartition {
261 partition: Partition,
263 with_name: Option<Ident>,
265 },
266 DropPrimaryKey {
271 drop_behavior: Option<DropBehavior>,
273 },
274 DropForeignKey {
279 name: Ident,
281 drop_behavior: Option<DropBehavior>,
283 },
284 DropIndex {
288 name: Ident,
290 },
291 EnableAlwaysRule {
295 name: Ident,
297 },
298 EnableAlwaysTrigger {
302 name: Ident,
304 },
305 EnableReplicaRule {
309 name: Ident,
311 },
312 EnableReplicaTrigger {
316 name: Ident,
318 },
319 EnableRowLevelSecurity,
324 ForceRowLevelSecurity,
329 NoForceRowLevelSecurity,
334 EnableRule {
338 name: Ident,
340 },
341 EnableTrigger {
345 name: Ident,
347 },
348 RenamePartitions {
350 old_partitions: Vec<Expr>,
352 new_partitions: Vec<Expr>,
354 },
355 ReplicaIdentity {
360 identity: ReplicaIdentity,
362 },
363 AddPartitions {
365 if_not_exists: bool,
367 new_partitions: Vec<Partition>,
369 },
370 DropPartitions {
372 partitions: Vec<Expr>,
374 if_exists: bool,
376 },
377 RenameColumn {
379 old_column_name: Ident,
381 new_column_name: Ident,
383 },
384 RenameTable {
386 table_name: RenameTableNameKind,
388 },
389 ChangeColumn {
392 old_name: Ident,
394 new_name: Ident,
396 data_type: DataType,
398 options: Vec<ColumnOption>,
400 column_position: Option<MySQLColumnPosition>,
402 },
403 ModifyColumn {
406 col_name: Ident,
408 data_type: DataType,
410 options: Vec<ColumnOption>,
412 column_position: Option<MySQLColumnPosition>,
414 },
415 ModifyOrderBy {
420 order_by: OneOrManyWithParens<Expr>,
422 },
423 RenameConstraint {
428 old_name: Ident,
430 new_name: Ident,
432 },
433 AlterColumn {
436 column_name: Ident,
438 op: AlterColumnOperation,
440 },
441 SwapWith {
445 table_name: ObjectName,
447 },
448 SetTblProperties {
450 table_properties: Vec<SqlOption>,
452 },
453 SetLogged,
457 SetUnlogged,
461 OwnerTo {
465 new_owner: Owner,
467 },
468 ClusterBy {
471 exprs: Vec<Expr>,
473 },
474 DropClusteringKey,
476 AlterSortKey {
479 columns: Vec<Expr>,
481 },
482 SuspendRecluster,
484 ResumeRecluster,
486 Refresh {
492 subpath: Option<String>,
494 },
495 Suspend,
499 Resume,
503 Algorithm {
509 equals: bool,
511 algorithm: AlterTableAlgorithm,
513 },
514
515 Lock {
521 equals: bool,
523 lock: AlterTableLock,
525 },
526 AutoIncrement {
532 equals: bool,
534 value: ValueWithSpan,
536 },
537 ValidateConstraint {
539 name: Ident,
541 },
542 SetOptionsParens {
550 options: Vec<SqlOption>,
552 },
553}
554
555#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
559#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
560#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
561pub enum AlterPolicyOperation {
562 Rename {
564 new_name: Ident,
566 },
567 Apply {
569 to: Option<Vec<Owner>>,
571 using: Option<Expr>,
573 with_check: Option<Expr>,
575 },
576}
577
578impl fmt::Display for AlterPolicyOperation {
579 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
580 match self {
581 AlterPolicyOperation::Rename { new_name } => {
582 write!(f, " RENAME TO {new_name}")
583 }
584 AlterPolicyOperation::Apply {
585 to,
586 using,
587 with_check,
588 } => {
589 if let Some(to) = to {
590 write!(f, " TO {}", display_comma_separated(to))?;
591 }
592 if let Some(using) = using {
593 write!(f, " USING ({using})")?;
594 }
595 if let Some(with_check) = with_check {
596 write!(f, " WITH CHECK ({with_check})")?;
597 }
598 Ok(())
599 }
600 }
601 }
602}
603
604#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
608#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
609#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
610pub enum AlterTableAlgorithm {
612 Default,
614 Instant,
616 Inplace,
618 Copy,
620}
621
622impl fmt::Display for AlterTableAlgorithm {
623 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
624 f.write_str(match self {
625 Self::Default => "DEFAULT",
626 Self::Instant => "INSTANT",
627 Self::Inplace => "INPLACE",
628 Self::Copy => "COPY",
629 })
630 }
631}
632
633#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
637#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
638#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
639pub enum AlterTableLock {
641 Default,
643 None,
645 Shared,
647 Exclusive,
649}
650
651impl fmt::Display for AlterTableLock {
652 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
653 f.write_str(match self {
654 Self::Default => "DEFAULT",
655 Self::None => "NONE",
656 Self::Shared => "SHARED",
657 Self::Exclusive => "EXCLUSIVE",
658 })
659 }
660}
661
662#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
663#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
664#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
665pub enum Owner {
667 Ident(Ident),
669 CurrentRole,
671 CurrentUser,
673 SessionUser,
675}
676
677impl fmt::Display for Owner {
678 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
679 match self {
680 Owner::Ident(ident) => write!(f, "{ident}"),
681 Owner::CurrentRole => write!(f, "CURRENT_ROLE"),
682 Owner::CurrentUser => write!(f, "CURRENT_USER"),
683 Owner::SessionUser => write!(f, "SESSION_USER"),
684 }
685 }
686}
687
688#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
689#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
690#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
691pub enum AlterConnectorOwner {
693 User(Ident),
695 Role(Ident),
697}
698
699impl fmt::Display for AlterConnectorOwner {
700 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
701 match self {
702 AlterConnectorOwner::User(ident) => write!(f, "USER {ident}"),
703 AlterConnectorOwner::Role(ident) => write!(f, "ROLE {ident}"),
704 }
705 }
706}
707
708#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
709#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
710#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
711pub enum AlterIndexOperation {
713 RenameIndex {
715 index_name: ObjectName,
717 },
718}
719
720impl fmt::Display for AlterTableOperation {
721 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
722 match self {
723 AlterTableOperation::AddPartitions {
724 if_not_exists,
725 new_partitions,
726 } => write!(
727 f,
728 "ADD{ine} {}",
729 display_separated(new_partitions, " "),
730 ine = if *if_not_exists { " IF NOT EXISTS" } else { "" }
731 ),
732 AlterTableOperation::AddConstraint {
733 not_valid,
734 constraint,
735 } => {
736 write!(f, "ADD {constraint}")?;
737 if *not_valid {
738 write!(f, " NOT VALID")?;
739 }
740 Ok(())
741 }
742 AlterTableOperation::AddColumn {
743 column_keyword,
744 if_not_exists,
745 column_def,
746 column_position,
747 } => {
748 write!(f, "ADD")?;
749 if *column_keyword {
750 write!(f, " COLUMN")?;
751 }
752 if *if_not_exists {
753 write!(f, " IF NOT EXISTS")?;
754 }
755 write!(f, " {column_def}")?;
756
757 if let Some(position) = column_position {
758 write!(f, " {position}")?;
759 }
760
761 Ok(())
762 }
763 AlterTableOperation::AddProjection {
764 if_not_exists,
765 name,
766 select: query,
767 } => {
768 write!(f, "ADD PROJECTION")?;
769 if *if_not_exists {
770 write!(f, " IF NOT EXISTS")?;
771 }
772 write!(f, " {name} ({query})")
773 }
774 AlterTableOperation::Algorithm { equals, algorithm } => {
775 write!(
776 f,
777 "ALGORITHM {}{}",
778 if *equals { "= " } else { "" },
779 algorithm
780 )
781 }
782 AlterTableOperation::DropProjection { if_exists, name } => {
783 write!(f, "DROP PROJECTION")?;
784 if *if_exists {
785 write!(f, " IF EXISTS")?;
786 }
787 write!(f, " {name}")
788 }
789 AlterTableOperation::MaterializeProjection {
790 if_exists,
791 name,
792 partition,
793 } => {
794 write!(f, "MATERIALIZE PROJECTION")?;
795 if *if_exists {
796 write!(f, " IF EXISTS")?;
797 }
798 write!(f, " {name}")?;
799 if let Some(partition) = partition {
800 write!(f, " IN PARTITION {partition}")?;
801 }
802 Ok(())
803 }
804 AlterTableOperation::ClearProjection {
805 if_exists,
806 name,
807 partition,
808 } => {
809 write!(f, "CLEAR PROJECTION")?;
810 if *if_exists {
811 write!(f, " IF EXISTS")?;
812 }
813 write!(f, " {name}")?;
814 if let Some(partition) = partition {
815 write!(f, " IN PARTITION {partition}")?;
816 }
817 Ok(())
818 }
819 AlterTableOperation::AlterColumn { column_name, op } => {
820 write!(f, "ALTER COLUMN {column_name} {op}")
821 }
822 AlterTableOperation::DisableRowLevelSecurity => {
823 write!(f, "DISABLE ROW LEVEL SECURITY")
824 }
825 AlterTableOperation::DisableRule { name } => {
826 write!(f, "DISABLE RULE {name}")
827 }
828 AlterTableOperation::DisableTrigger { name } => {
829 write!(f, "DISABLE TRIGGER {name}")
830 }
831 AlterTableOperation::DropPartitions {
832 partitions,
833 if_exists,
834 } => write!(
835 f,
836 "DROP{ie} PARTITION ({})",
837 display_comma_separated(partitions),
838 ie = if *if_exists { " IF EXISTS" } else { "" }
839 ),
840 AlterTableOperation::DropConstraint {
841 if_exists,
842 name,
843 drop_behavior,
844 } => {
845 write!(
846 f,
847 "DROP CONSTRAINT {}{}",
848 if *if_exists { "IF EXISTS " } else { "" },
849 name
850 )?;
851 if let Some(drop_behavior) = drop_behavior {
852 write!(f, " {drop_behavior}")?;
853 }
854 Ok(())
855 }
856 AlterTableOperation::DropPrimaryKey { drop_behavior } => {
857 write!(f, "DROP PRIMARY KEY")?;
858 if let Some(drop_behavior) = drop_behavior {
859 write!(f, " {drop_behavior}")?;
860 }
861 Ok(())
862 }
863 AlterTableOperation::DropForeignKey {
864 name,
865 drop_behavior,
866 } => {
867 write!(f, "DROP FOREIGN KEY {name}")?;
868 if let Some(drop_behavior) = drop_behavior {
869 write!(f, " {drop_behavior}")?;
870 }
871 Ok(())
872 }
873 AlterTableOperation::DropIndex { name } => write!(f, "DROP INDEX {name}"),
874 AlterTableOperation::DropColumn {
875 has_column_keyword,
876 column_names: column_name,
877 if_exists,
878 drop_behavior,
879 } => {
880 write!(
881 f,
882 "DROP {}{}{}",
883 if *has_column_keyword { "COLUMN " } else { "" },
884 if *if_exists { "IF EXISTS " } else { "" },
885 display_comma_separated(column_name),
886 )?;
887 if let Some(drop_behavior) = drop_behavior {
888 write!(f, " {drop_behavior}")?;
889 }
890 Ok(())
891 }
892 AlterTableOperation::AttachPartition { partition } => {
893 write!(f, "ATTACH {partition}")
894 }
895 AlterTableOperation::DetachPartition { partition } => {
896 write!(f, "DETACH {partition}")
897 }
898 AlterTableOperation::EnableAlwaysRule { name } => {
899 write!(f, "ENABLE ALWAYS RULE {name}")
900 }
901 AlterTableOperation::EnableAlwaysTrigger { name } => {
902 write!(f, "ENABLE ALWAYS TRIGGER {name}")
903 }
904 AlterTableOperation::EnableReplicaRule { name } => {
905 write!(f, "ENABLE REPLICA RULE {name}")
906 }
907 AlterTableOperation::EnableReplicaTrigger { name } => {
908 write!(f, "ENABLE REPLICA TRIGGER {name}")
909 }
910 AlterTableOperation::EnableRowLevelSecurity => {
911 write!(f, "ENABLE ROW LEVEL SECURITY")
912 }
913 AlterTableOperation::ForceRowLevelSecurity => {
914 write!(f, "FORCE ROW LEVEL SECURITY")
915 }
916 AlterTableOperation::NoForceRowLevelSecurity => {
917 write!(f, "NO FORCE ROW LEVEL SECURITY")
918 }
919 AlterTableOperation::EnableRule { name } => {
920 write!(f, "ENABLE RULE {name}")
921 }
922 AlterTableOperation::EnableTrigger { name } => {
923 write!(f, "ENABLE TRIGGER {name}")
924 }
925 AlterTableOperation::RenamePartitions {
926 old_partitions,
927 new_partitions,
928 } => write!(
929 f,
930 "PARTITION ({}) RENAME TO PARTITION ({})",
931 display_comma_separated(old_partitions),
932 display_comma_separated(new_partitions)
933 ),
934 AlterTableOperation::RenameColumn {
935 old_column_name,
936 new_column_name,
937 } => write!(f, "RENAME COLUMN {old_column_name} TO {new_column_name}"),
938 AlterTableOperation::RenameTable { table_name } => {
939 write!(f, "RENAME {table_name}")
940 }
941 AlterTableOperation::ChangeColumn {
942 old_name,
943 new_name,
944 data_type,
945 options,
946 column_position,
947 } => {
948 write!(f, "CHANGE COLUMN {old_name} {new_name} {data_type}")?;
949 if !options.is_empty() {
950 write!(f, " {}", display_separated(options, " "))?;
951 }
952 if let Some(position) = column_position {
953 write!(f, " {position}")?;
954 }
955
956 Ok(())
957 }
958 AlterTableOperation::ModifyColumn {
959 col_name,
960 data_type,
961 options,
962 column_position,
963 } => {
964 write!(f, "MODIFY COLUMN {col_name} {data_type}")?;
965 if !options.is_empty() {
966 write!(f, " {}", display_separated(options, " "))?;
967 }
968 if let Some(position) = column_position {
969 write!(f, " {position}")?;
970 }
971
972 Ok(())
973 }
974 AlterTableOperation::ModifyOrderBy { order_by } => {
975 write!(f, "MODIFY ORDER BY {order_by}")
976 }
977 AlterTableOperation::RenameConstraint { old_name, new_name } => {
978 write!(f, "RENAME CONSTRAINT {old_name} TO {new_name}")
979 }
980 AlterTableOperation::SwapWith { table_name } => {
981 write!(f, "SWAP WITH {table_name}")
982 }
983 AlterTableOperation::OwnerTo { new_owner } => {
984 write!(f, "OWNER TO {new_owner}")
985 }
986 AlterTableOperation::SetTblProperties { table_properties } => {
987 write!(
988 f,
989 "SET TBLPROPERTIES({})",
990 display_comma_separated(table_properties)
991 )
992 }
993 AlterTableOperation::SetLogged => {
994 write!(f, "SET LOGGED")
995 }
996 AlterTableOperation::SetUnlogged => {
997 write!(f, "SET UNLOGGED")
998 }
999 AlterTableOperation::FreezePartition {
1000 partition,
1001 with_name,
1002 } => {
1003 write!(f, "FREEZE {partition}")?;
1004 if let Some(name) = with_name {
1005 write!(f, " WITH NAME {name}")?;
1006 }
1007 Ok(())
1008 }
1009 AlterTableOperation::UnfreezePartition {
1010 partition,
1011 with_name,
1012 } => {
1013 write!(f, "UNFREEZE {partition}")?;
1014 if let Some(name) = with_name {
1015 write!(f, " WITH NAME {name}")?;
1016 }
1017 Ok(())
1018 }
1019 AlterTableOperation::ClusterBy { exprs } => {
1020 write!(f, "CLUSTER BY ({})", display_comma_separated(exprs))?;
1021 Ok(())
1022 }
1023 AlterTableOperation::DropClusteringKey => {
1024 write!(f, "DROP CLUSTERING KEY")?;
1025 Ok(())
1026 }
1027 AlterTableOperation::AlterSortKey { columns } => {
1028 write!(f, "ALTER SORTKEY({})", display_comma_separated(columns))?;
1029 Ok(())
1030 }
1031 AlterTableOperation::SuspendRecluster => {
1032 write!(f, "SUSPEND RECLUSTER")?;
1033 Ok(())
1034 }
1035 AlterTableOperation::ResumeRecluster => {
1036 write!(f, "RESUME RECLUSTER")?;
1037 Ok(())
1038 }
1039 AlterTableOperation::Refresh { subpath } => {
1040 write!(f, "REFRESH")?;
1041 if let Some(path) = subpath {
1042 write!(f, " '{path}'")?;
1043 }
1044 Ok(())
1045 }
1046 AlterTableOperation::Suspend => {
1047 write!(f, "SUSPEND")
1048 }
1049 AlterTableOperation::Resume => {
1050 write!(f, "RESUME")
1051 }
1052 AlterTableOperation::AutoIncrement { equals, value } => {
1053 write!(
1054 f,
1055 "AUTO_INCREMENT {}{}",
1056 if *equals { "= " } else { "" },
1057 value
1058 )
1059 }
1060 AlterTableOperation::Lock { equals, lock } => {
1061 write!(f, "LOCK {}{}", if *equals { "= " } else { "" }, lock)
1062 }
1063 AlterTableOperation::ReplicaIdentity { identity } => {
1064 write!(f, "REPLICA IDENTITY {identity}")
1065 }
1066 AlterTableOperation::ValidateConstraint { name } => {
1067 write!(f, "VALIDATE CONSTRAINT {name}")
1068 }
1069 AlterTableOperation::SetOptionsParens { options } => {
1070 write!(f, "SET ({})", display_comma_separated(options))
1071 }
1072 }
1073 }
1074}
1075
1076impl fmt::Display for AlterIndexOperation {
1077 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1078 match self {
1079 AlterIndexOperation::RenameIndex { index_name } => {
1080 write!(f, "RENAME TO {index_name}")
1081 }
1082 }
1083 }
1084}
1085
1086#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1088#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1089#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1090pub struct AlterType {
1091 pub name: ObjectName,
1093 pub operation: AlterTypeOperation,
1095}
1096
1097#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1099#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1100#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1101pub enum AlterTypeOperation {
1102 Rename(AlterTypeRename),
1104 AddValue(AlterTypeAddValue),
1106 RenameValue(AlterTypeRenameValue),
1108}
1109
1110#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1112#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1113#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1114pub struct AlterTypeRename {
1115 pub new_name: Ident,
1117}
1118
1119#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1121#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1122#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1123pub struct AlterTypeAddValue {
1124 pub if_not_exists: bool,
1126 pub value: Ident,
1128 pub position: Option<AlterTypeAddValuePosition>,
1130}
1131
1132#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1134#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1135#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1136pub enum AlterTypeAddValuePosition {
1137 Before(Ident),
1139 After(Ident),
1141}
1142
1143#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1145#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1146#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1147pub struct AlterTypeRenameValue {
1148 pub from: Ident,
1150 pub to: Ident,
1152}
1153
1154impl fmt::Display for AlterTypeOperation {
1155 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1156 match self {
1157 Self::Rename(AlterTypeRename { new_name }) => {
1158 write!(f, "RENAME TO {new_name}")
1159 }
1160 Self::AddValue(AlterTypeAddValue {
1161 if_not_exists,
1162 value,
1163 position,
1164 }) => {
1165 write!(f, "ADD VALUE")?;
1166 if *if_not_exists {
1167 write!(f, " IF NOT EXISTS")?;
1168 }
1169 write!(f, " {value}")?;
1170 match position {
1171 Some(AlterTypeAddValuePosition::Before(neighbor_value)) => {
1172 write!(f, " BEFORE {neighbor_value}")?;
1173 }
1174 Some(AlterTypeAddValuePosition::After(neighbor_value)) => {
1175 write!(f, " AFTER {neighbor_value}")?;
1176 }
1177 None => {}
1178 };
1179 Ok(())
1180 }
1181 Self::RenameValue(AlterTypeRenameValue { from, to }) => {
1182 write!(f, "RENAME VALUE {from} TO {to}")
1183 }
1184 }
1185 }
1186}
1187
1188#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1191#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1192#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1193pub struct AlterOperator {
1194 pub name: ObjectName,
1196 pub left_type: Option<DataType>,
1198 pub right_type: DataType,
1200 pub operation: AlterOperatorOperation,
1202}
1203
1204#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1206#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1207#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1208pub enum AlterOperatorOperation {
1209 OwnerTo(Owner),
1211 SetSchema {
1214 schema_name: ObjectName,
1216 },
1217 Set {
1219 options: Vec<OperatorOption>,
1221 },
1222}
1223
1224#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1226#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1227#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1228pub enum OperatorOption {
1229 Restrict(Option<ObjectName>),
1231 Join(Option<ObjectName>),
1233 Commutator(ObjectName),
1235 Negator(ObjectName),
1237 Hashes,
1239 Merges,
1241}
1242
1243impl fmt::Display for AlterOperator {
1244 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1245 write!(f, "ALTER OPERATOR {} (", self.name)?;
1246 if let Some(left_type) = &self.left_type {
1247 write!(f, "{}", left_type)?;
1248 } else {
1249 write!(f, "NONE")?;
1250 }
1251 write!(f, ", {}) {}", self.right_type, self.operation)
1252 }
1253}
1254
1255impl fmt::Display for AlterOperatorOperation {
1256 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1257 match self {
1258 Self::OwnerTo(owner) => write!(f, "OWNER TO {}", owner),
1259 Self::SetSchema { schema_name } => write!(f, "SET SCHEMA {}", schema_name),
1260 Self::Set { options } => {
1261 write!(f, "SET (")?;
1262 for (i, option) in options.iter().enumerate() {
1263 if i > 0 {
1264 write!(f, ", ")?;
1265 }
1266 write!(f, "{}", option)?;
1267 }
1268 write!(f, ")")
1269 }
1270 }
1271 }
1272}
1273
1274impl fmt::Display for OperatorOption {
1275 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1276 match self {
1277 Self::Restrict(Some(proc_name)) => write!(f, "RESTRICT = {}", proc_name),
1278 Self::Restrict(None) => write!(f, "RESTRICT = NONE"),
1279 Self::Join(Some(proc_name)) => write!(f, "JOIN = {}", proc_name),
1280 Self::Join(None) => write!(f, "JOIN = NONE"),
1281 Self::Commutator(op_name) => write!(f, "COMMUTATOR = {}", op_name),
1282 Self::Negator(op_name) => write!(f, "NEGATOR = {}", op_name),
1283 Self::Hashes => write!(f, "HASHES"),
1284 Self::Merges => write!(f, "MERGES"),
1285 }
1286 }
1287}
1288
1289#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1291#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1292#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1293pub enum AlterColumnOperation {
1294 SetNotNull,
1296 DropNotNull,
1298 SetDefault {
1301 value: Expr,
1303 },
1304 DropDefault,
1306 SetDataType {
1308 data_type: DataType,
1310 using: Option<Expr>,
1312 had_set: bool,
1314 },
1315
1316 AddGenerated {
1320 generated_as: Option<GeneratedAs>,
1322 sequence_options: Option<Vec<SequenceOptions>>,
1324 },
1325}
1326
1327impl fmt::Display for AlterColumnOperation {
1328 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1329 match self {
1330 AlterColumnOperation::SetNotNull => write!(f, "SET NOT NULL",),
1331 AlterColumnOperation::DropNotNull => write!(f, "DROP NOT NULL",),
1332 AlterColumnOperation::SetDefault { value } => {
1333 write!(f, "SET DEFAULT {value}")
1334 }
1335 AlterColumnOperation::DropDefault => {
1336 write!(f, "DROP DEFAULT")
1337 }
1338 AlterColumnOperation::SetDataType {
1339 data_type,
1340 using,
1341 had_set,
1342 } => {
1343 if *had_set {
1344 write!(f, "SET DATA ")?;
1345 }
1346 write!(f, "TYPE {data_type}")?;
1347 if let Some(expr) = using {
1348 write!(f, " USING {expr}")?;
1349 }
1350 Ok(())
1351 }
1352 AlterColumnOperation::AddGenerated {
1353 generated_as,
1354 sequence_options,
1355 } => {
1356 let generated_as = match generated_as {
1357 Some(GeneratedAs::Always) => " ALWAYS",
1358 Some(GeneratedAs::ByDefault) => " BY DEFAULT",
1359 _ => "",
1360 };
1361
1362 write!(f, "ADD GENERATED{generated_as} AS IDENTITY",)?;
1363 if let Some(options) = sequence_options {
1364 write!(f, " (")?;
1365
1366 for sequence_option in options {
1367 write!(f, "{sequence_option}")?;
1368 }
1369
1370 write!(f, " )")?;
1371 }
1372 Ok(())
1373 }
1374 }
1375 }
1376}
1377
1378#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1386#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1387#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1388pub enum KeyOrIndexDisplay {
1389 None,
1391 Key,
1393 Index,
1395}
1396
1397impl KeyOrIndexDisplay {
1398 pub fn is_none(self) -> bool {
1400 matches!(self, Self::None)
1401 }
1402}
1403
1404impl fmt::Display for KeyOrIndexDisplay {
1405 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1406 let left_space = matches!(f.align(), Some(fmt::Alignment::Right));
1407
1408 if left_space && !self.is_none() {
1409 f.write_char(' ')?
1410 }
1411
1412 match self {
1413 KeyOrIndexDisplay::None => {
1414 write!(f, "")
1415 }
1416 KeyOrIndexDisplay::Key => {
1417 write!(f, "KEY")
1418 }
1419 KeyOrIndexDisplay::Index => {
1420 write!(f, "INDEX")
1421 }
1422 }
1423 }
1424}
1425
1426#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1435#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1436#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1437pub enum IndexType {
1438 BTree,
1440 Hash,
1442 GIN,
1444 GiST,
1446 SPGiST,
1448 BRIN,
1450 Bloom,
1452 Custom(Ident),
1455}
1456
1457impl fmt::Display for IndexType {
1458 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1459 match self {
1460 Self::BTree => write!(f, "BTREE"),
1461 Self::Hash => write!(f, "HASH"),
1462 Self::GIN => write!(f, "GIN"),
1463 Self::GiST => write!(f, "GIST"),
1464 Self::SPGiST => write!(f, "SPGIST"),
1465 Self::BRIN => write!(f, "BRIN"),
1466 Self::Bloom => write!(f, "BLOOM"),
1467 Self::Custom(name) => write!(f, "{name}"),
1468 }
1469 }
1470}
1471
1472#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1478#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1479#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1480pub enum IndexOption {
1481 Using(IndexType),
1485 Comment(String),
1487}
1488
1489impl fmt::Display for IndexOption {
1490 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1491 match self {
1492 Self::Using(index_type) => write!(f, "USING {index_type}"),
1493 Self::Comment(s) => write!(f, "COMMENT '{s}'"),
1494 }
1495 }
1496}
1497
1498#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1502#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1503#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1504pub enum NullsDistinctOption {
1505 None,
1507 Distinct,
1509 NotDistinct,
1511}
1512
1513impl fmt::Display for NullsDistinctOption {
1514 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1515 match self {
1516 Self::None => Ok(()),
1517 Self::Distinct => write!(f, " NULLS DISTINCT"),
1518 Self::NotDistinct => write!(f, " NULLS NOT DISTINCT"),
1519 }
1520 }
1521}
1522
1523#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1524#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1525#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1526pub struct ProcedureParam {
1528 pub name: Ident,
1530 pub data_type: DataType,
1532 pub mode: Option<ArgMode>,
1534 pub default: Option<Expr>,
1536}
1537
1538impl fmt::Display for ProcedureParam {
1539 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1540 if let Some(mode) = &self.mode {
1541 if let Some(default) = &self.default {
1542 write!(f, "{mode} {} {} = {}", self.name, self.data_type, default)
1543 } else {
1544 write!(f, "{mode} {} {}", self.name, self.data_type)
1545 }
1546 } else if let Some(default) = &self.default {
1547 write!(f, "{} {} = {}", self.name, self.data_type, default)
1548 } else {
1549 write!(f, "{} {}", self.name, self.data_type)
1550 }
1551 }
1552}
1553
1554#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1556#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1557#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1558pub struct ColumnDef {
1559 pub name: Ident,
1561 pub data_type: DataType,
1563 pub options: Vec<ColumnOptionDef>,
1565}
1566
1567impl fmt::Display for ColumnDef {
1568 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1569 if self.data_type == DataType::Unspecified {
1570 write!(f, "{}", self.name)?;
1571 } else {
1572 write!(f, "{} {}", self.name, self.data_type)?;
1573 }
1574 for option in &self.options {
1575 write!(f, " {option}")?;
1576 }
1577 Ok(())
1578 }
1579}
1580
1581#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1598#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1599#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1600pub struct ViewColumnDef {
1601 pub name: Ident,
1603 pub data_type: Option<DataType>,
1605 pub options: Option<ColumnOptions>,
1607}
1608
1609#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1610#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1611#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1612pub enum ColumnOptions {
1614 CommaSeparated(Vec<ColumnOption>),
1616 SpaceSeparated(Vec<ColumnOption>),
1618}
1619
1620impl ColumnOptions {
1621 pub fn as_slice(&self) -> &[ColumnOption] {
1623 match self {
1624 ColumnOptions::CommaSeparated(options) => options.as_slice(),
1625 ColumnOptions::SpaceSeparated(options) => options.as_slice(),
1626 }
1627 }
1628}
1629
1630impl fmt::Display for ViewColumnDef {
1631 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1632 write!(f, "{}", self.name)?;
1633 if let Some(data_type) = self.data_type.as_ref() {
1634 write!(f, " {data_type}")?;
1635 }
1636 if let Some(options) = self.options.as_ref() {
1637 match options {
1638 ColumnOptions::CommaSeparated(column_options) => {
1639 write!(f, " {}", display_comma_separated(column_options.as_slice()))?;
1640 }
1641 ColumnOptions::SpaceSeparated(column_options) => {
1642 write!(f, " {}", display_separated(column_options.as_slice(), " "))?
1643 }
1644 }
1645 }
1646 Ok(())
1647 }
1648}
1649
1650#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1667#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1668#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1669pub struct ColumnOptionDef {
1670 pub name: Option<Ident>,
1672 pub option: ColumnOption,
1674}
1675
1676impl fmt::Display for ColumnOptionDef {
1677 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1678 write!(f, "{}{}", display_constraint_name(&self.name), self.option)
1679 }
1680}
1681
1682#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1690#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1691#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1692pub enum IdentityPropertyKind {
1693 Autoincrement(IdentityProperty),
1701 Identity(IdentityProperty),
1714}
1715
1716impl fmt::Display for IdentityPropertyKind {
1717 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1718 let (command, property) = match self {
1719 IdentityPropertyKind::Identity(property) => ("IDENTITY", property),
1720 IdentityPropertyKind::Autoincrement(property) => ("AUTOINCREMENT", property),
1721 };
1722 write!(f, "{command}")?;
1723 if let Some(parameters) = &property.parameters {
1724 write!(f, "{parameters}")?;
1725 }
1726 if let Some(order) = &property.order {
1727 write!(f, "{order}")?;
1728 }
1729 Ok(())
1730 }
1731}
1732
1733#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1735#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1736#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1737pub struct IdentityProperty {
1738 pub parameters: Option<IdentityPropertyFormatKind>,
1740 pub order: Option<IdentityPropertyOrder>,
1742}
1743
1744#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1759#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1760#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1761pub enum IdentityPropertyFormatKind {
1762 FunctionCall(IdentityParameters),
1770 StartAndIncrement(IdentityParameters),
1777}
1778
1779impl fmt::Display for IdentityPropertyFormatKind {
1780 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1781 match self {
1782 IdentityPropertyFormatKind::FunctionCall(parameters) => {
1783 write!(f, "({}, {})", parameters.seed, parameters.increment)
1784 }
1785 IdentityPropertyFormatKind::StartAndIncrement(parameters) => {
1786 write!(
1787 f,
1788 " START {} INCREMENT {}",
1789 parameters.seed, parameters.increment
1790 )
1791 }
1792 }
1793 }
1794}
1795#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1797#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1798#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1799pub struct IdentityParameters {
1800 pub seed: Expr,
1802 pub increment: Expr,
1804}
1805
1806#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1813#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1814#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1815pub enum IdentityPropertyOrder {
1816 Order,
1818 NoOrder,
1820}
1821
1822impl fmt::Display for IdentityPropertyOrder {
1823 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1824 match self {
1825 IdentityPropertyOrder::Order => write!(f, " ORDER"),
1826 IdentityPropertyOrder::NoOrder => write!(f, " NOORDER"),
1827 }
1828 }
1829}
1830
1831#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1839#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1840#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1841pub enum ColumnPolicy {
1842 MaskingPolicy(ColumnPolicyProperty),
1844 ProjectionPolicy(ColumnPolicyProperty),
1846}
1847
1848impl fmt::Display for ColumnPolicy {
1849 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1850 let (command, property) = match self {
1851 ColumnPolicy::MaskingPolicy(property) => ("MASKING POLICY", property),
1852 ColumnPolicy::ProjectionPolicy(property) => ("PROJECTION POLICY", property),
1853 };
1854 if property.with {
1855 write!(f, "WITH ")?;
1856 }
1857 write!(f, "{command} {}", property.policy_name)?;
1858 if let Some(using_columns) = &property.using_columns {
1859 write!(f, " USING ({})", display_comma_separated(using_columns))?;
1860 }
1861 Ok(())
1862 }
1863}
1864
1865#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1866#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1867#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1868pub struct ColumnPolicyProperty {
1870 pub with: bool,
1877 pub policy_name: ObjectName,
1879 pub using_columns: Option<Vec<Ident>>,
1881}
1882
1883#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1890#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1891#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1892pub struct TagsColumnOption {
1893 pub with: bool,
1900 pub tags: Vec<Tag>,
1902}
1903
1904impl fmt::Display for TagsColumnOption {
1905 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1906 if self.with {
1907 write!(f, "WITH ")?;
1908 }
1909 write!(f, "TAG ({})", display_comma_separated(&self.tags))?;
1910 Ok(())
1911 }
1912}
1913
1914#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1917#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1918#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1919pub enum ColumnOption {
1920 Null,
1922 NotNull,
1924 Default(Expr),
1926
1927 Materialized(Expr),
1932 Ephemeral(Option<Expr>),
1936 Alias(Expr),
1940
1941 PrimaryKey(PrimaryKeyConstraint),
1943 Unique(UniqueConstraint),
1945 ForeignKey(ForeignKeyConstraint),
1953 Check(CheckConstraint),
1955 DialectSpecific(Vec<Token>),
1959 CharacterSet(ObjectName),
1961 Collation(ObjectName),
1963 Comment(String),
1965 OnUpdate(Expr),
1967 Generated {
1970 generated_as: GeneratedAs,
1972 sequence_options: Option<Vec<SequenceOptions>>,
1974 generation_expr: Option<Expr>,
1976 generation_expr_mode: Option<GeneratedExpressionMode>,
1978 generated_keyword: bool,
1980 },
1981 Options(Vec<SqlOption>),
1989 Identity(IdentityPropertyKind),
1997 OnConflict(Keyword),
2000 Policy(ColumnPolicy),
2008 Tags(TagsColumnOption),
2015 Srid(Box<Expr>),
2022 Invisible,
2029}
2030
2031impl From<UniqueConstraint> for ColumnOption {
2032 fn from(c: UniqueConstraint) -> Self {
2033 ColumnOption::Unique(c)
2034 }
2035}
2036
2037impl From<PrimaryKeyConstraint> for ColumnOption {
2038 fn from(c: PrimaryKeyConstraint) -> Self {
2039 ColumnOption::PrimaryKey(c)
2040 }
2041}
2042
2043impl From<CheckConstraint> for ColumnOption {
2044 fn from(c: CheckConstraint) -> Self {
2045 ColumnOption::Check(c)
2046 }
2047}
2048impl From<ForeignKeyConstraint> for ColumnOption {
2049 fn from(fk: ForeignKeyConstraint) -> Self {
2050 ColumnOption::ForeignKey(fk)
2051 }
2052}
2053
2054impl fmt::Display for ColumnOption {
2055 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2056 use ColumnOption::*;
2057 match self {
2058 Null => write!(f, "NULL"),
2059 NotNull => write!(f, "NOT NULL"),
2060 Default(expr) => write!(f, "DEFAULT {expr}"),
2061 Materialized(expr) => write!(f, "MATERIALIZED {expr}"),
2062 Ephemeral(expr) => {
2063 if let Some(e) = expr {
2064 write!(f, "EPHEMERAL {e}")
2065 } else {
2066 write!(f, "EPHEMERAL")
2067 }
2068 }
2069 Alias(expr) => write!(f, "ALIAS {expr}"),
2070 PrimaryKey(constraint) => {
2071 write!(f, "PRIMARY KEY")?;
2072 if let Some(characteristics) = &constraint.characteristics {
2073 write!(f, " {characteristics}")?;
2074 }
2075 Ok(())
2076 }
2077 Unique(constraint) => {
2078 write!(f, "UNIQUE{:>}", constraint.index_type_display)?;
2079 if let Some(characteristics) = &constraint.characteristics {
2080 write!(f, " {characteristics}")?;
2081 }
2082 Ok(())
2083 }
2084 ForeignKey(constraint) => {
2085 write!(f, "REFERENCES {}", constraint.foreign_table)?;
2086 if !constraint.referred_columns.is_empty() {
2087 write!(
2088 f,
2089 " ({})",
2090 display_comma_separated(&constraint.referred_columns)
2091 )?;
2092 }
2093 if let Some(match_kind) = &constraint.match_kind {
2094 write!(f, " {match_kind}")?;
2095 }
2096 if let Some(action) = &constraint.on_delete {
2097 write!(f, " ON DELETE {action}")?;
2098 }
2099 if let Some(action) = &constraint.on_update {
2100 write!(f, " ON UPDATE {action}")?;
2101 }
2102 if let Some(characteristics) = &constraint.characteristics {
2103 write!(f, " {characteristics}")?;
2104 }
2105 Ok(())
2106 }
2107 Check(constraint) => write!(f, "{constraint}"),
2108 DialectSpecific(val) => write!(f, "{}", display_separated(val, " ")),
2109 CharacterSet(n) => write!(f, "CHARACTER SET {n}"),
2110 Collation(n) => write!(f, "COLLATE {n}"),
2111 Comment(v) => write!(f, "COMMENT '{}'", escape_single_quote_string(v)),
2112 OnUpdate(expr) => write!(f, "ON UPDATE {expr}"),
2113 Generated {
2114 generated_as,
2115 sequence_options,
2116 generation_expr,
2117 generation_expr_mode,
2118 generated_keyword,
2119 } => {
2120 if let Some(expr) = generation_expr {
2121 let modifier = match generation_expr_mode {
2122 None => "",
2123 Some(GeneratedExpressionMode::Virtual) => " VIRTUAL",
2124 Some(GeneratedExpressionMode::Stored) => " STORED",
2125 };
2126 if *generated_keyword {
2127 write!(f, "GENERATED ALWAYS AS ({expr}){modifier}")?;
2128 } else {
2129 write!(f, "AS ({expr}){modifier}")?;
2130 }
2131 Ok(())
2132 } else {
2133 let when = match generated_as {
2135 GeneratedAs::Always => "ALWAYS",
2136 GeneratedAs::ByDefault => "BY DEFAULT",
2137 GeneratedAs::ExpStored => "",
2139 };
2140 write!(f, "GENERATED {when} AS IDENTITY")?;
2141 if let Some(so) = sequence_options {
2142 if !so.is_empty() {
2143 write!(f, " (")?;
2144 }
2145 for sequence_option in so {
2146 write!(f, "{sequence_option}")?;
2147 }
2148 if !so.is_empty() {
2149 write!(f, " )")?;
2150 }
2151 }
2152 Ok(())
2153 }
2154 }
2155 Options(options) => {
2156 write!(f, "OPTIONS({})", display_comma_separated(options))
2157 }
2158 Identity(parameters) => {
2159 write!(f, "{parameters}")
2160 }
2161 OnConflict(keyword) => {
2162 write!(f, "ON CONFLICT {keyword:?}")?;
2163 Ok(())
2164 }
2165 Policy(parameters) => {
2166 write!(f, "{parameters}")
2167 }
2168 Tags(tags) => {
2169 write!(f, "{tags}")
2170 }
2171 Srid(srid) => {
2172 write!(f, "SRID {srid}")
2173 }
2174 Invisible => {
2175 write!(f, "INVISIBLE")
2176 }
2177 }
2178 }
2179}
2180
2181#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2184#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2185#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2186pub enum GeneratedAs {
2187 Always,
2189 ByDefault,
2191 ExpStored,
2193}
2194
2195#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2198#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2199#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2200pub enum GeneratedExpressionMode {
2201 Virtual,
2203 Stored,
2205}
2206
2207#[must_use]
2208pub(crate) fn display_constraint_name(name: &'_ Option<Ident>) -> impl fmt::Display + '_ {
2209 struct ConstraintName<'a>(&'a Option<Ident>);
2210 impl fmt::Display for ConstraintName<'_> {
2211 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2212 if let Some(name) = self.0 {
2213 write!(f, "CONSTRAINT {name} ")?;
2214 }
2215 Ok(())
2216 }
2217 }
2218 ConstraintName(name)
2219}
2220
2221#[must_use]
2225pub(crate) fn display_option<'a, T: fmt::Display>(
2226 prefix: &'a str,
2227 postfix: &'a str,
2228 option: &'a Option<T>,
2229) -> impl fmt::Display + 'a {
2230 struct OptionDisplay<'a, T>(&'a str, &'a str, &'a Option<T>);
2231 impl<T: fmt::Display> fmt::Display for OptionDisplay<'_, T> {
2232 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2233 if let Some(inner) = self.2 {
2234 let (prefix, postfix) = (self.0, self.1);
2235 write!(f, "{prefix}{inner}{postfix}")?;
2236 }
2237 Ok(())
2238 }
2239 }
2240 OptionDisplay(prefix, postfix, option)
2241}
2242
2243#[must_use]
2247pub(crate) fn display_option_spaced<T: fmt::Display>(option: &Option<T>) -> impl fmt::Display + '_ {
2248 display_option(" ", "", option)
2249}
2250
2251#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Default, Eq, Ord, Hash)]
2255#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2256#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2257pub struct ConstraintCharacteristics {
2258 pub deferrable: Option<bool>,
2260 pub initially: Option<DeferrableInitial>,
2262 pub enforced: Option<bool>,
2264}
2265
2266#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2268#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2269#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2270pub enum DeferrableInitial {
2271 Immediate,
2273 Deferred,
2275}
2276
2277impl ConstraintCharacteristics {
2278 fn deferrable_text(&self) -> Option<&'static str> {
2279 self.deferrable.map(|deferrable| {
2280 if deferrable {
2281 "DEFERRABLE"
2282 } else {
2283 "NOT DEFERRABLE"
2284 }
2285 })
2286 }
2287
2288 fn initially_immediate_text(&self) -> Option<&'static str> {
2289 self.initially
2290 .map(|initially_immediate| match initially_immediate {
2291 DeferrableInitial::Immediate => "INITIALLY IMMEDIATE",
2292 DeferrableInitial::Deferred => "INITIALLY DEFERRED",
2293 })
2294 }
2295
2296 fn enforced_text(&self) -> Option<&'static str> {
2297 self.enforced.map(
2298 |enforced| {
2299 if enforced {
2300 "ENFORCED"
2301 } else {
2302 "NOT ENFORCED"
2303 }
2304 },
2305 )
2306 }
2307}
2308
2309impl fmt::Display for ConstraintCharacteristics {
2310 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2311 let deferrable = self.deferrable_text();
2312 let initially_immediate = self.initially_immediate_text();
2313 let enforced = self.enforced_text();
2314
2315 match (deferrable, initially_immediate, enforced) {
2316 (None, None, None) => Ok(()),
2317 (None, None, Some(enforced)) => write!(f, "{enforced}"),
2318 (None, Some(initial), None) => write!(f, "{initial}"),
2319 (None, Some(initial), Some(enforced)) => write!(f, "{initial} {enforced}"),
2320 (Some(deferrable), None, None) => write!(f, "{deferrable}"),
2321 (Some(deferrable), None, Some(enforced)) => write!(f, "{deferrable} {enforced}"),
2322 (Some(deferrable), Some(initial), None) => write!(f, "{deferrable} {initial}"),
2323 (Some(deferrable), Some(initial), Some(enforced)) => {
2324 write!(f, "{deferrable} {initial} {enforced}")
2325 }
2326 }
2327 }
2328}
2329
2330#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2335#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2336#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2337pub enum ReferentialAction {
2338 Restrict,
2340 Cascade,
2342 SetNull,
2344 NoAction,
2346 SetDefault,
2348}
2349
2350impl fmt::Display for ReferentialAction {
2351 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2352 f.write_str(match self {
2353 ReferentialAction::Restrict => "RESTRICT",
2354 ReferentialAction::Cascade => "CASCADE",
2355 ReferentialAction::SetNull => "SET NULL",
2356 ReferentialAction::NoAction => "NO ACTION",
2357 ReferentialAction::SetDefault => "SET DEFAULT",
2358 })
2359 }
2360}
2361
2362#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2366#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2367#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2368pub enum DropBehavior {
2369 Restrict,
2371 Cascade,
2373}
2374
2375impl fmt::Display for DropBehavior {
2376 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2377 f.write_str(match self {
2378 DropBehavior::Restrict => "RESTRICT",
2379 DropBehavior::Cascade => "CASCADE",
2380 })
2381 }
2382}
2383
2384#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2386#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2387#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2388pub enum UserDefinedTypeRepresentation {
2389 Composite {
2391 attributes: Vec<UserDefinedTypeCompositeAttributeDef>,
2393 },
2394 Enum {
2399 labels: Vec<Ident>,
2401 },
2402 Range {
2406 options: Vec<UserDefinedTypeRangeOption>,
2408 },
2409 SqlDefinition {
2415 options: Vec<UserDefinedTypeSqlDefinitionOption>,
2417 },
2418}
2419
2420impl fmt::Display for UserDefinedTypeRepresentation {
2421 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2422 match self {
2423 Self::Composite { attributes } => {
2424 write!(f, "AS ({})", display_comma_separated(attributes))
2425 }
2426 Self::Enum { labels } => {
2427 write!(f, "AS ENUM ({})", display_comma_separated(labels))
2428 }
2429 Self::Range { options } => {
2430 write!(f, "AS RANGE ({})", display_comma_separated(options))
2431 }
2432 Self::SqlDefinition { options } => {
2433 write!(f, "({})", display_comma_separated(options))
2434 }
2435 }
2436 }
2437}
2438
2439#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2441#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2442#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2443pub struct UserDefinedTypeCompositeAttributeDef {
2444 pub name: Ident,
2446 pub data_type: DataType,
2448 pub collation: Option<ObjectName>,
2450}
2451
2452impl fmt::Display for UserDefinedTypeCompositeAttributeDef {
2453 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2454 write!(f, "{} {}", self.name, self.data_type)?;
2455 if let Some(collation) = &self.collation {
2456 write!(f, " COLLATE {collation}")?;
2457 }
2458 Ok(())
2459 }
2460}
2461
2462#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2485#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2486#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2487pub enum UserDefinedTypeInternalLength {
2488 Fixed(u64),
2490 Variable,
2492}
2493
2494impl fmt::Display for UserDefinedTypeInternalLength {
2495 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2496 match self {
2497 UserDefinedTypeInternalLength::Fixed(n) => write!(f, "{}", n),
2498 UserDefinedTypeInternalLength::Variable => write!(f, "VARIABLE"),
2499 }
2500 }
2501}
2502
2503#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2522#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2523#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2524pub enum Alignment {
2525 Char,
2527 Int2,
2529 Int4,
2531 Double,
2533}
2534
2535impl fmt::Display for Alignment {
2536 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2537 match self {
2538 Alignment::Char => write!(f, "char"),
2539 Alignment::Int2 => write!(f, "int2"),
2540 Alignment::Int4 => write!(f, "int4"),
2541 Alignment::Double => write!(f, "double"),
2542 }
2543 }
2544}
2545
2546#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2566#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2567#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2568pub enum UserDefinedTypeStorage {
2569 Plain,
2571 External,
2573 Extended,
2575 Main,
2577}
2578
2579impl fmt::Display for UserDefinedTypeStorage {
2580 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2581 match self {
2582 UserDefinedTypeStorage::Plain => write!(f, "plain"),
2583 UserDefinedTypeStorage::External => write!(f, "external"),
2584 UserDefinedTypeStorage::Extended => write!(f, "extended"),
2585 UserDefinedTypeStorage::Main => write!(f, "main"),
2586 }
2587 }
2588}
2589
2590#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2608#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2609#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2610pub enum UserDefinedTypeRangeOption {
2611 Subtype(DataType),
2613 SubtypeOpClass(ObjectName),
2615 Collation(ObjectName),
2617 Canonical(ObjectName),
2619 SubtypeDiff(ObjectName),
2621 MultirangeTypeName(ObjectName),
2623}
2624
2625impl fmt::Display for UserDefinedTypeRangeOption {
2626 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2627 match self {
2628 UserDefinedTypeRangeOption::Subtype(dt) => write!(f, "SUBTYPE = {}", dt),
2629 UserDefinedTypeRangeOption::SubtypeOpClass(name) => {
2630 write!(f, "SUBTYPE_OPCLASS = {}", name)
2631 }
2632 UserDefinedTypeRangeOption::Collation(name) => write!(f, "COLLATION = {}", name),
2633 UserDefinedTypeRangeOption::Canonical(name) => write!(f, "CANONICAL = {}", name),
2634 UserDefinedTypeRangeOption::SubtypeDiff(name) => write!(f, "SUBTYPE_DIFF = {}", name),
2635 UserDefinedTypeRangeOption::MultirangeTypeName(name) => {
2636 write!(f, "MULTIRANGE_TYPE_NAME = {}", name)
2637 }
2638 }
2639 }
2640}
2641
2642#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2663#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2664#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2665pub enum UserDefinedTypeSqlDefinitionOption {
2666 Input(ObjectName),
2668 Output(ObjectName),
2670 Receive(ObjectName),
2672 Send(ObjectName),
2674 TypmodIn(ObjectName),
2676 TypmodOut(ObjectName),
2678 Analyze(ObjectName),
2680 Subscript(ObjectName),
2682 InternalLength(UserDefinedTypeInternalLength),
2684 PassedByValue,
2686 Alignment(Alignment),
2688 Storage(UserDefinedTypeStorage),
2690 Like(ObjectName),
2692 Category(char),
2694 Preferred(bool),
2696 Default(Expr),
2698 Element(DataType),
2700 Delimiter(String),
2702 Collatable(bool),
2704}
2705
2706impl fmt::Display for UserDefinedTypeSqlDefinitionOption {
2707 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2708 match self {
2709 UserDefinedTypeSqlDefinitionOption::Input(name) => write!(f, "INPUT = {}", name),
2710 UserDefinedTypeSqlDefinitionOption::Output(name) => write!(f, "OUTPUT = {}", name),
2711 UserDefinedTypeSqlDefinitionOption::Receive(name) => write!(f, "RECEIVE = {}", name),
2712 UserDefinedTypeSqlDefinitionOption::Send(name) => write!(f, "SEND = {}", name),
2713 UserDefinedTypeSqlDefinitionOption::TypmodIn(name) => write!(f, "TYPMOD_IN = {}", name),
2714 UserDefinedTypeSqlDefinitionOption::TypmodOut(name) => {
2715 write!(f, "TYPMOD_OUT = {}", name)
2716 }
2717 UserDefinedTypeSqlDefinitionOption::Analyze(name) => write!(f, "ANALYZE = {}", name),
2718 UserDefinedTypeSqlDefinitionOption::Subscript(name) => {
2719 write!(f, "SUBSCRIPT = {}", name)
2720 }
2721 UserDefinedTypeSqlDefinitionOption::InternalLength(len) => {
2722 write!(f, "INTERNALLENGTH = {}", len)
2723 }
2724 UserDefinedTypeSqlDefinitionOption::PassedByValue => write!(f, "PASSEDBYVALUE"),
2725 UserDefinedTypeSqlDefinitionOption::Alignment(align) => {
2726 write!(f, "ALIGNMENT = {}", align)
2727 }
2728 UserDefinedTypeSqlDefinitionOption::Storage(storage) => {
2729 write!(f, "STORAGE = {}", storage)
2730 }
2731 UserDefinedTypeSqlDefinitionOption::Like(name) => write!(f, "LIKE = {}", name),
2732 UserDefinedTypeSqlDefinitionOption::Category(c) => write!(f, "CATEGORY = '{}'", c),
2733 UserDefinedTypeSqlDefinitionOption::Preferred(b) => write!(f, "PREFERRED = {}", b),
2734 UserDefinedTypeSqlDefinitionOption::Default(expr) => write!(f, "DEFAULT = {}", expr),
2735 UserDefinedTypeSqlDefinitionOption::Element(dt) => write!(f, "ELEMENT = {}", dt),
2736 UserDefinedTypeSqlDefinitionOption::Delimiter(s) => {
2737 write!(f, "DELIMITER = '{}'", escape_single_quote_string(s))
2738 }
2739 UserDefinedTypeSqlDefinitionOption::Collatable(b) => write!(f, "COLLATABLE = {}", b),
2740 }
2741 }
2742}
2743
2744#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2748#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2749#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2750pub enum Partition {
2751 Identifier(Ident),
2753 Expr(Expr),
2755 Part(Expr),
2758 Partitions(Vec<Expr>),
2760}
2761
2762impl fmt::Display for Partition {
2763 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2764 match self {
2765 Partition::Identifier(id) => write!(f, "PARTITION ID {id}"),
2766 Partition::Expr(expr) => write!(f, "PARTITION {expr}"),
2767 Partition::Part(expr) => write!(f, "PART {expr}"),
2768 Partition::Partitions(partitions) => {
2769 write!(f, "PARTITION ({})", display_comma_separated(partitions))
2770 }
2771 }
2772 }
2773}
2774
2775#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2778#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2779#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2780pub enum Deduplicate {
2781 All,
2783 ByExpression(Expr),
2785}
2786
2787impl fmt::Display for Deduplicate {
2788 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2789 match self {
2790 Deduplicate::All => write!(f, "DEDUPLICATE"),
2791 Deduplicate::ByExpression(expr) => write!(f, "DEDUPLICATE BY {expr}"),
2792 }
2793 }
2794}
2795
2796#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2801#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2802#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2803pub struct ClusteredBy {
2804 pub columns: Vec<Ident>,
2806 pub sorted_by: Option<Vec<OrderByExpr>>,
2808 pub num_buckets: Value,
2810}
2811
2812impl fmt::Display for ClusteredBy {
2813 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2814 write!(
2815 f,
2816 "CLUSTERED BY ({})",
2817 display_comma_separated(&self.columns)
2818 )?;
2819 if let Some(ref sorted_by) = self.sorted_by {
2820 write!(f, " SORTED BY ({})", display_comma_separated(sorted_by))?;
2821 }
2822 write!(f, " INTO {} BUCKETS", self.num_buckets)
2823 }
2824}
2825
2826#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2828#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2829#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2830pub struct CreateIndex {
2831 pub name: Option<ObjectName>,
2833 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2834 pub table_name: ObjectName,
2836 pub using: Option<IndexType>,
2839 pub columns: Vec<IndexColumn>,
2841 pub unique: bool,
2843 pub concurrently: bool,
2845 pub r#async: bool,
2849 pub if_not_exists: bool,
2851 pub include: Vec<Ident>,
2853 pub nulls_distinct: Option<bool>,
2855 pub with: Vec<Expr>,
2857 pub predicate: Option<Expr>,
2859 pub index_options: Vec<IndexOption>,
2861 pub alter_options: Vec<AlterTableOperation>,
2868}
2869
2870impl fmt::Display for CreateIndex {
2871 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2872 write!(
2873 f,
2874 "CREATE {unique}INDEX {concurrently}{async_}{if_not_exists}",
2875 unique = if self.unique { "UNIQUE " } else { "" },
2876 concurrently = if self.concurrently {
2877 "CONCURRENTLY "
2878 } else {
2879 ""
2880 },
2881 async_ = if self.r#async { "ASYNC " } else { "" },
2882 if_not_exists = if self.if_not_exists {
2883 "IF NOT EXISTS "
2884 } else {
2885 ""
2886 },
2887 )?;
2888 if let Some(value) = &self.name {
2889 write!(f, "{value} ")?;
2890 }
2891 write!(f, "ON {}", self.table_name)?;
2892 if let Some(value) = &self.using {
2893 write!(f, " USING {value} ")?;
2894 }
2895 write!(f, "({})", display_comma_separated(&self.columns))?;
2896 if !self.include.is_empty() {
2897 write!(f, " INCLUDE ({})", display_comma_separated(&self.include))?;
2898 }
2899 if let Some(value) = self.nulls_distinct {
2900 if value {
2901 write!(f, " NULLS DISTINCT")?;
2902 } else {
2903 write!(f, " NULLS NOT DISTINCT")?;
2904 }
2905 }
2906 if !self.with.is_empty() {
2907 write!(f, " WITH ({})", display_comma_separated(&self.with))?;
2908 }
2909 if let Some(predicate) = &self.predicate {
2910 write!(f, " WHERE {predicate}")?;
2911 }
2912 if !self.index_options.is_empty() {
2913 write!(f, " {}", display_separated(&self.index_options, " "))?;
2914 }
2915 if !self.alter_options.is_empty() {
2916 write!(f, " {}", display_separated(&self.alter_options, " "))?;
2917 }
2918 Ok(())
2919 }
2920}
2921
2922#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2924#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2925#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2926pub struct CreateTable {
2927 pub or_replace: bool,
2929 pub temporary: bool,
2931 pub unlogged: bool,
2933 pub external: bool,
2935 pub dynamic: bool,
2937 pub global: Option<bool>,
2939 pub if_not_exists: bool,
2941 pub transient: bool,
2943 pub volatile: bool,
2945 pub iceberg: bool,
2947 pub snapshot: bool,
2950 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2952 pub name: ObjectName,
2953 pub columns: Vec<ColumnDef>,
2955 pub constraints: Vec<TableConstraint>,
2957 pub hive_distribution: HiveDistributionStyle,
2959 pub hive_formats: Option<HiveFormat>,
2961 pub table_options: CreateTableOptions,
2963 pub file_format: Option<FileFormat>,
2965 pub location: Option<String>,
2967 pub query: Option<Box<Query>>,
2969 pub without_rowid: bool,
2971 pub like: Option<CreateTableLikeKind>,
2973 pub clone: Option<ObjectName>,
2975 pub version: Option<TableVersion>,
2977 pub comment: Option<CommentDef>,
2981 pub on_commit: Option<OnCommit>,
2984 pub on_cluster: Option<Ident>,
2987 pub primary_key: Option<Box<Expr>>,
2990 pub order_by: Option<OneOrManyWithParens<Expr>>,
2994 pub partition_by: Option<Box<Expr>>,
2997 pub cluster_by: Option<WrappedCollection<Vec<Expr>>>,
3002 pub clustered_by: Option<ClusteredBy>,
3005 pub inherits: Option<Vec<ObjectName>>,
3010 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3014 pub partition_of: Option<ObjectName>,
3015 pub for_values: Option<ForValues>,
3018 pub strict: bool,
3022 pub copy_grants: bool,
3025 pub enable_schema_evolution: Option<bool>,
3028 pub change_tracking: Option<bool>,
3031 pub data_retention_time_in_days: Option<u64>,
3034 pub max_data_extension_time_in_days: Option<u64>,
3037 pub default_ddl_collation: Option<String>,
3040 pub with_aggregation_policy: Option<ObjectName>,
3043 pub with_row_access_policy: Option<RowAccessPolicy>,
3046 pub with_storage_lifecycle_policy: Option<StorageLifecyclePolicy>,
3049 pub with_tags: Option<Vec<Tag>>,
3052 pub external_volume: Option<String>,
3055 pub with_connection: Option<ObjectName>,
3058 pub base_location: Option<String>,
3061 pub catalog: Option<String>,
3064 pub catalog_sync: Option<String>,
3067 pub storage_serialization_policy: Option<StorageSerializationPolicy>,
3070 pub target_lag: Option<String>,
3073 pub warehouse: Option<Ident>,
3076 pub refresh_mode: Option<RefreshModeKind>,
3079 pub initialize: Option<InitializeKind>,
3082 pub require_user: bool,
3085 pub diststyle: Option<DistStyle>,
3088 pub distkey: Option<Expr>,
3091 pub sortkey: Option<Vec<Expr>>,
3094 pub backup: Option<bool>,
3097 pub multiset: Option<bool>,
3102 pub fallback: Option<bool>,
3107 pub with_data: Option<WithData>,
3111}
3112
3113impl fmt::Display for CreateTable {
3114 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3115 write!(
3123 f,
3124 "CREATE {or_replace}{external}{global}{multiset}{temporary}{unlogged}{transient}{volatile}{dynamic}{iceberg}{snapshot}TABLE {if_not_exists}{name}",
3125 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3126 external = if self.external { "EXTERNAL " } else { "" },
3127 snapshot = if self.snapshot { "SNAPSHOT " } else { "" },
3128 global = self.global
3129 .map(|global| {
3130 if global {
3131 "GLOBAL "
3132 } else {
3133 "LOCAL "
3134 }
3135 })
3136 .unwrap_or(""),
3137 if_not_exists = if self.if_not_exists { "IF NOT EXISTS " } else { "" },
3138 multiset = self
3139 .multiset
3140 .map(|m| if m { "MULTISET " } else { "SET " })
3141 .unwrap_or(""),
3142 temporary = if self.temporary { "TEMPORARY " } else { "" },
3143 unlogged = if self.unlogged { "UNLOGGED " } else { "" },
3144 transient = if self.transient { "TRANSIENT " } else { "" },
3145 volatile = if self.volatile { "VOLATILE " } else { "" },
3146 iceberg = if self.iceberg { "ICEBERG " } else { "" },
3147 dynamic = if self.dynamic { "DYNAMIC " } else { "" },
3148 name = self.name,
3149 )?;
3150 if let Some(fallback) = self.fallback {
3151 write!(f, ", {}", if fallback { "FALLBACK" } else { "NO FALLBACK" })?;
3152 }
3153 if let Some(partition_of) = &self.partition_of {
3154 write!(f, " PARTITION OF {partition_of}")?;
3155 }
3156 if let Some(on_cluster) = &self.on_cluster {
3157 write!(f, " ON CLUSTER {on_cluster}")?;
3158 }
3159 if !self.columns.is_empty() || !self.constraints.is_empty() {
3160 f.write_str(" (")?;
3161 NewLine.fmt(f)?;
3162 Indent(DisplayCommaSeparated(&self.columns)).fmt(f)?;
3163 if !self.columns.is_empty() && !self.constraints.is_empty() {
3164 f.write_str(",")?;
3165 SpaceOrNewline.fmt(f)?;
3166 }
3167 Indent(DisplayCommaSeparated(&self.constraints)).fmt(f)?;
3168 NewLine.fmt(f)?;
3169 f.write_str(")")?;
3170 } else if self.query.is_none()
3171 && self.like.is_none()
3172 && self.clone.is_none()
3173 && self.partition_of.is_none()
3174 {
3175 f.write_str(" ()")?;
3177 } else if let Some(CreateTableLikeKind::Parenthesized(like_in_columns_list)) = &self.like {
3178 write!(f, " ({like_in_columns_list})")?;
3179 }
3180 if let Some(for_values) = &self.for_values {
3181 write!(f, " {for_values}")?;
3182 }
3183
3184 if let Some(comment) = &self.comment {
3187 write!(f, " COMMENT '{comment}'")?;
3188 }
3189
3190 if self.without_rowid {
3192 write!(f, " WITHOUT ROWID")?;
3193 }
3194
3195 if let Some(CreateTableLikeKind::Plain(like)) = &self.like {
3196 write!(f, " {like}")?;
3197 }
3198
3199 if let Some(c) = &self.clone {
3200 write!(f, " CLONE {c}")?;
3201 }
3202
3203 if let Some(version) = &self.version {
3204 write!(f, " {version}")?;
3205 }
3206
3207 match &self.hive_distribution {
3208 HiveDistributionStyle::PARTITIONED { columns } => {
3209 write!(f, " PARTITIONED BY ({})", display_comma_separated(columns))?;
3210 }
3211 HiveDistributionStyle::SKEWED {
3212 columns,
3213 on,
3214 stored_as_directories,
3215 } => {
3216 write!(
3217 f,
3218 " SKEWED BY ({})) ON ({})",
3219 display_comma_separated(columns),
3220 display_comma_separated(on)
3221 )?;
3222 if *stored_as_directories {
3223 write!(f, " STORED AS DIRECTORIES")?;
3224 }
3225 }
3226 _ => (),
3227 }
3228
3229 if let Some(clustered_by) = &self.clustered_by {
3230 write!(f, " {clustered_by}")?;
3231 }
3232
3233 if let Some(HiveFormat {
3234 row_format,
3235 serde_properties,
3236 storage,
3237 location,
3238 }) = &self.hive_formats
3239 {
3240 match row_format {
3241 Some(HiveRowFormat::SERDE { class }) => write!(f, " ROW FORMAT SERDE '{class}'")?,
3242 Some(HiveRowFormat::DELIMITED { delimiters }) => {
3243 write!(f, " ROW FORMAT DELIMITED")?;
3244 if !delimiters.is_empty() {
3245 write!(f, " {}", display_separated(delimiters, " "))?;
3246 }
3247 }
3248 None => (),
3249 }
3250 match storage {
3251 Some(HiveIOFormat::IOF {
3252 input_format,
3253 output_format,
3254 }) => write!(
3255 f,
3256 " STORED AS INPUTFORMAT {input_format} OUTPUTFORMAT {output_format}"
3257 )?,
3258 Some(HiveIOFormat::FileFormat { format }) if !self.external => {
3259 write!(f, " STORED AS {format}")?
3260 }
3261 Some(HiveIOFormat::Using { format }) => write!(f, " USING {format}")?,
3262 _ => (),
3263 }
3264 if let Some(serde_properties) = serde_properties.as_ref() {
3265 write!(
3266 f,
3267 " WITH SERDEPROPERTIES ({})",
3268 display_comma_separated(serde_properties)
3269 )?;
3270 }
3271 if !self.external {
3272 if let Some(loc) = location {
3273 write!(f, " LOCATION '{loc}'")?;
3274 }
3275 }
3276 }
3277 if self.external {
3278 if let Some(file_format) = self.file_format {
3279 write!(f, " STORED AS {file_format}")?;
3280 }
3281 if let Some(location) = &self.location {
3282 write!(f, " LOCATION '{location}'")?;
3283 }
3284 }
3285
3286 match &self.table_options {
3287 options @ CreateTableOptions::With(_)
3288 | options @ CreateTableOptions::Plain(_)
3289 | options @ CreateTableOptions::TableProperties(_) => write!(f, " {options}")?,
3290 _ => (),
3291 }
3292
3293 if let Some(primary_key) = &self.primary_key {
3294 write!(f, " PRIMARY KEY {primary_key}")?;
3295 }
3296 if let Some(order_by) = &self.order_by {
3297 write!(f, " ORDER BY {order_by}")?;
3298 }
3299 if let Some(inherits) = &self.inherits {
3300 write!(f, " INHERITS ({})", display_comma_separated(inherits))?;
3301 }
3302 if let Some(partition_by) = self.partition_by.as_ref() {
3303 write!(f, " PARTITION BY {partition_by}")?;
3304 }
3305 if let Some(cluster_by) = self.cluster_by.as_ref() {
3306 write!(f, " CLUSTER BY {cluster_by}")?;
3307 }
3308 if let Some(with_connection) = &self.with_connection {
3309 write!(f, " WITH CONNECTION {with_connection}")?;
3310 }
3311 if let options @ CreateTableOptions::Options(_) = &self.table_options {
3312 write!(f, " {options}")?;
3313 }
3314 if let Some(external_volume) = self.external_volume.as_ref() {
3315 write!(f, " EXTERNAL_VOLUME='{external_volume}'")?;
3316 }
3317
3318 if let Some(catalog) = self.catalog.as_ref() {
3319 write!(f, " CATALOG='{catalog}'")?;
3320 }
3321
3322 if self.iceberg {
3323 if let Some(base_location) = self.base_location.as_ref() {
3324 write!(f, " BASE_LOCATION='{base_location}'")?;
3325 }
3326 }
3327
3328 if let Some(catalog_sync) = self.catalog_sync.as_ref() {
3329 write!(f, " CATALOG_SYNC='{catalog_sync}'")?;
3330 }
3331
3332 if let Some(storage_serialization_policy) = self.storage_serialization_policy.as_ref() {
3333 write!(
3334 f,
3335 " STORAGE_SERIALIZATION_POLICY={storage_serialization_policy}"
3336 )?;
3337 }
3338
3339 if self.copy_grants {
3340 write!(f, " COPY GRANTS")?;
3341 }
3342
3343 if let Some(is_enabled) = self.enable_schema_evolution {
3344 write!(
3345 f,
3346 " ENABLE_SCHEMA_EVOLUTION={}",
3347 if is_enabled { "TRUE" } else { "FALSE" }
3348 )?;
3349 }
3350
3351 if let Some(is_enabled) = self.change_tracking {
3352 write!(
3353 f,
3354 " CHANGE_TRACKING={}",
3355 if is_enabled { "TRUE" } else { "FALSE" }
3356 )?;
3357 }
3358
3359 if let Some(data_retention_time_in_days) = self.data_retention_time_in_days {
3360 write!(
3361 f,
3362 " DATA_RETENTION_TIME_IN_DAYS={data_retention_time_in_days}",
3363 )?;
3364 }
3365
3366 if let Some(max_data_extension_time_in_days) = self.max_data_extension_time_in_days {
3367 write!(
3368 f,
3369 " MAX_DATA_EXTENSION_TIME_IN_DAYS={max_data_extension_time_in_days}",
3370 )?;
3371 }
3372
3373 if let Some(default_ddl_collation) = &self.default_ddl_collation {
3374 write!(f, " DEFAULT_DDL_COLLATION='{default_ddl_collation}'",)?;
3375 }
3376
3377 if let Some(with_aggregation_policy) = &self.with_aggregation_policy {
3378 write!(f, " WITH AGGREGATION POLICY {with_aggregation_policy}",)?;
3379 }
3380
3381 if let Some(row_access_policy) = &self.with_row_access_policy {
3382 write!(f, " {row_access_policy}",)?;
3383 }
3384
3385 if let Some(storage_lifecycle_policy) = &self.with_storage_lifecycle_policy {
3386 write!(f, " {storage_lifecycle_policy}",)?;
3387 }
3388
3389 if let Some(tag) = &self.with_tags {
3390 write!(f, " WITH TAG ({})", display_comma_separated(tag.as_slice()))?;
3391 }
3392
3393 if let Some(target_lag) = &self.target_lag {
3394 write!(f, " TARGET_LAG='{target_lag}'")?;
3395 }
3396
3397 if let Some(warehouse) = &self.warehouse {
3398 write!(f, " WAREHOUSE={warehouse}")?;
3399 }
3400
3401 if let Some(refresh_mode) = &self.refresh_mode {
3402 write!(f, " REFRESH_MODE={refresh_mode}")?;
3403 }
3404
3405 if let Some(initialize) = &self.initialize {
3406 write!(f, " INITIALIZE={initialize}")?;
3407 }
3408
3409 if self.require_user {
3410 write!(f, " REQUIRE USER")?;
3411 }
3412
3413 if self.on_commit.is_some() {
3414 let on_commit = match self.on_commit {
3415 Some(OnCommit::DeleteRows) => "ON COMMIT DELETE ROWS",
3416 Some(OnCommit::PreserveRows) => "ON COMMIT PRESERVE ROWS",
3417 Some(OnCommit::Drop) => "ON COMMIT DROP",
3418 None => "",
3419 };
3420 write!(f, " {on_commit}")?;
3421 }
3422 if self.strict {
3423 write!(f, " STRICT")?;
3424 }
3425 if let Some(backup) = self.backup {
3426 write!(f, " BACKUP {}", if backup { "YES" } else { "NO" })?;
3427 }
3428 if let Some(diststyle) = &self.diststyle {
3429 write!(f, " DISTSTYLE {diststyle}")?;
3430 }
3431 if let Some(distkey) = &self.distkey {
3432 write!(f, " DISTKEY({distkey})")?;
3433 }
3434 if let Some(sortkey) = &self.sortkey {
3435 write!(f, " SORTKEY({})", display_comma_separated(sortkey))?;
3436 }
3437 if let Some(query) = &self.query {
3438 write!(f, " AS {query}")?;
3439 }
3440 if let Some(with_data) = &self.with_data {
3441 write!(f, " {with_data}")?;
3442 }
3443 Ok(())
3444 }
3445}
3446
3447#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
3451#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3452#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3453pub struct WithData {
3454 pub data: bool,
3456 pub statistics: Option<bool>,
3459}
3460
3461impl fmt::Display for WithData {
3462 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3463 f.write_str("WITH ")?;
3464 if !self.data {
3465 f.write_str("NO ")?;
3466 }
3467 f.write_str("DATA")?;
3468 if let Some(stats) = self.statistics {
3469 f.write_str(" AND ")?;
3470 if !stats {
3471 f.write_str("NO ")?;
3472 }
3473 f.write_str("STATISTICS")?;
3474 }
3475 Ok(())
3476 }
3477}
3478
3479#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3485#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3486#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3487pub enum ForValues {
3488 In(Vec<Expr>),
3490 From {
3492 from: Vec<PartitionBoundValue>,
3494 to: Vec<PartitionBoundValue>,
3496 },
3497 With {
3499 modulus: u64,
3501 remainder: u64,
3503 },
3504 Default,
3506}
3507
3508impl fmt::Display for ForValues {
3509 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3510 match self {
3511 ForValues::In(values) => {
3512 write!(f, "FOR VALUES IN ({})", display_comma_separated(values))
3513 }
3514 ForValues::From { from, to } => {
3515 write!(
3516 f,
3517 "FOR VALUES FROM ({}) TO ({})",
3518 display_comma_separated(from),
3519 display_comma_separated(to)
3520 )
3521 }
3522 ForValues::With { modulus, remainder } => {
3523 write!(
3524 f,
3525 "FOR VALUES WITH (MODULUS {modulus}, REMAINDER {remainder})"
3526 )
3527 }
3528 ForValues::Default => write!(f, "DEFAULT"),
3529 }
3530 }
3531}
3532
3533#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3538#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3539#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3540pub enum PartitionBoundValue {
3541 Expr(Expr),
3543 MinValue,
3545 MaxValue,
3547}
3548
3549impl fmt::Display for PartitionBoundValue {
3550 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3551 match self {
3552 PartitionBoundValue::Expr(expr) => write!(f, "{expr}"),
3553 PartitionBoundValue::MinValue => write!(f, "MINVALUE"),
3554 PartitionBoundValue::MaxValue => write!(f, "MAXVALUE"),
3555 }
3556 }
3557}
3558
3559#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3563#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3564#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3565pub enum DistStyle {
3566 Auto,
3568 Even,
3570 Key,
3572 All,
3574}
3575
3576impl fmt::Display for DistStyle {
3577 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3578 match self {
3579 DistStyle::Auto => write!(f, "AUTO"),
3580 DistStyle::Even => write!(f, "EVEN"),
3581 DistStyle::Key => write!(f, "KEY"),
3582 DistStyle::All => write!(f, "ALL"),
3583 }
3584 }
3585}
3586
3587#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3588#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3589#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3590pub struct CreateDomain {
3603 pub name: ObjectName,
3605 pub data_type: DataType,
3607 pub collation: Option<Ident>,
3609 pub default: Option<Expr>,
3611 pub constraints: Vec<TableConstraint>,
3613}
3614
3615impl fmt::Display for CreateDomain {
3616 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3617 write!(
3618 f,
3619 "CREATE DOMAIN {name} AS {data_type}",
3620 name = self.name,
3621 data_type = self.data_type
3622 )?;
3623 if let Some(collation) = &self.collation {
3624 write!(f, " COLLATE {collation}")?;
3625 }
3626 if let Some(default) = &self.default {
3627 write!(f, " DEFAULT {default}")?;
3628 }
3629 if !self.constraints.is_empty() {
3630 write!(f, " {}", display_separated(&self.constraints, " "))?;
3631 }
3632 Ok(())
3633 }
3634}
3635
3636#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3638#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3639#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3640pub enum FunctionReturnType {
3641 DataType(DataType),
3643 SetOf(DataType),
3647}
3648
3649impl fmt::Display for FunctionReturnType {
3650 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3651 match self {
3652 FunctionReturnType::DataType(data_type) => write!(f, "{data_type}"),
3653 FunctionReturnType::SetOf(data_type) => write!(f, "SETOF {data_type}"),
3654 }
3655 }
3656}
3657
3658#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3659#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3660#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3661pub struct CreateFunction {
3663 pub or_alter: bool,
3667 pub or_replace: bool,
3669 pub temporary: bool,
3671 pub if_not_exists: bool,
3673 pub name: ObjectName,
3675 pub args: Option<Vec<OperateFunctionArg>>,
3677 pub return_type: Option<FunctionReturnType>,
3679 pub function_body: Option<CreateFunctionBody>,
3687 pub behavior: Option<FunctionBehavior>,
3693 pub called_on_null: Option<FunctionCalledOnNull>,
3697 pub parallel: Option<FunctionParallel>,
3701 pub security: Option<FunctionSecurity>,
3705 pub set_params: Vec<FunctionDefinitionSetParam>,
3709 pub using: Option<CreateFunctionUsing>,
3711 pub language: Option<Ident>,
3719 pub determinism_specifier: Option<FunctionDeterminismSpecifier>,
3723 pub options: Option<Vec<SqlOption>>,
3727 pub remote_connection: Option<ObjectName>,
3737}
3738
3739impl fmt::Display for CreateFunction {
3740 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3741 write!(
3742 f,
3743 "CREATE {or_alter}{or_replace}{temp}FUNCTION {if_not_exists}{name}",
3744 name = self.name,
3745 temp = if self.temporary { "TEMPORARY " } else { "" },
3746 or_alter = if self.or_alter { "OR ALTER " } else { "" },
3747 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3748 if_not_exists = if self.if_not_exists {
3749 "IF NOT EXISTS "
3750 } else {
3751 ""
3752 },
3753 )?;
3754 if let Some(args) = &self.args {
3755 write!(f, "({})", display_comma_separated(args))?;
3756 }
3757 if let Some(return_type) = &self.return_type {
3758 write!(f, " RETURNS {return_type}")?;
3759 }
3760 if let Some(determinism_specifier) = &self.determinism_specifier {
3761 write!(f, " {determinism_specifier}")?;
3762 }
3763 if let Some(language) = &self.language {
3764 write!(f, " LANGUAGE {language}")?;
3765 }
3766 if let Some(behavior) = &self.behavior {
3767 write!(f, " {behavior}")?;
3768 }
3769 if let Some(called_on_null) = &self.called_on_null {
3770 write!(f, " {called_on_null}")?;
3771 }
3772 if let Some(parallel) = &self.parallel {
3773 write!(f, " {parallel}")?;
3774 }
3775 if let Some(security) = &self.security {
3776 write!(f, " {security}")?;
3777 }
3778 for set_param in &self.set_params {
3779 write!(f, " {set_param}")?;
3780 }
3781 if let Some(remote_connection) = &self.remote_connection {
3782 write!(f, " REMOTE WITH CONNECTION {remote_connection}")?;
3783 }
3784 if let Some(CreateFunctionBody::AsBeforeOptions { body, link_symbol }) = &self.function_body
3785 {
3786 write!(f, " AS {body}")?;
3787 if let Some(link_symbol) = link_symbol {
3788 write!(f, ", {link_symbol}")?;
3789 }
3790 }
3791 if let Some(CreateFunctionBody::Return(function_body)) = &self.function_body {
3792 write!(f, " RETURN {function_body}")?;
3793 }
3794 if let Some(CreateFunctionBody::AsReturnExpr(function_body)) = &self.function_body {
3795 write!(f, " AS RETURN {function_body}")?;
3796 }
3797 if let Some(CreateFunctionBody::AsReturnSelect(function_body)) = &self.function_body {
3798 write!(f, " AS RETURN {function_body}")?;
3799 }
3800 if let Some(using) = &self.using {
3801 write!(f, " {using}")?;
3802 }
3803 if let Some(options) = &self.options {
3804 write!(
3805 f,
3806 " OPTIONS({})",
3807 display_comma_separated(options.as_slice())
3808 )?;
3809 }
3810 if let Some(CreateFunctionBody::AsAfterOptions(function_body)) = &self.function_body {
3811 write!(f, " AS {function_body}")?;
3812 }
3813 if let Some(CreateFunctionBody::AsBeginEnd(bes)) = &self.function_body {
3814 write!(f, " AS {bes}")?;
3815 }
3816 Ok(())
3817 }
3818}
3819
3820#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3830#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3831#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3832pub struct CreateConnector {
3833 pub name: Ident,
3835 pub if_not_exists: bool,
3837 pub connector_type: Option<String>,
3839 pub url: Option<String>,
3841 pub comment: Option<CommentDef>,
3843 pub with_dcproperties: Option<Vec<SqlOption>>,
3845}
3846
3847impl fmt::Display for CreateConnector {
3848 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3849 write!(
3850 f,
3851 "CREATE CONNECTOR {if_not_exists}{name}",
3852 if_not_exists = if self.if_not_exists {
3853 "IF NOT EXISTS "
3854 } else {
3855 ""
3856 },
3857 name = self.name,
3858 )?;
3859
3860 if let Some(connector_type) = &self.connector_type {
3861 write!(f, " TYPE '{connector_type}'")?;
3862 }
3863
3864 if let Some(url) = &self.url {
3865 write!(f, " URL '{url}'")?;
3866 }
3867
3868 if let Some(comment) = &self.comment {
3869 write!(f, " COMMENT = '{comment}'")?;
3870 }
3871
3872 if let Some(with_dcproperties) = &self.with_dcproperties {
3873 write!(
3874 f,
3875 " WITH DCPROPERTIES({})",
3876 display_comma_separated(with_dcproperties)
3877 )?;
3878 }
3879
3880 Ok(())
3881 }
3882}
3883
3884#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3889#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3890#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3891pub enum AlterSchemaOperation {
3892 SetDefaultCollate {
3894 collate: Expr,
3896 },
3897 AddReplica {
3899 replica: Ident,
3901 options: Option<Vec<SqlOption>>,
3903 },
3904 DropReplica {
3906 replica: Ident,
3908 },
3909 SetOptionsParens {
3911 options: Vec<SqlOption>,
3913 },
3914 Rename {
3916 name: ObjectName,
3918 },
3919 OwnerTo {
3921 owner: Owner,
3923 },
3924}
3925
3926impl fmt::Display for AlterSchemaOperation {
3927 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3928 match self {
3929 AlterSchemaOperation::SetDefaultCollate { collate } => {
3930 write!(f, "SET DEFAULT COLLATE {collate}")
3931 }
3932 AlterSchemaOperation::AddReplica { replica, options } => {
3933 write!(f, "ADD REPLICA {replica}")?;
3934 if let Some(options) = options {
3935 write!(f, " OPTIONS ({})", display_comma_separated(options))?;
3936 }
3937 Ok(())
3938 }
3939 AlterSchemaOperation::DropReplica { replica } => write!(f, "DROP REPLICA {replica}"),
3940 AlterSchemaOperation::SetOptionsParens { options } => {
3941 write!(f, "SET OPTIONS ({})", display_comma_separated(options))
3942 }
3943 AlterSchemaOperation::Rename { name } => write!(f, "RENAME TO {name}"),
3944 AlterSchemaOperation::OwnerTo { owner } => write!(f, "OWNER TO {owner}"),
3945 }
3946 }
3947}
3948#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3954#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3955#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3956pub enum RenameTableNameKind {
3957 As(ObjectName),
3959 To(ObjectName),
3961}
3962
3963impl fmt::Display for RenameTableNameKind {
3964 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3965 match self {
3966 RenameTableNameKind::As(name) => write!(f, "AS {name}"),
3967 RenameTableNameKind::To(name) => write!(f, "TO {name}"),
3968 }
3969 }
3970}
3971
3972#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3973#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3974#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3975pub struct AlterSchema {
3977 pub name: ObjectName,
3979 pub if_exists: bool,
3981 pub operations: Vec<AlterSchemaOperation>,
3983}
3984
3985impl fmt::Display for AlterSchema {
3986 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3987 write!(f, "ALTER SCHEMA ")?;
3988 if self.if_exists {
3989 write!(f, "IF EXISTS ")?;
3990 }
3991 write!(f, "{}", self.name)?;
3992 for operation in &self.operations {
3993 write!(f, " {operation}")?;
3994 }
3995
3996 Ok(())
3997 }
3998}
3999
4000impl Spanned for RenameTableNameKind {
4001 fn span(&self) -> Span {
4002 match self {
4003 RenameTableNameKind::As(name) => name.span(),
4004 RenameTableNameKind::To(name) => name.span(),
4005 }
4006 }
4007}
4008
4009#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
4010#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4011#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4012pub enum TriggerObjectKind {
4014 For(TriggerObject),
4016 ForEach(TriggerObject),
4018}
4019
4020impl Display for TriggerObjectKind {
4021 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4022 match self {
4023 TriggerObjectKind::For(obj) => write!(f, "FOR {obj}"),
4024 TriggerObjectKind::ForEach(obj) => write!(f, "FOR EACH {obj}"),
4025 }
4026 }
4027}
4028
4029#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4030#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4031#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4032pub struct CreateTrigger {
4046 pub or_alter: bool,
4050 pub temporary: bool,
4067 pub or_replace: bool,
4077 pub is_constraint: bool,
4079 pub name: ObjectName,
4081 pub period: Option<TriggerPeriod>,
4110 pub period_before_table: bool,
4121 pub events: Vec<TriggerEvent>,
4123 pub table_name: ObjectName,
4125 pub referenced_table_name: Option<ObjectName>,
4128 pub referencing: Vec<TriggerReferencing>,
4130 pub trigger_object: Option<TriggerObjectKind>,
4135 pub condition: Option<Expr>,
4137 pub exec_body: Option<TriggerExecBody>,
4139 pub statements_as: bool,
4141 pub statements: Option<ConditionalStatements>,
4143 pub characteristics: Option<ConstraintCharacteristics>,
4145}
4146
4147impl Display for CreateTrigger {
4148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4149 let CreateTrigger {
4150 or_alter,
4151 temporary,
4152 or_replace,
4153 is_constraint,
4154 name,
4155 period_before_table,
4156 period,
4157 events,
4158 table_name,
4159 referenced_table_name,
4160 referencing,
4161 trigger_object,
4162 condition,
4163 exec_body,
4164 statements_as,
4165 statements,
4166 characteristics,
4167 } = self;
4168 write!(
4169 f,
4170 "CREATE {temporary}{or_alter}{or_replace}{is_constraint}TRIGGER {name} ",
4171 temporary = if *temporary { "TEMPORARY " } else { "" },
4172 or_alter = if *or_alter { "OR ALTER " } else { "" },
4173 or_replace = if *or_replace { "OR REPLACE " } else { "" },
4174 is_constraint = if *is_constraint { "CONSTRAINT " } else { "" },
4175 )?;
4176
4177 if *period_before_table {
4178 if let Some(p) = period {
4179 write!(f, "{p} ")?;
4180 }
4181 if !events.is_empty() {
4182 write!(f, "{} ", display_separated(events, " OR "))?;
4183 }
4184 write!(f, "ON {table_name}")?;
4185 } else {
4186 write!(f, "ON {table_name} ")?;
4187 if let Some(p) = period {
4188 write!(f, "{p}")?;
4189 }
4190 if !events.is_empty() {
4191 write!(f, " {}", display_separated(events, ", "))?;
4192 }
4193 }
4194
4195 if let Some(referenced_table_name) = referenced_table_name {
4196 write!(f, " FROM {referenced_table_name}")?;
4197 }
4198
4199 if let Some(characteristics) = characteristics {
4200 write!(f, " {characteristics}")?;
4201 }
4202
4203 if !referencing.is_empty() {
4204 write!(f, " REFERENCING {}", display_separated(referencing, " "))?;
4205 }
4206
4207 if let Some(trigger_object) = trigger_object {
4208 write!(f, " {trigger_object}")?;
4209 }
4210 if let Some(condition) = condition {
4211 write!(f, " WHEN {condition}")?;
4212 }
4213 if let Some(exec_body) = exec_body {
4214 write!(f, " EXECUTE {exec_body}")?;
4215 }
4216 if let Some(statements) = statements {
4217 if *statements_as {
4218 write!(f, " AS")?;
4219 }
4220 write!(f, " {statements}")?;
4221 }
4222 Ok(())
4223 }
4224}
4225
4226#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4227#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4228#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4229pub struct DropTrigger {
4236 pub if_exists: bool,
4238 pub trigger_name: ObjectName,
4240 pub table_name: Option<ObjectName>,
4242 pub option: Option<ReferentialAction>,
4244}
4245
4246impl fmt::Display for DropTrigger {
4247 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4248 let DropTrigger {
4249 if_exists,
4250 trigger_name,
4251 table_name,
4252 option,
4253 } = self;
4254 write!(f, "DROP TRIGGER")?;
4255 if *if_exists {
4256 write!(f, " IF EXISTS")?;
4257 }
4258 match &table_name {
4259 Some(table_name) => write!(f, " {trigger_name} ON {table_name}")?,
4260 None => write!(f, " {trigger_name}")?,
4261 };
4262 if let Some(option) = option {
4263 write!(f, " {option}")?;
4264 }
4265 Ok(())
4266 }
4267}
4268
4269#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4275#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4276#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4277pub struct Truncate {
4278 pub table_names: Vec<super::TruncateTableTarget>,
4280 pub partitions: Option<Vec<Expr>>,
4282 pub table: bool,
4284 pub if_exists: bool,
4286 pub identity: Option<super::TruncateIdentityOption>,
4288 pub cascade: Option<super::CascadeOption>,
4290 pub on_cluster: Option<Ident>,
4293}
4294
4295impl fmt::Display for Truncate {
4296 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4297 let table = if self.table { "TABLE " } else { "" };
4298 let if_exists = if self.if_exists { "IF EXISTS " } else { "" };
4299
4300 write!(
4301 f,
4302 "TRUNCATE {table}{if_exists}{table_names}",
4303 table_names = display_comma_separated(&self.table_names)
4304 )?;
4305
4306 if let Some(identity) = &self.identity {
4307 match identity {
4308 super::TruncateIdentityOption::Restart => write!(f, " RESTART IDENTITY")?,
4309 super::TruncateIdentityOption::Continue => write!(f, " CONTINUE IDENTITY")?,
4310 }
4311 }
4312 if let Some(cascade) = &self.cascade {
4313 match cascade {
4314 super::CascadeOption::Cascade => write!(f, " CASCADE")?,
4315 super::CascadeOption::Restrict => write!(f, " RESTRICT")?,
4316 }
4317 }
4318
4319 if let Some(ref parts) = &self.partitions {
4320 if !parts.is_empty() {
4321 write!(f, " PARTITION ({})", display_comma_separated(parts))?;
4322 }
4323 }
4324 if let Some(on_cluster) = &self.on_cluster {
4325 write!(f, " ON CLUSTER {on_cluster}")?;
4326 }
4327 Ok(())
4328 }
4329}
4330
4331impl Spanned for Truncate {
4332 fn span(&self) -> Span {
4333 Span::union_iter(
4334 self.table_names.iter().map(|i| i.name.span()).chain(
4335 self.partitions
4336 .iter()
4337 .flat_map(|i| i.iter().map(|k| k.span())),
4338 ),
4339 )
4340 }
4341}
4342
4343#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4350#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4351#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4352pub struct Msck {
4353 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4355 pub table_name: ObjectName,
4356 pub repair: bool,
4358 pub partition_action: Option<super::AddDropSync>,
4360}
4361
4362impl fmt::Display for Msck {
4363 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4364 write!(
4365 f,
4366 "MSCK {repair}TABLE {table}",
4367 repair = if self.repair { "REPAIR " } else { "" },
4368 table = self.table_name
4369 )?;
4370 if let Some(pa) = &self.partition_action {
4371 write!(f, " {pa}")?;
4372 }
4373 Ok(())
4374 }
4375}
4376
4377impl Spanned for Msck {
4378 fn span(&self) -> Span {
4379 self.table_name.span()
4380 }
4381}
4382
4383#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4385#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4386#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4387pub struct CreateView {
4388 pub or_alter: bool,
4392 pub or_replace: bool,
4394 pub materialized: bool,
4396 pub secure: bool,
4399 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4401 pub name: ObjectName,
4402 pub name_before_not_exists: bool,
4413 pub columns: Vec<ViewColumnDef>,
4415 pub query: Box<Query>,
4417 pub options: CreateTableOptions,
4419 pub cluster_by: Vec<Ident>,
4421 pub comment: Option<String>,
4424 pub with_no_schema_binding: bool,
4426 pub if_not_exists: bool,
4428 pub temporary: bool,
4430 pub copy_grants: bool,
4433 pub to: Option<ObjectName>,
4436 pub params: Option<CreateViewParams>,
4438}
4439
4440impl fmt::Display for CreateView {
4441 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4442 write!(
4443 f,
4444 "CREATE {or_alter}{or_replace}",
4445 or_alter = if self.or_alter { "OR ALTER " } else { "" },
4446 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
4447 )?;
4448 if let Some(ref params) = self.params {
4449 params.fmt(f)?;
4450 }
4451 write!(
4452 f,
4453 "{secure}{materialized}{temporary}VIEW {if_not_and_name}{to}",
4454 if_not_and_name = if self.if_not_exists {
4455 if self.name_before_not_exists {
4456 format!("{} IF NOT EXISTS", self.name)
4457 } else {
4458 format!("IF NOT EXISTS {}", self.name)
4459 }
4460 } else {
4461 format!("{}", self.name)
4462 },
4463 secure = if self.secure { "SECURE " } else { "" },
4464 materialized = if self.materialized {
4465 "MATERIALIZED "
4466 } else {
4467 ""
4468 },
4469 temporary = if self.temporary { "TEMPORARY " } else { "" },
4470 to = self
4471 .to
4472 .as_ref()
4473 .map(|to| format!(" TO {to}"))
4474 .unwrap_or_default()
4475 )?;
4476 if self.copy_grants {
4477 write!(f, " COPY GRANTS")?;
4478 }
4479 if !self.columns.is_empty() {
4480 write!(f, " ({})", display_comma_separated(&self.columns))?;
4481 }
4482 if matches!(self.options, CreateTableOptions::With(_)) {
4483 write!(f, " {}", self.options)?;
4484 }
4485 if let Some(ref comment) = self.comment {
4486 write!(f, " COMMENT = '{}'", escape_single_quote_string(comment))?;
4487 }
4488 if !self.cluster_by.is_empty() {
4489 write!(
4490 f,
4491 " CLUSTER BY ({})",
4492 display_comma_separated(&self.cluster_by)
4493 )?;
4494 }
4495 if matches!(self.options, CreateTableOptions::Options(_)) {
4496 write!(f, " {}", self.options)?;
4497 }
4498 f.write_str(" AS")?;
4499 SpaceOrNewline.fmt(f)?;
4500 self.query.fmt(f)?;
4501 if self.with_no_schema_binding {
4502 write!(f, " WITH NO SCHEMA BINDING")?;
4503 }
4504 Ok(())
4505 }
4506}
4507
4508#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4511#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4512#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4513pub struct CreateExtension {
4514 pub name: Ident,
4516 pub if_not_exists: bool,
4518 pub cascade: bool,
4520 pub schema: Option<Ident>,
4522 pub version: Option<Ident>,
4524}
4525
4526impl fmt::Display for CreateExtension {
4527 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4528 write!(
4529 f,
4530 "CREATE EXTENSION {if_not_exists}{name}",
4531 if_not_exists = if self.if_not_exists {
4532 "IF NOT EXISTS "
4533 } else {
4534 ""
4535 },
4536 name = self.name
4537 )?;
4538 if self.cascade || self.schema.is_some() || self.version.is_some() {
4539 write!(f, " WITH")?;
4540
4541 if let Some(name) = &self.schema {
4542 write!(f, " SCHEMA {name}")?;
4543 }
4544 if let Some(version) = &self.version {
4545 write!(f, " VERSION {version}")?;
4546 }
4547 if self.cascade {
4548 write!(f, " CASCADE")?;
4549 }
4550 }
4551
4552 Ok(())
4553 }
4554}
4555
4556impl Spanned for CreateExtension {
4557 fn span(&self) -> Span {
4558 Span::empty()
4559 }
4560}
4561
4562#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4570#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4571#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4572pub struct DropExtension {
4573 pub names: Vec<Ident>,
4575 pub if_exists: bool,
4577 pub cascade_or_restrict: Option<ReferentialAction>,
4579}
4580
4581impl fmt::Display for DropExtension {
4582 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4583 write!(f, "DROP EXTENSION")?;
4584 if self.if_exists {
4585 write!(f, " IF EXISTS")?;
4586 }
4587 write!(f, " {}", display_comma_separated(&self.names))?;
4588 if let Some(cascade_or_restrict) = &self.cascade_or_restrict {
4589 write!(f, " {cascade_or_restrict}")?;
4590 }
4591 Ok(())
4592 }
4593}
4594
4595impl Spanned for DropExtension {
4596 fn span(&self) -> Span {
4597 Span::empty()
4598 }
4599}
4600
4601#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4604#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4605#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4606pub struct CreateCollation {
4607 pub if_not_exists: bool,
4609 pub name: ObjectName,
4611 pub definition: CreateCollationDefinition,
4613}
4614
4615#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4617#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4618#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4619pub enum CreateCollationDefinition {
4620 From(ObjectName),
4626 Options(Vec<SqlOption>),
4632}
4633
4634impl fmt::Display for CreateCollation {
4635 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4636 write!(
4637 f,
4638 "CREATE COLLATION {if_not_exists}{name}",
4639 if_not_exists = if self.if_not_exists {
4640 "IF NOT EXISTS "
4641 } else {
4642 ""
4643 },
4644 name = self.name
4645 )?;
4646 match &self.definition {
4647 CreateCollationDefinition::From(existing_collation) => {
4648 write!(f, " FROM {existing_collation}")
4649 }
4650 CreateCollationDefinition::Options(options) => {
4651 write!(f, " ({})", display_comma_separated(options))
4652 }
4653 }
4654 }
4655}
4656
4657impl Spanned for CreateCollation {
4658 fn span(&self) -> Span {
4659 Span::empty()
4660 }
4661}
4662
4663#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4666#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4667#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4668pub struct AlterCollation {
4669 pub name: ObjectName,
4671 pub operation: AlterCollationOperation,
4673}
4674
4675#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4677#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4678#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4679pub enum AlterCollationOperation {
4680 RenameTo {
4686 new_name: Ident,
4688 },
4689 OwnerTo(Owner),
4695 SetSchema {
4701 schema_name: ObjectName,
4703 },
4704 RefreshVersion,
4710}
4711
4712impl fmt::Display for AlterCollationOperation {
4713 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4714 match self {
4715 AlterCollationOperation::RenameTo { new_name } => write!(f, "RENAME TO {new_name}"),
4716 AlterCollationOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
4717 AlterCollationOperation::SetSchema { schema_name } => {
4718 write!(f, "SET SCHEMA {schema_name}")
4719 }
4720 AlterCollationOperation::RefreshVersion => write!(f, "REFRESH VERSION"),
4721 }
4722 }
4723}
4724
4725impl fmt::Display for AlterCollation {
4726 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4727 write!(f, "ALTER COLLATION {} {}", self.name, self.operation)
4728 }
4729}
4730
4731impl Spanned for AlterCollation {
4732 fn span(&self) -> Span {
4733 Span::empty()
4734 }
4735}
4736
4737#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4740#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4741#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4742pub enum AlterTableType {
4743 Iceberg,
4746 Dynamic,
4749 External,
4752}
4753
4754#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4756#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4757#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4758pub struct AlterTable {
4759 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4761 pub name: ObjectName,
4762 pub if_exists: bool,
4764 pub only: bool,
4766 pub operations: Vec<AlterTableOperation>,
4768 pub location: Option<HiveSetLocation>,
4770 pub on_cluster: Option<Ident>,
4774 pub table_type: Option<AlterTableType>,
4776 pub end_token: AttachedToken,
4778}
4779
4780impl fmt::Display for AlterTable {
4781 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4782 match &self.table_type {
4783 Some(AlterTableType::Iceberg) => write!(f, "ALTER ICEBERG TABLE ")?,
4784 Some(AlterTableType::Dynamic) => write!(f, "ALTER DYNAMIC TABLE ")?,
4785 Some(AlterTableType::External) => write!(f, "ALTER EXTERNAL TABLE ")?,
4786 None => write!(f, "ALTER TABLE ")?,
4787 }
4788
4789 if self.if_exists {
4790 write!(f, "IF EXISTS ")?;
4791 }
4792 if self.only {
4793 write!(f, "ONLY ")?;
4794 }
4795 write!(f, "{} ", self.name)?;
4796 if let Some(cluster) = &self.on_cluster {
4797 write!(f, "ON CLUSTER {cluster} ")?;
4798 }
4799 write!(f, "{}", display_comma_separated(&self.operations))?;
4800 if let Some(loc) = &self.location {
4801 write!(f, " {loc}")?
4802 }
4803 Ok(())
4804 }
4805}
4806
4807#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4809#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4810#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4811pub struct DropFunction {
4812 pub if_exists: bool,
4814 pub func_desc: Vec<FunctionDesc>,
4816 pub drop_behavior: Option<DropBehavior>,
4818}
4819
4820impl fmt::Display for DropFunction {
4821 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4822 write!(
4823 f,
4824 "DROP FUNCTION{} {}",
4825 if self.if_exists { " IF EXISTS" } else { "" },
4826 display_comma_separated(&self.func_desc),
4827 )?;
4828 if let Some(op) = &self.drop_behavior {
4829 write!(f, " {op}")?;
4830 }
4831 Ok(())
4832 }
4833}
4834
4835impl Spanned for DropFunction {
4836 fn span(&self) -> Span {
4837 Span::empty()
4838 }
4839}
4840
4841#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4844#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4845#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4846pub struct CreateOperator {
4847 pub name: ObjectName,
4849 pub function: ObjectName,
4851 pub is_procedure: bool,
4853 pub left_arg: Option<DataType>,
4855 pub right_arg: Option<DataType>,
4857 pub options: Vec<OperatorOption>,
4859}
4860
4861#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4864#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4865#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4866pub struct CreateOperatorFamily {
4867 pub name: ObjectName,
4869 pub using: Ident,
4871}
4872
4873#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4876#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4877#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4878pub struct CreateOperatorClass {
4879 pub name: ObjectName,
4881 pub default: bool,
4883 pub for_type: DataType,
4885 pub using: Ident,
4887 pub family: Option<ObjectName>,
4889 pub items: Vec<OperatorClassItem>,
4891}
4892
4893impl fmt::Display for CreateOperator {
4894 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4895 write!(f, "CREATE OPERATOR {} (", self.name)?;
4896
4897 let function_keyword = if self.is_procedure {
4898 "PROCEDURE"
4899 } else {
4900 "FUNCTION"
4901 };
4902 let mut params = vec![format!("{} = {}", function_keyword, self.function)];
4903
4904 if let Some(left_arg) = &self.left_arg {
4905 params.push(format!("LEFTARG = {}", left_arg));
4906 }
4907 if let Some(right_arg) = &self.right_arg {
4908 params.push(format!("RIGHTARG = {}", right_arg));
4909 }
4910
4911 for option in &self.options {
4912 params.push(option.to_string());
4913 }
4914
4915 write!(f, "{}", params.join(", "))?;
4916 write!(f, ")")
4917 }
4918}
4919
4920impl fmt::Display for CreateOperatorFamily {
4921 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4922 write!(
4923 f,
4924 "CREATE OPERATOR FAMILY {} USING {}",
4925 self.name, self.using
4926 )
4927 }
4928}
4929
4930impl fmt::Display for CreateOperatorClass {
4931 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4932 write!(f, "CREATE OPERATOR CLASS {}", self.name)?;
4933 if self.default {
4934 write!(f, " DEFAULT")?;
4935 }
4936 write!(f, " FOR TYPE {} USING {}", self.for_type, self.using)?;
4937 if let Some(family) = &self.family {
4938 write!(f, " FAMILY {}", family)?;
4939 }
4940 write!(f, " AS {}", display_comma_separated(&self.items))
4941 }
4942}
4943
4944#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4946#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4947#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4948pub struct OperatorArgTypes {
4949 pub left: DataType,
4951 pub right: DataType,
4953}
4954
4955impl fmt::Display for OperatorArgTypes {
4956 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4957 write!(f, "{}, {}", self.left, self.right)
4958 }
4959}
4960
4961#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4963#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4964#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4965pub enum OperatorClassItem {
4966 Operator {
4968 strategy_number: u64,
4970 operator_name: ObjectName,
4972 op_types: Option<OperatorArgTypes>,
4974 purpose: Option<OperatorPurpose>,
4976 },
4977 Function {
4979 support_number: u64,
4981 op_types: Option<Vec<DataType>>,
4983 function_name: ObjectName,
4985 argument_types: Vec<DataType>,
4987 },
4988 Storage {
4990 storage_type: DataType,
4992 },
4993}
4994
4995#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4997#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4998#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4999pub enum OperatorPurpose {
5000 ForSearch,
5002 ForOrderBy {
5004 sort_family: ObjectName,
5006 },
5007}
5008
5009impl fmt::Display for OperatorClassItem {
5010 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5011 match self {
5012 OperatorClassItem::Operator {
5013 strategy_number,
5014 operator_name,
5015 op_types,
5016 purpose,
5017 } => {
5018 write!(f, "OPERATOR {strategy_number} {operator_name}")?;
5019 if let Some(types) = op_types {
5020 write!(f, " ({types})")?;
5021 }
5022 if let Some(purpose) = purpose {
5023 write!(f, " {purpose}")?;
5024 }
5025 Ok(())
5026 }
5027 OperatorClassItem::Function {
5028 support_number,
5029 op_types,
5030 function_name,
5031 argument_types,
5032 } => {
5033 write!(f, "FUNCTION {support_number}")?;
5034 if let Some(types) = op_types {
5035 write!(f, " ({})", display_comma_separated(types))?;
5036 }
5037 write!(f, " {function_name}")?;
5038 if !argument_types.is_empty() {
5039 write!(f, "({})", display_comma_separated(argument_types))?;
5040 }
5041 Ok(())
5042 }
5043 OperatorClassItem::Storage { storage_type } => {
5044 write!(f, "STORAGE {storage_type}")
5045 }
5046 }
5047 }
5048}
5049
5050impl fmt::Display for OperatorPurpose {
5051 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5052 match self {
5053 OperatorPurpose::ForSearch => write!(f, "FOR SEARCH"),
5054 OperatorPurpose::ForOrderBy { sort_family } => {
5055 write!(f, "FOR ORDER BY {sort_family}")
5056 }
5057 }
5058 }
5059}
5060
5061#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5064#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5065#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5066pub struct DropOperator {
5067 pub if_exists: bool,
5069 pub operators: Vec<DropOperatorSignature>,
5071 pub drop_behavior: Option<DropBehavior>,
5073}
5074
5075#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5077#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5078#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5079pub struct DropOperatorSignature {
5080 pub name: ObjectName,
5082 pub left_type: Option<DataType>,
5084 pub right_type: DataType,
5086}
5087
5088impl fmt::Display for DropOperatorSignature {
5089 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5090 write!(f, "{} (", self.name)?;
5091 if let Some(left_type) = &self.left_type {
5092 write!(f, "{}", left_type)?;
5093 } else {
5094 write!(f, "NONE")?;
5095 }
5096 write!(f, ", {})", self.right_type)
5097 }
5098}
5099
5100impl fmt::Display for DropOperator {
5101 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5102 write!(f, "DROP OPERATOR")?;
5103 if self.if_exists {
5104 write!(f, " IF EXISTS")?;
5105 }
5106 write!(f, " {}", display_comma_separated(&self.operators))?;
5107 if let Some(drop_behavior) = &self.drop_behavior {
5108 write!(f, " {}", drop_behavior)?;
5109 }
5110 Ok(())
5111 }
5112}
5113
5114impl Spanned for DropOperator {
5115 fn span(&self) -> Span {
5116 Span::empty()
5117 }
5118}
5119
5120#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5123#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5124#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5125pub struct DropOperatorFamily {
5126 pub if_exists: bool,
5128 pub names: Vec<ObjectName>,
5130 pub using: Ident,
5132 pub drop_behavior: Option<DropBehavior>,
5134}
5135
5136impl fmt::Display for DropOperatorFamily {
5137 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5138 write!(f, "DROP OPERATOR FAMILY")?;
5139 if self.if_exists {
5140 write!(f, " IF EXISTS")?;
5141 }
5142 write!(f, " {}", display_comma_separated(&self.names))?;
5143 write!(f, " USING {}", self.using)?;
5144 if let Some(drop_behavior) = &self.drop_behavior {
5145 write!(f, " {}", drop_behavior)?;
5146 }
5147 Ok(())
5148 }
5149}
5150
5151impl Spanned for DropOperatorFamily {
5152 fn span(&self) -> Span {
5153 Span::empty()
5154 }
5155}
5156
5157#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5160#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5161#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5162pub struct DropOperatorClass {
5163 pub if_exists: bool,
5165 pub names: Vec<ObjectName>,
5167 pub using: Ident,
5169 pub drop_behavior: Option<DropBehavior>,
5171}
5172
5173impl fmt::Display for DropOperatorClass {
5174 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5175 write!(f, "DROP OPERATOR CLASS")?;
5176 if self.if_exists {
5177 write!(f, " IF EXISTS")?;
5178 }
5179 write!(f, " {}", display_comma_separated(&self.names))?;
5180 write!(f, " USING {}", self.using)?;
5181 if let Some(drop_behavior) = &self.drop_behavior {
5182 write!(f, " {}", drop_behavior)?;
5183 }
5184 Ok(())
5185 }
5186}
5187
5188impl Spanned for DropOperatorClass {
5189 fn span(&self) -> Span {
5190 Span::empty()
5191 }
5192}
5193
5194#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5196#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5197#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5198pub enum OperatorFamilyItem {
5199 Operator {
5201 strategy_number: u64,
5203 operator_name: ObjectName,
5205 op_types: Vec<DataType>,
5207 purpose: Option<OperatorPurpose>,
5209 },
5210 Function {
5212 support_number: u64,
5214 op_types: Option<Vec<DataType>>,
5216 function_name: ObjectName,
5218 argument_types: Vec<DataType>,
5220 },
5221}
5222
5223#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5225#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5226#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5227pub enum OperatorFamilyDropItem {
5228 Operator {
5230 strategy_number: u64,
5232 op_types: Vec<DataType>,
5234 },
5235 Function {
5237 support_number: u64,
5239 op_types: Vec<DataType>,
5241 },
5242}
5243
5244impl fmt::Display for OperatorFamilyItem {
5245 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5246 match self {
5247 OperatorFamilyItem::Operator {
5248 strategy_number,
5249 operator_name,
5250 op_types,
5251 purpose,
5252 } => {
5253 write!(
5254 f,
5255 "OPERATOR {strategy_number} {operator_name} ({})",
5256 display_comma_separated(op_types)
5257 )?;
5258 if let Some(purpose) = purpose {
5259 write!(f, " {purpose}")?;
5260 }
5261 Ok(())
5262 }
5263 OperatorFamilyItem::Function {
5264 support_number,
5265 op_types,
5266 function_name,
5267 argument_types,
5268 } => {
5269 write!(f, "FUNCTION {support_number}")?;
5270 if let Some(types) = op_types {
5271 write!(f, " ({})", display_comma_separated(types))?;
5272 }
5273 write!(f, " {function_name}")?;
5274 if !argument_types.is_empty() {
5275 write!(f, "({})", display_comma_separated(argument_types))?;
5276 }
5277 Ok(())
5278 }
5279 }
5280 }
5281}
5282
5283impl fmt::Display for OperatorFamilyDropItem {
5284 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5285 match self {
5286 OperatorFamilyDropItem::Operator {
5287 strategy_number,
5288 op_types,
5289 } => {
5290 write!(
5291 f,
5292 "OPERATOR {strategy_number} ({})",
5293 display_comma_separated(op_types)
5294 )
5295 }
5296 OperatorFamilyDropItem::Function {
5297 support_number,
5298 op_types,
5299 } => {
5300 write!(
5301 f,
5302 "FUNCTION {support_number} ({})",
5303 display_comma_separated(op_types)
5304 )
5305 }
5306 }
5307 }
5308}
5309
5310#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5313#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5314#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5315pub struct AlterOperatorFamily {
5316 pub name: ObjectName,
5318 pub using: Ident,
5320 pub operation: AlterOperatorFamilyOperation,
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 enum AlterOperatorFamilyOperation {
5329 Add {
5331 items: Vec<OperatorFamilyItem>,
5333 },
5334 Drop {
5336 items: Vec<OperatorFamilyDropItem>,
5338 },
5339 RenameTo {
5341 new_name: ObjectName,
5343 },
5344 OwnerTo(Owner),
5346 SetSchema {
5348 schema_name: ObjectName,
5350 },
5351}
5352
5353impl fmt::Display for AlterOperatorFamily {
5354 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5355 write!(
5356 f,
5357 "ALTER OPERATOR FAMILY {} USING {}",
5358 self.name, self.using
5359 )?;
5360 write!(f, " {}", self.operation)
5361 }
5362}
5363
5364impl fmt::Display for AlterOperatorFamilyOperation {
5365 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5366 match self {
5367 AlterOperatorFamilyOperation::Add { items } => {
5368 write!(f, "ADD {}", display_comma_separated(items))
5369 }
5370 AlterOperatorFamilyOperation::Drop { items } => {
5371 write!(f, "DROP {}", display_comma_separated(items))
5372 }
5373 AlterOperatorFamilyOperation::RenameTo { new_name } => {
5374 write!(f, "RENAME TO {new_name}")
5375 }
5376 AlterOperatorFamilyOperation::OwnerTo(owner) => {
5377 write!(f, "OWNER TO {owner}")
5378 }
5379 AlterOperatorFamilyOperation::SetSchema { schema_name } => {
5380 write!(f, "SET SCHEMA {schema_name}")
5381 }
5382 }
5383 }
5384}
5385
5386impl Spanned for AlterOperatorFamily {
5387 fn span(&self) -> Span {
5388 Span::empty()
5389 }
5390}
5391
5392#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5395#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5396#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5397pub struct AlterOperatorClass {
5398 pub name: ObjectName,
5400 pub using: Ident,
5402 pub operation: AlterOperatorClassOperation,
5404}
5405
5406#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5408#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5409#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5410pub enum AlterOperatorClassOperation {
5411 RenameTo {
5414 new_name: ObjectName,
5416 },
5417 OwnerTo(Owner),
5419 SetSchema {
5422 schema_name: ObjectName,
5424 },
5425}
5426
5427impl fmt::Display for AlterOperatorClass {
5428 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5429 write!(f, "ALTER OPERATOR CLASS {} USING {}", self.name, self.using)?;
5430 write!(f, " {}", self.operation)
5431 }
5432}
5433
5434impl fmt::Display for AlterOperatorClassOperation {
5435 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5436 match self {
5437 AlterOperatorClassOperation::RenameTo { new_name } => {
5438 write!(f, "RENAME TO {new_name}")
5439 }
5440 AlterOperatorClassOperation::OwnerTo(owner) => {
5441 write!(f, "OWNER TO {owner}")
5442 }
5443 AlterOperatorClassOperation::SetSchema { schema_name } => {
5444 write!(f, "SET SCHEMA {schema_name}")
5445 }
5446 }
5447 }
5448}
5449
5450impl Spanned for AlterOperatorClass {
5451 fn span(&self) -> Span {
5452 Span::empty()
5453 }
5454}
5455
5456#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5458#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5459#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5460pub struct AlterFunction {
5461 pub kind: AlterFunctionKind,
5463 pub function: FunctionDesc,
5465 pub aggregate_order_by: Option<Vec<OperateFunctionArg>>,
5469 pub aggregate_star: bool,
5473 pub operation: AlterFunctionOperation,
5475}
5476
5477#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5479#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5480#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5481pub enum AlterFunctionKind {
5482 Function,
5484 Aggregate,
5486}
5487
5488impl fmt::Display for AlterFunctionKind {
5489 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5490 match self {
5491 Self::Function => write!(f, "FUNCTION"),
5492 Self::Aggregate => write!(f, "AGGREGATE"),
5493 }
5494 }
5495}
5496
5497#[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 enum AlterFunctionOperation {
5502 RenameTo {
5504 new_name: Ident,
5506 },
5507 OwnerTo(Owner),
5509 SetSchema {
5511 schema_name: ObjectName,
5513 },
5514 DependsOnExtension {
5516 no: bool,
5518 extension_name: ObjectName,
5520 },
5521 Actions {
5523 actions: Vec<AlterFunctionAction>,
5525 restrict: bool,
5527 },
5528}
5529
5530#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5532#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5533#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5534pub enum AlterFunctionAction {
5535 CalledOnNull(FunctionCalledOnNull),
5537 Behavior(FunctionBehavior),
5539 Leakproof(bool),
5541 Security {
5543 external: bool,
5545 security: FunctionSecurity,
5547 },
5548 Parallel(FunctionParallel),
5550 Cost(Expr),
5552 Rows(Expr),
5554 Support(ObjectName),
5556 Set(FunctionDefinitionSetParam),
5559 Reset(ResetConfig),
5561}
5562
5563impl fmt::Display for AlterFunction {
5564 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5565 write!(f, "ALTER {} ", self.kind)?;
5566 match self.kind {
5567 AlterFunctionKind::Function => {
5568 write!(f, "{} ", self.function)?;
5569 }
5570 AlterFunctionKind::Aggregate => {
5571 write!(f, "{}(", self.function.name)?;
5572 if self.aggregate_star {
5573 write!(f, "*")?;
5574 } else {
5575 if let Some(args) = &self.function.args {
5576 write!(f, "{}", display_comma_separated(args))?;
5577 }
5578 if let Some(order_by_args) = &self.aggregate_order_by {
5579 if self
5580 .function
5581 .args
5582 .as_ref()
5583 .is_some_and(|args| !args.is_empty())
5584 {
5585 write!(f, " ")?;
5586 }
5587 write!(f, "ORDER BY {}", display_comma_separated(order_by_args))?;
5588 }
5589 }
5590 write!(f, ") ")?;
5591 }
5592 }
5593 write!(f, "{}", self.operation)
5594 }
5595}
5596
5597impl fmt::Display for AlterFunctionOperation {
5598 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5599 match self {
5600 AlterFunctionOperation::RenameTo { new_name } => {
5601 write!(f, "RENAME TO {new_name}")
5602 }
5603 AlterFunctionOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
5604 AlterFunctionOperation::SetSchema { schema_name } => {
5605 write!(f, "SET SCHEMA {schema_name}")
5606 }
5607 AlterFunctionOperation::DependsOnExtension { no, extension_name } => {
5608 if *no {
5609 write!(f, "NO DEPENDS ON EXTENSION {extension_name}")
5610 } else {
5611 write!(f, "DEPENDS ON EXTENSION {extension_name}")
5612 }
5613 }
5614 AlterFunctionOperation::Actions { actions, restrict } => {
5615 write!(f, "{}", display_separated(actions, " "))?;
5616 if *restrict {
5617 write!(f, " RESTRICT")?;
5618 }
5619 Ok(())
5620 }
5621 }
5622 }
5623}
5624
5625impl fmt::Display for AlterFunctionAction {
5626 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5627 match self {
5628 AlterFunctionAction::CalledOnNull(called_on_null) => write!(f, "{called_on_null}"),
5629 AlterFunctionAction::Behavior(behavior) => write!(f, "{behavior}"),
5630 AlterFunctionAction::Leakproof(leakproof) => {
5631 if *leakproof {
5632 write!(f, "LEAKPROOF")
5633 } else {
5634 write!(f, "NOT LEAKPROOF")
5635 }
5636 }
5637 AlterFunctionAction::Security { external, security } => {
5638 if *external {
5639 write!(f, "EXTERNAL ")?;
5640 }
5641 write!(f, "{security}")
5642 }
5643 AlterFunctionAction::Parallel(parallel) => write!(f, "{parallel}"),
5644 AlterFunctionAction::Cost(execution_cost) => write!(f, "COST {execution_cost}"),
5645 AlterFunctionAction::Rows(result_rows) => write!(f, "ROWS {result_rows}"),
5646 AlterFunctionAction::Support(support_function) => {
5647 write!(f, "SUPPORT {support_function}")
5648 }
5649 AlterFunctionAction::Set(set_param) => write!(f, "{set_param}"),
5650 AlterFunctionAction::Reset(reset_config) => match reset_config {
5651 ResetConfig::ALL => write!(f, "RESET ALL"),
5652 ResetConfig::ConfigName(name) => write!(f, "RESET {name}"),
5653 },
5654 }
5655 }
5656}
5657
5658impl Spanned for AlterFunction {
5659 fn span(&self) -> Span {
5660 Span::empty()
5661 }
5662}
5663
5664#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5668#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5669#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5670pub enum TextSearchObjectType {
5671 Dictionary,
5673 Configuration,
5675 Template,
5677 Parser,
5679}
5680
5681impl fmt::Display for TextSearchObjectType {
5682 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5683 match self {
5684 TextSearchObjectType::Dictionary => write!(f, "DICTIONARY"),
5685 TextSearchObjectType::Configuration => write!(f, "CONFIGURATION"),
5686 TextSearchObjectType::Template => write!(f, "TEMPLATE"),
5687 TextSearchObjectType::Parser => write!(f, "PARSER"),
5688 }
5689 }
5690}
5691
5692#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5696#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5697#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5698pub struct CreateTextSearch {
5699 pub object_type: TextSearchObjectType,
5701 pub name: ObjectName,
5703 pub options: Vec<SqlOption>,
5705}
5706
5707impl fmt::Display for CreateTextSearch {
5708 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5709 write!(
5710 f,
5711 "CREATE TEXT SEARCH {} {} ({})",
5712 self.object_type,
5713 self.name,
5714 display_comma_separated(&self.options)
5715 )
5716 }
5717}
5718
5719impl Spanned for CreateTextSearch {
5720 fn span(&self) -> Span {
5721 Span::empty()
5722 }
5723}
5724
5725#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5729#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5730#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5731pub struct AlterTextSearchOption {
5732 pub key: Ident,
5734 pub value: Option<Expr>,
5736}
5737
5738impl fmt::Display for AlterTextSearchOption {
5739 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5740 match &self.value {
5741 Some(value) => write!(f, "{} = {}", self.key, value),
5742 None => write!(f, "{}", self.key),
5743 }
5744 }
5745}
5746
5747#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5751#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5752#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5753pub enum AlterTextSearchOperation {
5754 RenameTo {
5756 new_name: Ident,
5758 },
5759 OwnerTo(Owner),
5761 SetSchema {
5763 schema_name: ObjectName,
5765 },
5766 SetOptions {
5768 options: Vec<AlterTextSearchOption>,
5770 },
5771}
5772
5773impl fmt::Display for AlterTextSearchOperation {
5774 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5775 match self {
5776 AlterTextSearchOperation::RenameTo { new_name } => write!(f, "RENAME TO {new_name}"),
5777 AlterTextSearchOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
5778 AlterTextSearchOperation::SetSchema { schema_name } => {
5779 write!(f, "SET SCHEMA {schema_name}")
5780 }
5781 AlterTextSearchOperation::SetOptions { options } => {
5782 write!(f, "({})", display_comma_separated(options))
5783 }
5784 }
5785 }
5786}
5787
5788#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5792#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5793#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5794pub struct AlterTextSearch {
5795 pub object_type: TextSearchObjectType,
5797 pub name: ObjectName,
5799 pub operation: AlterTextSearchOperation,
5801}
5802
5803impl fmt::Display for AlterTextSearch {
5804 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5805 write!(
5806 f,
5807 "ALTER TEXT SEARCH {} {} {}",
5808 self.object_type, self.name, self.operation
5809 )
5810 }
5811}
5812
5813impl Spanned for AlterTextSearch {
5814 fn span(&self) -> Span {
5815 Span::empty()
5816 }
5817}
5818
5819#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5823#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5824#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5825pub struct CreatePolicy {
5826 pub name: Ident,
5828 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5830 pub table_name: ObjectName,
5831 pub policy_type: Option<CreatePolicyType>,
5833 pub command: Option<CreatePolicyCommand>,
5835 pub to: Option<Vec<Owner>>,
5837 pub using: Option<Expr>,
5839 pub with_check: Option<Expr>,
5841}
5842
5843impl fmt::Display for CreatePolicy {
5844 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5845 write!(
5846 f,
5847 "CREATE POLICY {name} ON {table_name}",
5848 name = self.name,
5849 table_name = self.table_name,
5850 )?;
5851 if let Some(ref policy_type) = self.policy_type {
5852 write!(f, " AS {policy_type}")?;
5853 }
5854 if let Some(ref command) = self.command {
5855 write!(f, " FOR {command}")?;
5856 }
5857 if let Some(ref to) = self.to {
5858 write!(f, " TO {}", display_comma_separated(to))?;
5859 }
5860 if let Some(ref using) = self.using {
5861 write!(f, " USING ({using})")?;
5862 }
5863 if let Some(ref with_check) = self.with_check {
5864 write!(f, " WITH CHECK ({with_check})")?;
5865 }
5866 Ok(())
5867 }
5868}
5869
5870#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5876#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5877#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5878pub enum CreatePolicyType {
5879 Permissive,
5881 Restrictive,
5883}
5884
5885impl fmt::Display for CreatePolicyType {
5886 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5887 match self {
5888 CreatePolicyType::Permissive => write!(f, "PERMISSIVE"),
5889 CreatePolicyType::Restrictive => write!(f, "RESTRICTIVE"),
5890 }
5891 }
5892}
5893
5894#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5900#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5901#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5902pub enum CreatePolicyCommand {
5903 All,
5905 Select,
5907 Insert,
5909 Update,
5911 Delete,
5913}
5914
5915impl fmt::Display for CreatePolicyCommand {
5916 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5917 match self {
5918 CreatePolicyCommand::All => write!(f, "ALL"),
5919 CreatePolicyCommand::Select => write!(f, "SELECT"),
5920 CreatePolicyCommand::Insert => write!(f, "INSERT"),
5921 CreatePolicyCommand::Update => write!(f, "UPDATE"),
5922 CreatePolicyCommand::Delete => write!(f, "DELETE"),
5923 }
5924 }
5925}
5926
5927#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5931#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5932#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5933pub struct DropPolicy {
5934 pub if_exists: bool,
5936 pub name: Ident,
5938 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5940 pub table_name: ObjectName,
5941 pub drop_behavior: Option<DropBehavior>,
5943}
5944
5945impl fmt::Display for DropPolicy {
5946 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5947 write!(
5948 f,
5949 "DROP POLICY {if_exists}{name} ON {table_name}",
5950 if_exists = if self.if_exists { "IF EXISTS " } else { "" },
5951 name = self.name,
5952 table_name = self.table_name
5953 )?;
5954 if let Some(ref behavior) = self.drop_behavior {
5955 write!(f, " {behavior}")?;
5956 }
5957 Ok(())
5958 }
5959}
5960
5961impl From<CreatePolicy> for crate::ast::Statement {
5962 fn from(v: CreatePolicy) -> Self {
5963 crate::ast::Statement::CreatePolicy(v)
5964 }
5965}
5966
5967impl From<DropPolicy> for crate::ast::Statement {
5968 fn from(v: DropPolicy) -> Self {
5969 crate::ast::Statement::DropPolicy(v)
5970 }
5971}
5972
5973#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5980#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5981#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5982pub struct AlterPolicy {
5983 pub name: Ident,
5985 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5987 pub table_name: ObjectName,
5988 pub operation: AlterPolicyOperation,
5990}
5991
5992impl fmt::Display for AlterPolicy {
5993 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5994 write!(
5995 f,
5996 "ALTER POLICY {name} ON {table_name}{operation}",
5997 name = self.name,
5998 table_name = self.table_name,
5999 operation = self.operation
6000 )
6001 }
6002}
6003
6004impl From<AlterPolicy> for crate::ast::Statement {
6005 fn from(v: AlterPolicy) -> Self {
6006 crate::ast::Statement::AlterPolicy(v)
6007 }
6008}
6009
6010#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6014#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6015#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6016pub struct CreateForeignTable {
6017 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6019 pub name: ObjectName,
6020 pub if_not_exists: bool,
6022 pub columns: Vec<ColumnDef>,
6024 pub constraints: Vec<TableConstraint>,
6028 pub server_name: Ident,
6030 pub options: Option<Vec<CreateServerOption>>,
6032}
6033
6034impl fmt::Display for CreateForeignTable {
6035 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6036 write!(
6037 f,
6038 "CREATE FOREIGN TABLE {if_not_exists}{name} ({columns}",
6039 if_not_exists = if self.if_not_exists {
6040 "IF NOT EXISTS "
6041 } else {
6042 ""
6043 },
6044 name = self.name,
6045 columns = display_comma_separated(&self.columns),
6046 )?;
6047 if !self.columns.is_empty() && !self.constraints.is_empty() {
6048 write!(f, ", ")?;
6049 }
6050 write!(f, "{}", display_comma_separated(&self.constraints))?;
6051 write!(f, ") SERVER {}", self.server_name)?;
6052 if let Some(options) = &self.options {
6053 write!(f, " OPTIONS ({})", display_comma_separated(options))?;
6054 }
6055 Ok(())
6056 }
6057}
6058
6059impl From<CreateForeignTable> for crate::ast::Statement {
6060 fn from(v: CreateForeignTable) -> Self {
6061 crate::ast::Statement::CreateForeignTable(v)
6062 }
6063}
6064
6065impl Spanned for CreateForeignTable {
6066 fn span(&self) -> Span {
6067 Span::union_iter(
6068 core::iter::once(self.name.span())
6069 .chain(self.columns.iter().map(|column| column.span()))
6070 .chain(self.constraints.iter().map(|constraint| constraint.span()))
6071 .chain(core::iter::once(self.server_name.span))
6072 .chain(
6073 self.options
6074 .iter()
6075 .flatten()
6076 .flat_map(|option| [option.key.span, option.value.span]),
6077 ),
6078 )
6079 }
6080}