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, CreateTableLikeKind, CreateTableOptions, CreateViewParams, DataType, Expr,
46 FileFormat, FunctionBehavior, FunctionCalledOnNull, FunctionDefinitionSetParam, FunctionDesc,
47 FunctionDeterminismSpecifier, FunctionParallel, FunctionSecurity, HiveDistributionStyle,
48 HiveFormat, HiveIOFormat, HiveRowFormat, HiveSetLocation, Ident, InitializeKind,
49 MySQLColumnPosition, ObjectName, OnCommit, OneOrManyWithParens, OperateFunctionArg,
50 OrderByExpr, ProjectionSelect, Query, RefreshModeKind, ResetConfig, RowAccessPolicy,
51 SequenceOptions, Spanned, SqlOption, StorageLifecyclePolicy, StorageSerializationPolicy,
52 TableVersion, Tag, TriggerEvent, TriggerExecBody, TriggerObject, TriggerPeriod,
53 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 RenameConstraint {
420 old_name: Ident,
422 new_name: Ident,
424 },
425 AlterColumn {
428 column_name: Ident,
430 op: AlterColumnOperation,
432 },
433 SwapWith {
437 table_name: ObjectName,
439 },
440 SetTblProperties {
442 table_properties: Vec<SqlOption>,
444 },
445 OwnerTo {
449 new_owner: Owner,
451 },
452 ClusterBy {
455 exprs: Vec<Expr>,
457 },
458 DropClusteringKey,
460 AlterSortKey {
463 columns: Vec<Expr>,
465 },
466 SuspendRecluster,
468 ResumeRecluster,
470 Refresh {
476 subpath: Option<String>,
478 },
479 Suspend,
483 Resume,
487 Algorithm {
493 equals: bool,
495 algorithm: AlterTableAlgorithm,
497 },
498
499 Lock {
505 equals: bool,
507 lock: AlterTableLock,
509 },
510 AutoIncrement {
516 equals: bool,
518 value: ValueWithSpan,
520 },
521 ValidateConstraint {
523 name: Ident,
525 },
526 SetOptionsParens {
534 options: Vec<SqlOption>,
536 },
537}
538
539#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
543#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
544#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
545pub enum AlterPolicyOperation {
546 Rename {
548 new_name: Ident,
550 },
551 Apply {
553 to: Option<Vec<Owner>>,
555 using: Option<Expr>,
557 with_check: Option<Expr>,
559 },
560}
561
562impl fmt::Display for AlterPolicyOperation {
563 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
564 match self {
565 AlterPolicyOperation::Rename { new_name } => {
566 write!(f, " RENAME TO {new_name}")
567 }
568 AlterPolicyOperation::Apply {
569 to,
570 using,
571 with_check,
572 } => {
573 if let Some(to) = to {
574 write!(f, " TO {}", display_comma_separated(to))?;
575 }
576 if let Some(using) = using {
577 write!(f, " USING ({using})")?;
578 }
579 if let Some(with_check) = with_check {
580 write!(f, " WITH CHECK ({with_check})")?;
581 }
582 Ok(())
583 }
584 }
585 }
586}
587
588#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
592#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
593#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
594pub enum AlterTableAlgorithm {
596 Default,
598 Instant,
600 Inplace,
602 Copy,
604}
605
606impl fmt::Display for AlterTableAlgorithm {
607 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
608 f.write_str(match self {
609 Self::Default => "DEFAULT",
610 Self::Instant => "INSTANT",
611 Self::Inplace => "INPLACE",
612 Self::Copy => "COPY",
613 })
614 }
615}
616
617#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
621#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
622#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
623pub enum AlterTableLock {
625 Default,
627 None,
629 Shared,
631 Exclusive,
633}
634
635impl fmt::Display for AlterTableLock {
636 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
637 f.write_str(match self {
638 Self::Default => "DEFAULT",
639 Self::None => "NONE",
640 Self::Shared => "SHARED",
641 Self::Exclusive => "EXCLUSIVE",
642 })
643 }
644}
645
646#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
647#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
648#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
649pub enum Owner {
651 Ident(Ident),
653 CurrentRole,
655 CurrentUser,
657 SessionUser,
659}
660
661impl fmt::Display for Owner {
662 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
663 match self {
664 Owner::Ident(ident) => write!(f, "{ident}"),
665 Owner::CurrentRole => write!(f, "CURRENT_ROLE"),
666 Owner::CurrentUser => write!(f, "CURRENT_USER"),
667 Owner::SessionUser => write!(f, "SESSION_USER"),
668 }
669 }
670}
671
672#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
673#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
674#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
675pub enum AlterConnectorOwner {
677 User(Ident),
679 Role(Ident),
681}
682
683impl fmt::Display for AlterConnectorOwner {
684 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
685 match self {
686 AlterConnectorOwner::User(ident) => write!(f, "USER {ident}"),
687 AlterConnectorOwner::Role(ident) => write!(f, "ROLE {ident}"),
688 }
689 }
690}
691
692#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
693#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
694#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
695pub enum AlterIndexOperation {
697 RenameIndex {
699 index_name: ObjectName,
701 },
702}
703
704impl fmt::Display for AlterTableOperation {
705 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
706 match self {
707 AlterTableOperation::AddPartitions {
708 if_not_exists,
709 new_partitions,
710 } => write!(
711 f,
712 "ADD{ine} {}",
713 display_separated(new_partitions, " "),
714 ine = if *if_not_exists { " IF NOT EXISTS" } else { "" }
715 ),
716 AlterTableOperation::AddConstraint {
717 not_valid,
718 constraint,
719 } => {
720 write!(f, "ADD {constraint}")?;
721 if *not_valid {
722 write!(f, " NOT VALID")?;
723 }
724 Ok(())
725 }
726 AlterTableOperation::AddColumn {
727 column_keyword,
728 if_not_exists,
729 column_def,
730 column_position,
731 } => {
732 write!(f, "ADD")?;
733 if *column_keyword {
734 write!(f, " COLUMN")?;
735 }
736 if *if_not_exists {
737 write!(f, " IF NOT EXISTS")?;
738 }
739 write!(f, " {column_def}")?;
740
741 if let Some(position) = column_position {
742 write!(f, " {position}")?;
743 }
744
745 Ok(())
746 }
747 AlterTableOperation::AddProjection {
748 if_not_exists,
749 name,
750 select: query,
751 } => {
752 write!(f, "ADD PROJECTION")?;
753 if *if_not_exists {
754 write!(f, " IF NOT EXISTS")?;
755 }
756 write!(f, " {name} ({query})")
757 }
758 AlterTableOperation::Algorithm { equals, algorithm } => {
759 write!(
760 f,
761 "ALGORITHM {}{}",
762 if *equals { "= " } else { "" },
763 algorithm
764 )
765 }
766 AlterTableOperation::DropProjection { if_exists, name } => {
767 write!(f, "DROP PROJECTION")?;
768 if *if_exists {
769 write!(f, " IF EXISTS")?;
770 }
771 write!(f, " {name}")
772 }
773 AlterTableOperation::MaterializeProjection {
774 if_exists,
775 name,
776 partition,
777 } => {
778 write!(f, "MATERIALIZE PROJECTION")?;
779 if *if_exists {
780 write!(f, " IF EXISTS")?;
781 }
782 write!(f, " {name}")?;
783 if let Some(partition) = partition {
784 write!(f, " IN PARTITION {partition}")?;
785 }
786 Ok(())
787 }
788 AlterTableOperation::ClearProjection {
789 if_exists,
790 name,
791 partition,
792 } => {
793 write!(f, "CLEAR PROJECTION")?;
794 if *if_exists {
795 write!(f, " IF EXISTS")?;
796 }
797 write!(f, " {name}")?;
798 if let Some(partition) = partition {
799 write!(f, " IN PARTITION {partition}")?;
800 }
801 Ok(())
802 }
803 AlterTableOperation::AlterColumn { column_name, op } => {
804 write!(f, "ALTER COLUMN {column_name} {op}")
805 }
806 AlterTableOperation::DisableRowLevelSecurity => {
807 write!(f, "DISABLE ROW LEVEL SECURITY")
808 }
809 AlterTableOperation::DisableRule { name } => {
810 write!(f, "DISABLE RULE {name}")
811 }
812 AlterTableOperation::DisableTrigger { name } => {
813 write!(f, "DISABLE TRIGGER {name}")
814 }
815 AlterTableOperation::DropPartitions {
816 partitions,
817 if_exists,
818 } => write!(
819 f,
820 "DROP{ie} PARTITION ({})",
821 display_comma_separated(partitions),
822 ie = if *if_exists { " IF EXISTS" } else { "" }
823 ),
824 AlterTableOperation::DropConstraint {
825 if_exists,
826 name,
827 drop_behavior,
828 } => {
829 write!(
830 f,
831 "DROP CONSTRAINT {}{}",
832 if *if_exists { "IF EXISTS " } else { "" },
833 name
834 )?;
835 if let Some(drop_behavior) = drop_behavior {
836 write!(f, " {drop_behavior}")?;
837 }
838 Ok(())
839 }
840 AlterTableOperation::DropPrimaryKey { drop_behavior } => {
841 write!(f, "DROP PRIMARY KEY")?;
842 if let Some(drop_behavior) = drop_behavior {
843 write!(f, " {drop_behavior}")?;
844 }
845 Ok(())
846 }
847 AlterTableOperation::DropForeignKey {
848 name,
849 drop_behavior,
850 } => {
851 write!(f, "DROP FOREIGN KEY {name}")?;
852 if let Some(drop_behavior) = drop_behavior {
853 write!(f, " {drop_behavior}")?;
854 }
855 Ok(())
856 }
857 AlterTableOperation::DropIndex { name } => write!(f, "DROP INDEX {name}"),
858 AlterTableOperation::DropColumn {
859 has_column_keyword,
860 column_names: column_name,
861 if_exists,
862 drop_behavior,
863 } => {
864 write!(
865 f,
866 "DROP {}{}{}",
867 if *has_column_keyword { "COLUMN " } else { "" },
868 if *if_exists { "IF EXISTS " } else { "" },
869 display_comma_separated(column_name),
870 )?;
871 if let Some(drop_behavior) = drop_behavior {
872 write!(f, " {drop_behavior}")?;
873 }
874 Ok(())
875 }
876 AlterTableOperation::AttachPartition { partition } => {
877 write!(f, "ATTACH {partition}")
878 }
879 AlterTableOperation::DetachPartition { partition } => {
880 write!(f, "DETACH {partition}")
881 }
882 AlterTableOperation::EnableAlwaysRule { name } => {
883 write!(f, "ENABLE ALWAYS RULE {name}")
884 }
885 AlterTableOperation::EnableAlwaysTrigger { name } => {
886 write!(f, "ENABLE ALWAYS TRIGGER {name}")
887 }
888 AlterTableOperation::EnableReplicaRule { name } => {
889 write!(f, "ENABLE REPLICA RULE {name}")
890 }
891 AlterTableOperation::EnableReplicaTrigger { name } => {
892 write!(f, "ENABLE REPLICA TRIGGER {name}")
893 }
894 AlterTableOperation::EnableRowLevelSecurity => {
895 write!(f, "ENABLE ROW LEVEL SECURITY")
896 }
897 AlterTableOperation::ForceRowLevelSecurity => {
898 write!(f, "FORCE ROW LEVEL SECURITY")
899 }
900 AlterTableOperation::NoForceRowLevelSecurity => {
901 write!(f, "NO FORCE ROW LEVEL SECURITY")
902 }
903 AlterTableOperation::EnableRule { name } => {
904 write!(f, "ENABLE RULE {name}")
905 }
906 AlterTableOperation::EnableTrigger { name } => {
907 write!(f, "ENABLE TRIGGER {name}")
908 }
909 AlterTableOperation::RenamePartitions {
910 old_partitions,
911 new_partitions,
912 } => write!(
913 f,
914 "PARTITION ({}) RENAME TO PARTITION ({})",
915 display_comma_separated(old_partitions),
916 display_comma_separated(new_partitions)
917 ),
918 AlterTableOperation::RenameColumn {
919 old_column_name,
920 new_column_name,
921 } => write!(f, "RENAME COLUMN {old_column_name} TO {new_column_name}"),
922 AlterTableOperation::RenameTable { table_name } => {
923 write!(f, "RENAME {table_name}")
924 }
925 AlterTableOperation::ChangeColumn {
926 old_name,
927 new_name,
928 data_type,
929 options,
930 column_position,
931 } => {
932 write!(f, "CHANGE COLUMN {old_name} {new_name} {data_type}")?;
933 if !options.is_empty() {
934 write!(f, " {}", display_separated(options, " "))?;
935 }
936 if let Some(position) = column_position {
937 write!(f, " {position}")?;
938 }
939
940 Ok(())
941 }
942 AlterTableOperation::ModifyColumn {
943 col_name,
944 data_type,
945 options,
946 column_position,
947 } => {
948 write!(f, "MODIFY COLUMN {col_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::RenameConstraint { old_name, new_name } => {
959 write!(f, "RENAME CONSTRAINT {old_name} TO {new_name}")
960 }
961 AlterTableOperation::SwapWith { table_name } => {
962 write!(f, "SWAP WITH {table_name}")
963 }
964 AlterTableOperation::OwnerTo { new_owner } => {
965 write!(f, "OWNER TO {new_owner}")
966 }
967 AlterTableOperation::SetTblProperties { table_properties } => {
968 write!(
969 f,
970 "SET TBLPROPERTIES({})",
971 display_comma_separated(table_properties)
972 )
973 }
974 AlterTableOperation::FreezePartition {
975 partition,
976 with_name,
977 } => {
978 write!(f, "FREEZE {partition}")?;
979 if let Some(name) = with_name {
980 write!(f, " WITH NAME {name}")?;
981 }
982 Ok(())
983 }
984 AlterTableOperation::UnfreezePartition {
985 partition,
986 with_name,
987 } => {
988 write!(f, "UNFREEZE {partition}")?;
989 if let Some(name) = with_name {
990 write!(f, " WITH NAME {name}")?;
991 }
992 Ok(())
993 }
994 AlterTableOperation::ClusterBy { exprs } => {
995 write!(f, "CLUSTER BY ({})", display_comma_separated(exprs))?;
996 Ok(())
997 }
998 AlterTableOperation::DropClusteringKey => {
999 write!(f, "DROP CLUSTERING KEY")?;
1000 Ok(())
1001 }
1002 AlterTableOperation::AlterSortKey { columns } => {
1003 write!(f, "ALTER SORTKEY({})", display_comma_separated(columns))?;
1004 Ok(())
1005 }
1006 AlterTableOperation::SuspendRecluster => {
1007 write!(f, "SUSPEND RECLUSTER")?;
1008 Ok(())
1009 }
1010 AlterTableOperation::ResumeRecluster => {
1011 write!(f, "RESUME RECLUSTER")?;
1012 Ok(())
1013 }
1014 AlterTableOperation::Refresh { subpath } => {
1015 write!(f, "REFRESH")?;
1016 if let Some(path) = subpath {
1017 write!(f, " '{path}'")?;
1018 }
1019 Ok(())
1020 }
1021 AlterTableOperation::Suspend => {
1022 write!(f, "SUSPEND")
1023 }
1024 AlterTableOperation::Resume => {
1025 write!(f, "RESUME")
1026 }
1027 AlterTableOperation::AutoIncrement { equals, value } => {
1028 write!(
1029 f,
1030 "AUTO_INCREMENT {}{}",
1031 if *equals { "= " } else { "" },
1032 value
1033 )
1034 }
1035 AlterTableOperation::Lock { equals, lock } => {
1036 write!(f, "LOCK {}{}", if *equals { "= " } else { "" }, lock)
1037 }
1038 AlterTableOperation::ReplicaIdentity { identity } => {
1039 write!(f, "REPLICA IDENTITY {identity}")
1040 }
1041 AlterTableOperation::ValidateConstraint { name } => {
1042 write!(f, "VALIDATE CONSTRAINT {name}")
1043 }
1044 AlterTableOperation::SetOptionsParens { options } => {
1045 write!(f, "SET ({})", display_comma_separated(options))
1046 }
1047 }
1048 }
1049}
1050
1051impl fmt::Display for AlterIndexOperation {
1052 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1053 match self {
1054 AlterIndexOperation::RenameIndex { index_name } => {
1055 write!(f, "RENAME TO {index_name}")
1056 }
1057 }
1058 }
1059}
1060
1061#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1063#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1064#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1065pub struct AlterType {
1066 pub name: ObjectName,
1068 pub operation: AlterTypeOperation,
1070}
1071
1072#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1074#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1075#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1076pub enum AlterTypeOperation {
1077 Rename(AlterTypeRename),
1079 AddValue(AlterTypeAddValue),
1081 RenameValue(AlterTypeRenameValue),
1083}
1084
1085#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1087#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1088#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1089pub struct AlterTypeRename {
1090 pub new_name: Ident,
1092}
1093
1094#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1096#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1097#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1098pub struct AlterTypeAddValue {
1099 pub if_not_exists: bool,
1101 pub value: Ident,
1103 pub position: Option<AlterTypeAddValuePosition>,
1105}
1106
1107#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1109#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1110#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1111pub enum AlterTypeAddValuePosition {
1112 Before(Ident),
1114 After(Ident),
1116}
1117
1118#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1120#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1121#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1122pub struct AlterTypeRenameValue {
1123 pub from: Ident,
1125 pub to: Ident,
1127}
1128
1129impl fmt::Display for AlterTypeOperation {
1130 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1131 match self {
1132 Self::Rename(AlterTypeRename { new_name }) => {
1133 write!(f, "RENAME TO {new_name}")
1134 }
1135 Self::AddValue(AlterTypeAddValue {
1136 if_not_exists,
1137 value,
1138 position,
1139 }) => {
1140 write!(f, "ADD VALUE")?;
1141 if *if_not_exists {
1142 write!(f, " IF NOT EXISTS")?;
1143 }
1144 write!(f, " {value}")?;
1145 match position {
1146 Some(AlterTypeAddValuePosition::Before(neighbor_value)) => {
1147 write!(f, " BEFORE {neighbor_value}")?;
1148 }
1149 Some(AlterTypeAddValuePosition::After(neighbor_value)) => {
1150 write!(f, " AFTER {neighbor_value}")?;
1151 }
1152 None => {}
1153 };
1154 Ok(())
1155 }
1156 Self::RenameValue(AlterTypeRenameValue { from, to }) => {
1157 write!(f, "RENAME VALUE {from} TO {to}")
1158 }
1159 }
1160 }
1161}
1162
1163#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1166#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1167#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1168pub struct AlterOperator {
1169 pub name: ObjectName,
1171 pub left_type: Option<DataType>,
1173 pub right_type: DataType,
1175 pub operation: AlterOperatorOperation,
1177}
1178
1179#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1181#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1182#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1183pub enum AlterOperatorOperation {
1184 OwnerTo(Owner),
1186 SetSchema {
1189 schema_name: ObjectName,
1191 },
1192 Set {
1194 options: Vec<OperatorOption>,
1196 },
1197}
1198
1199#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1201#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1202#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1203pub enum OperatorOption {
1204 Restrict(Option<ObjectName>),
1206 Join(Option<ObjectName>),
1208 Commutator(ObjectName),
1210 Negator(ObjectName),
1212 Hashes,
1214 Merges,
1216}
1217
1218impl fmt::Display for AlterOperator {
1219 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1220 write!(f, "ALTER OPERATOR {} (", self.name)?;
1221 if let Some(left_type) = &self.left_type {
1222 write!(f, "{}", left_type)?;
1223 } else {
1224 write!(f, "NONE")?;
1225 }
1226 write!(f, ", {}) {}", self.right_type, self.operation)
1227 }
1228}
1229
1230impl fmt::Display for AlterOperatorOperation {
1231 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1232 match self {
1233 Self::OwnerTo(owner) => write!(f, "OWNER TO {}", owner),
1234 Self::SetSchema { schema_name } => write!(f, "SET SCHEMA {}", schema_name),
1235 Self::Set { options } => {
1236 write!(f, "SET (")?;
1237 for (i, option) in options.iter().enumerate() {
1238 if i > 0 {
1239 write!(f, ", ")?;
1240 }
1241 write!(f, "{}", option)?;
1242 }
1243 write!(f, ")")
1244 }
1245 }
1246 }
1247}
1248
1249impl fmt::Display for OperatorOption {
1250 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1251 match self {
1252 Self::Restrict(Some(proc_name)) => write!(f, "RESTRICT = {}", proc_name),
1253 Self::Restrict(None) => write!(f, "RESTRICT = NONE"),
1254 Self::Join(Some(proc_name)) => write!(f, "JOIN = {}", proc_name),
1255 Self::Join(None) => write!(f, "JOIN = NONE"),
1256 Self::Commutator(op_name) => write!(f, "COMMUTATOR = {}", op_name),
1257 Self::Negator(op_name) => write!(f, "NEGATOR = {}", op_name),
1258 Self::Hashes => write!(f, "HASHES"),
1259 Self::Merges => write!(f, "MERGES"),
1260 }
1261 }
1262}
1263
1264#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1266#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1267#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1268pub enum AlterColumnOperation {
1269 SetNotNull,
1271 DropNotNull,
1273 SetDefault {
1276 value: Expr,
1278 },
1279 DropDefault,
1281 SetStorage {
1283 storage: AlterColumnStorage,
1285 },
1286 SetDataType {
1288 data_type: DataType,
1290 using: Option<Expr>,
1292 had_set: bool,
1294 },
1295
1296 AddGenerated {
1300 generated_as: Option<GeneratedAs>,
1302 sequence_options: Option<Vec<SequenceOptions>>,
1304 },
1305}
1306
1307impl fmt::Display for AlterColumnOperation {
1308 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1309 match self {
1310 AlterColumnOperation::SetNotNull => write!(f, "SET NOT NULL",),
1311 AlterColumnOperation::DropNotNull => write!(f, "DROP NOT NULL",),
1312 AlterColumnOperation::SetDefault { value } => {
1313 write!(f, "SET DEFAULT {value}")
1314 }
1315 AlterColumnOperation::DropDefault => {
1316 write!(f, "DROP DEFAULT")
1317 }
1318 AlterColumnOperation::SetStorage { storage } => {
1319 write!(f, "SET STORAGE {storage}")
1320 }
1321 AlterColumnOperation::SetDataType {
1322 data_type,
1323 using,
1324 had_set,
1325 } => {
1326 if *had_set {
1327 write!(f, "SET DATA ")?;
1328 }
1329 write!(f, "TYPE {data_type}")?;
1330 if let Some(expr) = using {
1331 write!(f, " USING {expr}")?;
1332 }
1333 Ok(())
1334 }
1335 AlterColumnOperation::AddGenerated {
1336 generated_as,
1337 sequence_options,
1338 } => {
1339 let generated_as = match generated_as {
1340 Some(GeneratedAs::Always) => " ALWAYS",
1341 Some(GeneratedAs::ByDefault) => " BY DEFAULT",
1342 _ => "",
1343 };
1344
1345 write!(f, "ADD GENERATED{generated_as} AS IDENTITY",)?;
1346 if let Some(options) = sequence_options {
1347 write!(f, " (")?;
1348
1349 for sequence_option in options {
1350 write!(f, "{sequence_option}")?;
1351 }
1352
1353 write!(f, " )")?;
1354 }
1355 Ok(())
1356 }
1357 }
1358 }
1359}
1360
1361#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1363#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1364#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1365pub enum AlterColumnStorage {
1366 Plain,
1368 External,
1370 Extended,
1372 Main,
1374 Default,
1376}
1377
1378impl fmt::Display for AlterColumnStorage {
1379 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1380 match self {
1381 AlterColumnStorage::Plain => write!(f, "PLAIN"),
1382 AlterColumnStorage::External => write!(f, "EXTERNAL"),
1383 AlterColumnStorage::Extended => write!(f, "EXTENDED"),
1384 AlterColumnStorage::Main => write!(f, "MAIN"),
1385 AlterColumnStorage::Default => write!(f, "DEFAULT"),
1386 }
1387 }
1388}
1389
1390#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1398#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1399#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1400pub enum KeyOrIndexDisplay {
1401 None,
1403 Key,
1405 Index,
1407}
1408
1409impl KeyOrIndexDisplay {
1410 pub fn is_none(self) -> bool {
1412 matches!(self, Self::None)
1413 }
1414}
1415
1416impl fmt::Display for KeyOrIndexDisplay {
1417 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1418 let left_space = matches!(f.align(), Some(fmt::Alignment::Right));
1419
1420 if left_space && !self.is_none() {
1421 f.write_char(' ')?
1422 }
1423
1424 match self {
1425 KeyOrIndexDisplay::None => {
1426 write!(f, "")
1427 }
1428 KeyOrIndexDisplay::Key => {
1429 write!(f, "KEY")
1430 }
1431 KeyOrIndexDisplay::Index => {
1432 write!(f, "INDEX")
1433 }
1434 }
1435 }
1436}
1437
1438#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1447#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1448#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1449pub enum IndexType {
1450 BTree,
1452 Hash,
1454 GIN,
1456 GiST,
1458 SPGiST,
1460 BRIN,
1462 Bloom,
1464 Custom(Ident),
1467}
1468
1469impl fmt::Display for IndexType {
1470 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1471 match self {
1472 Self::BTree => write!(f, "BTREE"),
1473 Self::Hash => write!(f, "HASH"),
1474 Self::GIN => write!(f, "GIN"),
1475 Self::GiST => write!(f, "GIST"),
1476 Self::SPGiST => write!(f, "SPGIST"),
1477 Self::BRIN => write!(f, "BRIN"),
1478 Self::Bloom => write!(f, "BLOOM"),
1479 Self::Custom(name) => write!(f, "{name}"),
1480 }
1481 }
1482}
1483
1484#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1490#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1491#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1492pub enum IndexOption {
1493 Using(IndexType),
1497 Comment(String),
1499}
1500
1501impl fmt::Display for IndexOption {
1502 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1503 match self {
1504 Self::Using(index_type) => write!(f, "USING {index_type}"),
1505 Self::Comment(s) => write!(f, "COMMENT '{s}'"),
1506 }
1507 }
1508}
1509
1510#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1514#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1515#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1516pub enum NullsDistinctOption {
1517 None,
1519 Distinct,
1521 NotDistinct,
1523}
1524
1525impl fmt::Display for NullsDistinctOption {
1526 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1527 match self {
1528 Self::None => Ok(()),
1529 Self::Distinct => write!(f, " NULLS DISTINCT"),
1530 Self::NotDistinct => write!(f, " NULLS NOT DISTINCT"),
1531 }
1532 }
1533}
1534
1535#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1536#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1537#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1538pub struct ProcedureParam {
1540 pub name: Ident,
1542 pub data_type: DataType,
1544 pub mode: Option<ArgMode>,
1546 pub default: Option<Expr>,
1548}
1549
1550impl fmt::Display for ProcedureParam {
1551 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1552 if let Some(mode) = &self.mode {
1553 if let Some(default) = &self.default {
1554 write!(f, "{mode} {} {} = {}", self.name, self.data_type, default)
1555 } else {
1556 write!(f, "{mode} {} {}", self.name, self.data_type)
1557 }
1558 } else if let Some(default) = &self.default {
1559 write!(f, "{} {} = {}", self.name, self.data_type, default)
1560 } else {
1561 write!(f, "{} {}", self.name, self.data_type)
1562 }
1563 }
1564}
1565
1566#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1568#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1569#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1570pub struct ColumnDef {
1571 pub name: Ident,
1573 pub data_type: DataType,
1575 pub options: Vec<ColumnOptionDef>,
1577}
1578
1579impl fmt::Display for ColumnDef {
1580 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1581 if self.data_type == DataType::Unspecified {
1582 write!(f, "{}", self.name)?;
1583 } else {
1584 write!(f, "{} {}", self.name, self.data_type)?;
1585 }
1586 for option in &self.options {
1587 write!(f, " {option}")?;
1588 }
1589 Ok(())
1590 }
1591}
1592
1593#[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 struct ViewColumnDef {
1613 pub name: Ident,
1615 pub data_type: Option<DataType>,
1617 pub options: Option<ColumnOptions>,
1619}
1620
1621#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1622#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1623#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1624pub enum ColumnOptions {
1626 CommaSeparated(Vec<ColumnOption>),
1628 SpaceSeparated(Vec<ColumnOption>),
1630}
1631
1632impl ColumnOptions {
1633 pub fn as_slice(&self) -> &[ColumnOption] {
1635 match self {
1636 ColumnOptions::CommaSeparated(options) => options.as_slice(),
1637 ColumnOptions::SpaceSeparated(options) => options.as_slice(),
1638 }
1639 }
1640}
1641
1642impl fmt::Display for ViewColumnDef {
1643 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1644 write!(f, "{}", self.name)?;
1645 if let Some(data_type) = self.data_type.as_ref() {
1646 write!(f, " {data_type}")?;
1647 }
1648 if let Some(options) = self.options.as_ref() {
1649 match options {
1650 ColumnOptions::CommaSeparated(column_options) => {
1651 write!(f, " {}", display_comma_separated(column_options.as_slice()))?;
1652 }
1653 ColumnOptions::SpaceSeparated(column_options) => {
1654 write!(f, " {}", display_separated(column_options.as_slice(), " "))?
1655 }
1656 }
1657 }
1658 Ok(())
1659 }
1660}
1661
1662#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1679#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1680#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1681pub struct ColumnOptionDef {
1682 pub name: Option<Ident>,
1684 pub option: ColumnOption,
1686}
1687
1688impl fmt::Display for ColumnOptionDef {
1689 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1690 write!(f, "{}{}", display_constraint_name(&self.name), self.option)
1691 }
1692}
1693
1694#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1702#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1703#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1704pub enum IdentityPropertyKind {
1705 Autoincrement(IdentityProperty),
1713 Identity(IdentityProperty),
1726}
1727
1728impl fmt::Display for IdentityPropertyKind {
1729 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1730 let (command, property) = match self {
1731 IdentityPropertyKind::Identity(property) => ("IDENTITY", property),
1732 IdentityPropertyKind::Autoincrement(property) => ("AUTOINCREMENT", property),
1733 };
1734 write!(f, "{command}")?;
1735 if let Some(parameters) = &property.parameters {
1736 write!(f, "{parameters}")?;
1737 }
1738 if let Some(order) = &property.order {
1739 write!(f, "{order}")?;
1740 }
1741 Ok(())
1742 }
1743}
1744
1745#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1747#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1748#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1749pub struct IdentityProperty {
1750 pub parameters: Option<IdentityPropertyFormatKind>,
1752 pub order: Option<IdentityPropertyOrder>,
1754}
1755
1756#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1771#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1772#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1773pub enum IdentityPropertyFormatKind {
1774 FunctionCall(IdentityParameters),
1782 StartAndIncrement(IdentityParameters),
1789}
1790
1791impl fmt::Display for IdentityPropertyFormatKind {
1792 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1793 match self {
1794 IdentityPropertyFormatKind::FunctionCall(parameters) => {
1795 write!(f, "({}, {})", parameters.seed, parameters.increment)
1796 }
1797 IdentityPropertyFormatKind::StartAndIncrement(parameters) => {
1798 write!(
1799 f,
1800 " START {} INCREMENT {}",
1801 parameters.seed, parameters.increment
1802 )
1803 }
1804 }
1805 }
1806}
1807#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1809#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1810#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1811pub struct IdentityParameters {
1812 pub seed: Expr,
1814 pub increment: Expr,
1816}
1817
1818#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1825#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1826#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1827pub enum IdentityPropertyOrder {
1828 Order,
1830 NoOrder,
1832}
1833
1834impl fmt::Display for IdentityPropertyOrder {
1835 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1836 match self {
1837 IdentityPropertyOrder::Order => write!(f, " ORDER"),
1838 IdentityPropertyOrder::NoOrder => write!(f, " NOORDER"),
1839 }
1840 }
1841}
1842
1843#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1851#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1852#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1853pub enum ColumnPolicy {
1854 MaskingPolicy(ColumnPolicyProperty),
1856 ProjectionPolicy(ColumnPolicyProperty),
1858}
1859
1860impl fmt::Display for ColumnPolicy {
1861 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1862 let (command, property) = match self {
1863 ColumnPolicy::MaskingPolicy(property) => ("MASKING POLICY", property),
1864 ColumnPolicy::ProjectionPolicy(property) => ("PROJECTION POLICY", property),
1865 };
1866 if property.with {
1867 write!(f, "WITH ")?;
1868 }
1869 write!(f, "{command} {}", property.policy_name)?;
1870 if let Some(using_columns) = &property.using_columns {
1871 write!(f, " USING ({})", display_comma_separated(using_columns))?;
1872 }
1873 Ok(())
1874 }
1875}
1876
1877#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1878#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1879#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1880pub struct ColumnPolicyProperty {
1882 pub with: bool,
1889 pub policy_name: ObjectName,
1891 pub using_columns: Option<Vec<Ident>>,
1893}
1894
1895#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1902#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1903#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1904pub struct TagsColumnOption {
1905 pub with: bool,
1912 pub tags: Vec<Tag>,
1914}
1915
1916impl fmt::Display for TagsColumnOption {
1917 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1918 if self.with {
1919 write!(f, "WITH ")?;
1920 }
1921 write!(f, "TAG ({})", display_comma_separated(&self.tags))?;
1922 Ok(())
1923 }
1924}
1925
1926#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1929#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1930#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1931pub enum ColumnOption {
1932 Null,
1934 NotNull,
1936 Default(Expr),
1938
1939 Materialized(Expr),
1944 Ephemeral(Option<Expr>),
1948 Alias(Expr),
1952
1953 PrimaryKey(PrimaryKeyConstraint),
1955 Unique(UniqueConstraint),
1957 ForeignKey(ForeignKeyConstraint),
1965 Check(CheckConstraint),
1967 DialectSpecific(Vec<Token>),
1971 CharacterSet(ObjectName),
1973 Collation(ObjectName),
1975 Comment(String),
1977 OnUpdate(Expr),
1979 Generated {
1982 generated_as: GeneratedAs,
1984 sequence_options: Option<Vec<SequenceOptions>>,
1986 generation_expr: Option<Expr>,
1988 generation_expr_mode: Option<GeneratedExpressionMode>,
1990 generated_keyword: bool,
1992 },
1993 Options(Vec<SqlOption>),
2001 Identity(IdentityPropertyKind),
2009 OnConflict(Keyword),
2012 Policy(ColumnPolicy),
2020 Tags(TagsColumnOption),
2027 Srid(Box<Expr>),
2034 Invisible,
2041}
2042
2043impl From<UniqueConstraint> for ColumnOption {
2044 fn from(c: UniqueConstraint) -> Self {
2045 ColumnOption::Unique(c)
2046 }
2047}
2048
2049impl From<PrimaryKeyConstraint> for ColumnOption {
2050 fn from(c: PrimaryKeyConstraint) -> Self {
2051 ColumnOption::PrimaryKey(c)
2052 }
2053}
2054
2055impl From<CheckConstraint> for ColumnOption {
2056 fn from(c: CheckConstraint) -> Self {
2057 ColumnOption::Check(c)
2058 }
2059}
2060impl From<ForeignKeyConstraint> for ColumnOption {
2061 fn from(fk: ForeignKeyConstraint) -> Self {
2062 ColumnOption::ForeignKey(fk)
2063 }
2064}
2065
2066impl fmt::Display for ColumnOption {
2067 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2068 use ColumnOption::*;
2069 match self {
2070 Null => write!(f, "NULL"),
2071 NotNull => write!(f, "NOT NULL"),
2072 Default(expr) => write!(f, "DEFAULT {expr}"),
2073 Materialized(expr) => write!(f, "MATERIALIZED {expr}"),
2074 Ephemeral(expr) => {
2075 if let Some(e) = expr {
2076 write!(f, "EPHEMERAL {e}")
2077 } else {
2078 write!(f, "EPHEMERAL")
2079 }
2080 }
2081 Alias(expr) => write!(f, "ALIAS {expr}"),
2082 PrimaryKey(constraint) => {
2083 write!(f, "PRIMARY KEY")?;
2084 if let Some(characteristics) = &constraint.characteristics {
2085 write!(f, " {characteristics}")?;
2086 }
2087 Ok(())
2088 }
2089 Unique(constraint) => {
2090 write!(f, "UNIQUE{:>}", constraint.index_type_display)?;
2091 if let Some(characteristics) = &constraint.characteristics {
2092 write!(f, " {characteristics}")?;
2093 }
2094 Ok(())
2095 }
2096 ForeignKey(constraint) => {
2097 write!(f, "REFERENCES {}", constraint.foreign_table)?;
2098 if !constraint.referred_columns.is_empty() {
2099 write!(
2100 f,
2101 " ({})",
2102 display_comma_separated(&constraint.referred_columns)
2103 )?;
2104 }
2105 if let Some(match_kind) = &constraint.match_kind {
2106 write!(f, " {match_kind}")?;
2107 }
2108 if let Some(action) = &constraint.on_delete {
2109 write!(f, " ON DELETE {action}")?;
2110 }
2111 if let Some(action) = &constraint.on_update {
2112 write!(f, " ON UPDATE {action}")?;
2113 }
2114 if let Some(characteristics) = &constraint.characteristics {
2115 write!(f, " {characteristics}")?;
2116 }
2117 Ok(())
2118 }
2119 Check(constraint) => write!(f, "{constraint}"),
2120 DialectSpecific(val) => write!(f, "{}", display_separated(val, " ")),
2121 CharacterSet(n) => write!(f, "CHARACTER SET {n}"),
2122 Collation(n) => write!(f, "COLLATE {n}"),
2123 Comment(v) => write!(f, "COMMENT '{}'", escape_single_quote_string(v)),
2124 OnUpdate(expr) => write!(f, "ON UPDATE {expr}"),
2125 Generated {
2126 generated_as,
2127 sequence_options,
2128 generation_expr,
2129 generation_expr_mode,
2130 generated_keyword,
2131 } => {
2132 if let Some(expr) = generation_expr {
2133 let modifier = match generation_expr_mode {
2134 None => "",
2135 Some(GeneratedExpressionMode::Virtual) => " VIRTUAL",
2136 Some(GeneratedExpressionMode::Stored) => " STORED",
2137 };
2138 if *generated_keyword {
2139 write!(f, "GENERATED ALWAYS AS ({expr}){modifier}")?;
2140 } else {
2141 write!(f, "AS ({expr}){modifier}")?;
2142 }
2143 Ok(())
2144 } else {
2145 let when = match generated_as {
2147 GeneratedAs::Always => "ALWAYS",
2148 GeneratedAs::ByDefault => "BY DEFAULT",
2149 GeneratedAs::ExpStored => "",
2151 };
2152 write!(f, "GENERATED {when} AS IDENTITY")?;
2153 if let Some(so) = sequence_options {
2154 if !so.is_empty() {
2155 write!(f, " (")?;
2156 }
2157 for sequence_option in so {
2158 write!(f, "{sequence_option}")?;
2159 }
2160 if !so.is_empty() {
2161 write!(f, " )")?;
2162 }
2163 }
2164 Ok(())
2165 }
2166 }
2167 Options(options) => {
2168 write!(f, "OPTIONS({})", display_comma_separated(options))
2169 }
2170 Identity(parameters) => {
2171 write!(f, "{parameters}")
2172 }
2173 OnConflict(keyword) => {
2174 write!(f, "ON CONFLICT {keyword:?}")?;
2175 Ok(())
2176 }
2177 Policy(parameters) => {
2178 write!(f, "{parameters}")
2179 }
2180 Tags(tags) => {
2181 write!(f, "{tags}")
2182 }
2183 Srid(srid) => {
2184 write!(f, "SRID {srid}")
2185 }
2186 Invisible => {
2187 write!(f, "INVISIBLE")
2188 }
2189 }
2190 }
2191}
2192
2193#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2196#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2197#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2198pub enum GeneratedAs {
2199 Always,
2201 ByDefault,
2203 ExpStored,
2205}
2206
2207#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2210#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2211#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2212pub enum GeneratedExpressionMode {
2213 Virtual,
2215 Stored,
2217}
2218
2219#[must_use]
2220pub(crate) fn display_constraint_name(name: &'_ Option<Ident>) -> impl fmt::Display + '_ {
2221 struct ConstraintName<'a>(&'a Option<Ident>);
2222 impl fmt::Display for ConstraintName<'_> {
2223 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2224 if let Some(name) = self.0 {
2225 write!(f, "CONSTRAINT {name} ")?;
2226 }
2227 Ok(())
2228 }
2229 }
2230 ConstraintName(name)
2231}
2232
2233#[must_use]
2237pub(crate) fn display_option<'a, T: fmt::Display>(
2238 prefix: &'a str,
2239 postfix: &'a str,
2240 option: &'a Option<T>,
2241) -> impl fmt::Display + 'a {
2242 struct OptionDisplay<'a, T>(&'a str, &'a str, &'a Option<T>);
2243 impl<T: fmt::Display> fmt::Display for OptionDisplay<'_, T> {
2244 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2245 if let Some(inner) = self.2 {
2246 let (prefix, postfix) = (self.0, self.1);
2247 write!(f, "{prefix}{inner}{postfix}")?;
2248 }
2249 Ok(())
2250 }
2251 }
2252 OptionDisplay(prefix, postfix, option)
2253}
2254
2255#[must_use]
2259pub(crate) fn display_option_spaced<T: fmt::Display>(option: &Option<T>) -> impl fmt::Display + '_ {
2260 display_option(" ", "", option)
2261}
2262
2263#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Default, Eq, Ord, Hash)]
2267#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2268#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2269pub struct ConstraintCharacteristics {
2270 pub deferrable: Option<bool>,
2272 pub initially: Option<DeferrableInitial>,
2274 pub enforced: Option<bool>,
2276}
2277
2278#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2280#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2281#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2282pub enum DeferrableInitial {
2283 Immediate,
2285 Deferred,
2287}
2288
2289impl ConstraintCharacteristics {
2290 fn deferrable_text(&self) -> Option<&'static str> {
2291 self.deferrable.map(|deferrable| {
2292 if deferrable {
2293 "DEFERRABLE"
2294 } else {
2295 "NOT DEFERRABLE"
2296 }
2297 })
2298 }
2299
2300 fn initially_immediate_text(&self) -> Option<&'static str> {
2301 self.initially
2302 .map(|initially_immediate| match initially_immediate {
2303 DeferrableInitial::Immediate => "INITIALLY IMMEDIATE",
2304 DeferrableInitial::Deferred => "INITIALLY DEFERRED",
2305 })
2306 }
2307
2308 fn enforced_text(&self) -> Option<&'static str> {
2309 self.enforced.map(
2310 |enforced| {
2311 if enforced {
2312 "ENFORCED"
2313 } else {
2314 "NOT ENFORCED"
2315 }
2316 },
2317 )
2318 }
2319}
2320
2321impl fmt::Display for ConstraintCharacteristics {
2322 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2323 let deferrable = self.deferrable_text();
2324 let initially_immediate = self.initially_immediate_text();
2325 let enforced = self.enforced_text();
2326
2327 match (deferrable, initially_immediate, enforced) {
2328 (None, None, None) => Ok(()),
2329 (None, None, Some(enforced)) => write!(f, "{enforced}"),
2330 (None, Some(initial), None) => write!(f, "{initial}"),
2331 (None, Some(initial), Some(enforced)) => write!(f, "{initial} {enforced}"),
2332 (Some(deferrable), None, None) => write!(f, "{deferrable}"),
2333 (Some(deferrable), None, Some(enforced)) => write!(f, "{deferrable} {enforced}"),
2334 (Some(deferrable), Some(initial), None) => write!(f, "{deferrable} {initial}"),
2335 (Some(deferrable), Some(initial), Some(enforced)) => {
2336 write!(f, "{deferrable} {initial} {enforced}")
2337 }
2338 }
2339 }
2340}
2341
2342#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2347#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2348#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2349pub enum ReferentialAction {
2350 Restrict,
2352 Cascade,
2354 SetNull,
2356 NoAction,
2358 SetDefault,
2360}
2361
2362impl fmt::Display for ReferentialAction {
2363 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2364 f.write_str(match self {
2365 ReferentialAction::Restrict => "RESTRICT",
2366 ReferentialAction::Cascade => "CASCADE",
2367 ReferentialAction::SetNull => "SET NULL",
2368 ReferentialAction::NoAction => "NO ACTION",
2369 ReferentialAction::SetDefault => "SET DEFAULT",
2370 })
2371 }
2372}
2373
2374#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2378#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2379#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2380pub enum DropBehavior {
2381 Restrict,
2383 Cascade,
2385}
2386
2387impl fmt::Display for DropBehavior {
2388 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2389 f.write_str(match self {
2390 DropBehavior::Restrict => "RESTRICT",
2391 DropBehavior::Cascade => "CASCADE",
2392 })
2393 }
2394}
2395
2396#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2398#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2399#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2400pub enum UserDefinedTypeRepresentation {
2401 Composite {
2403 attributes: Vec<UserDefinedTypeCompositeAttributeDef>,
2405 },
2406 Enum {
2411 labels: Vec<Ident>,
2413 },
2414 Range {
2418 options: Vec<UserDefinedTypeRangeOption>,
2420 },
2421 SqlDefinition {
2427 options: Vec<UserDefinedTypeSqlDefinitionOption>,
2429 },
2430}
2431
2432impl fmt::Display for UserDefinedTypeRepresentation {
2433 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2434 match self {
2435 Self::Composite { attributes } => {
2436 write!(f, "AS ({})", display_comma_separated(attributes))
2437 }
2438 Self::Enum { labels } => {
2439 write!(f, "AS ENUM ({})", display_comma_separated(labels))
2440 }
2441 Self::Range { options } => {
2442 write!(f, "AS RANGE ({})", display_comma_separated(options))
2443 }
2444 Self::SqlDefinition { options } => {
2445 write!(f, "({})", display_comma_separated(options))
2446 }
2447 }
2448 }
2449}
2450
2451#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2453#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2454#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2455pub struct UserDefinedTypeCompositeAttributeDef {
2456 pub name: Ident,
2458 pub data_type: DataType,
2460 pub collation: Option<ObjectName>,
2462}
2463
2464impl fmt::Display for UserDefinedTypeCompositeAttributeDef {
2465 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2466 write!(f, "{} {}", self.name, self.data_type)?;
2467 if let Some(collation) = &self.collation {
2468 write!(f, " COLLATE {collation}")?;
2469 }
2470 Ok(())
2471 }
2472}
2473
2474#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2497#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2498#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2499pub enum UserDefinedTypeInternalLength {
2500 Fixed(u64),
2502 Variable,
2504}
2505
2506impl fmt::Display for UserDefinedTypeInternalLength {
2507 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2508 match self {
2509 UserDefinedTypeInternalLength::Fixed(n) => write!(f, "{}", n),
2510 UserDefinedTypeInternalLength::Variable => write!(f, "VARIABLE"),
2511 }
2512 }
2513}
2514
2515#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2534#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2535#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2536pub enum Alignment {
2537 Char,
2539 Int2,
2541 Int4,
2543 Double,
2545}
2546
2547impl fmt::Display for Alignment {
2548 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2549 match self {
2550 Alignment::Char => write!(f, "char"),
2551 Alignment::Int2 => write!(f, "int2"),
2552 Alignment::Int4 => write!(f, "int4"),
2553 Alignment::Double => write!(f, "double"),
2554 }
2555 }
2556}
2557
2558#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2578#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2579#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2580pub enum UserDefinedTypeStorage {
2581 Plain,
2583 External,
2585 Extended,
2587 Main,
2589}
2590
2591impl fmt::Display for UserDefinedTypeStorage {
2592 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2593 match self {
2594 UserDefinedTypeStorage::Plain => write!(f, "plain"),
2595 UserDefinedTypeStorage::External => write!(f, "external"),
2596 UserDefinedTypeStorage::Extended => write!(f, "extended"),
2597 UserDefinedTypeStorage::Main => write!(f, "main"),
2598 }
2599 }
2600}
2601
2602#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2620#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2621#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2622pub enum UserDefinedTypeRangeOption {
2623 Subtype(DataType),
2625 SubtypeOpClass(ObjectName),
2627 Collation(ObjectName),
2629 Canonical(ObjectName),
2631 SubtypeDiff(ObjectName),
2633 MultirangeTypeName(ObjectName),
2635}
2636
2637impl fmt::Display for UserDefinedTypeRangeOption {
2638 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2639 match self {
2640 UserDefinedTypeRangeOption::Subtype(dt) => write!(f, "SUBTYPE = {}", dt),
2641 UserDefinedTypeRangeOption::SubtypeOpClass(name) => {
2642 write!(f, "SUBTYPE_OPCLASS = {}", name)
2643 }
2644 UserDefinedTypeRangeOption::Collation(name) => write!(f, "COLLATION = {}", name),
2645 UserDefinedTypeRangeOption::Canonical(name) => write!(f, "CANONICAL = {}", name),
2646 UserDefinedTypeRangeOption::SubtypeDiff(name) => write!(f, "SUBTYPE_DIFF = {}", name),
2647 UserDefinedTypeRangeOption::MultirangeTypeName(name) => {
2648 write!(f, "MULTIRANGE_TYPE_NAME = {}", name)
2649 }
2650 }
2651 }
2652}
2653
2654#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2675#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2676#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2677pub enum UserDefinedTypeSqlDefinitionOption {
2678 Input(ObjectName),
2680 Output(ObjectName),
2682 Receive(ObjectName),
2684 Send(ObjectName),
2686 TypmodIn(ObjectName),
2688 TypmodOut(ObjectName),
2690 Analyze(ObjectName),
2692 Subscript(ObjectName),
2694 InternalLength(UserDefinedTypeInternalLength),
2696 PassedByValue,
2698 Alignment(Alignment),
2700 Storage(UserDefinedTypeStorage),
2702 Like(ObjectName),
2704 Category(char),
2706 Preferred(bool),
2708 Default(Expr),
2710 Element(DataType),
2712 Delimiter(String),
2714 Collatable(bool),
2716}
2717
2718impl fmt::Display for UserDefinedTypeSqlDefinitionOption {
2719 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2720 match self {
2721 UserDefinedTypeSqlDefinitionOption::Input(name) => write!(f, "INPUT = {}", name),
2722 UserDefinedTypeSqlDefinitionOption::Output(name) => write!(f, "OUTPUT = {}", name),
2723 UserDefinedTypeSqlDefinitionOption::Receive(name) => write!(f, "RECEIVE = {}", name),
2724 UserDefinedTypeSqlDefinitionOption::Send(name) => write!(f, "SEND = {}", name),
2725 UserDefinedTypeSqlDefinitionOption::TypmodIn(name) => write!(f, "TYPMOD_IN = {}", name),
2726 UserDefinedTypeSqlDefinitionOption::TypmodOut(name) => {
2727 write!(f, "TYPMOD_OUT = {}", name)
2728 }
2729 UserDefinedTypeSqlDefinitionOption::Analyze(name) => write!(f, "ANALYZE = {}", name),
2730 UserDefinedTypeSqlDefinitionOption::Subscript(name) => {
2731 write!(f, "SUBSCRIPT = {}", name)
2732 }
2733 UserDefinedTypeSqlDefinitionOption::InternalLength(len) => {
2734 write!(f, "INTERNALLENGTH = {}", len)
2735 }
2736 UserDefinedTypeSqlDefinitionOption::PassedByValue => write!(f, "PASSEDBYVALUE"),
2737 UserDefinedTypeSqlDefinitionOption::Alignment(align) => {
2738 write!(f, "ALIGNMENT = {}", align)
2739 }
2740 UserDefinedTypeSqlDefinitionOption::Storage(storage) => {
2741 write!(f, "STORAGE = {}", storage)
2742 }
2743 UserDefinedTypeSqlDefinitionOption::Like(name) => write!(f, "LIKE = {}", name),
2744 UserDefinedTypeSqlDefinitionOption::Category(c) => write!(f, "CATEGORY = '{}'", c),
2745 UserDefinedTypeSqlDefinitionOption::Preferred(b) => write!(f, "PREFERRED = {}", b),
2746 UserDefinedTypeSqlDefinitionOption::Default(expr) => write!(f, "DEFAULT = {}", expr),
2747 UserDefinedTypeSqlDefinitionOption::Element(dt) => write!(f, "ELEMENT = {}", dt),
2748 UserDefinedTypeSqlDefinitionOption::Delimiter(s) => {
2749 write!(f, "DELIMITER = '{}'", escape_single_quote_string(s))
2750 }
2751 UserDefinedTypeSqlDefinitionOption::Collatable(b) => write!(f, "COLLATABLE = {}", b),
2752 }
2753 }
2754}
2755
2756#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2760#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2761#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2762pub enum Partition {
2763 Identifier(Ident),
2765 Expr(Expr),
2767 Part(Expr),
2770 Partitions(Vec<Expr>),
2772}
2773
2774impl fmt::Display for Partition {
2775 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2776 match self {
2777 Partition::Identifier(id) => write!(f, "PARTITION ID {id}"),
2778 Partition::Expr(expr) => write!(f, "PARTITION {expr}"),
2779 Partition::Part(expr) => write!(f, "PART {expr}"),
2780 Partition::Partitions(partitions) => {
2781 write!(f, "PARTITION ({})", display_comma_separated(partitions))
2782 }
2783 }
2784 }
2785}
2786
2787#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2790#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2791#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2792pub enum Deduplicate {
2793 All,
2795 ByExpression(Expr),
2797}
2798
2799impl fmt::Display for Deduplicate {
2800 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2801 match self {
2802 Deduplicate::All => write!(f, "DEDUPLICATE"),
2803 Deduplicate::ByExpression(expr) => write!(f, "DEDUPLICATE BY {expr}"),
2804 }
2805 }
2806}
2807
2808#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2813#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2814#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2815pub struct ClusteredBy {
2816 pub columns: Vec<Ident>,
2818 pub sorted_by: Option<Vec<OrderByExpr>>,
2820 pub num_buckets: Value,
2822}
2823
2824impl fmt::Display for ClusteredBy {
2825 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2826 write!(
2827 f,
2828 "CLUSTERED BY ({})",
2829 display_comma_separated(&self.columns)
2830 )?;
2831 if let Some(ref sorted_by) = self.sorted_by {
2832 write!(f, " SORTED BY ({})", display_comma_separated(sorted_by))?;
2833 }
2834 write!(f, " INTO {} BUCKETS", self.num_buckets)
2835 }
2836}
2837
2838#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2840#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2841#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2842pub struct CreateIndex {
2843 pub name: Option<ObjectName>,
2845 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2846 pub table_name: ObjectName,
2848 pub using: Option<IndexType>,
2851 pub columns: Vec<IndexColumn>,
2853 pub unique: bool,
2855 pub concurrently: bool,
2857 pub r#async: bool,
2861 pub if_not_exists: bool,
2863 pub include: Vec<Ident>,
2865 pub nulls_distinct: Option<bool>,
2867 pub with: Vec<Expr>,
2869 pub predicate: Option<Expr>,
2871 pub index_options: Vec<IndexOption>,
2873 pub alter_options: Vec<AlterTableOperation>,
2880}
2881
2882impl fmt::Display for CreateIndex {
2883 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2884 write!(
2885 f,
2886 "CREATE {unique}INDEX {concurrently}{async_}{if_not_exists}",
2887 unique = if self.unique { "UNIQUE " } else { "" },
2888 concurrently = if self.concurrently {
2889 "CONCURRENTLY "
2890 } else {
2891 ""
2892 },
2893 async_ = if self.r#async { "ASYNC " } else { "" },
2894 if_not_exists = if self.if_not_exists {
2895 "IF NOT EXISTS "
2896 } else {
2897 ""
2898 },
2899 )?;
2900 if let Some(value) = &self.name {
2901 write!(f, "{value} ")?;
2902 }
2903 write!(f, "ON {}", self.table_name)?;
2904 if let Some(value) = &self.using {
2905 write!(f, " USING {value} ")?;
2906 }
2907 write!(f, "({})", display_comma_separated(&self.columns))?;
2908 if !self.include.is_empty() {
2909 write!(f, " INCLUDE ({})", display_comma_separated(&self.include))?;
2910 }
2911 if let Some(value) = self.nulls_distinct {
2912 if value {
2913 write!(f, " NULLS DISTINCT")?;
2914 } else {
2915 write!(f, " NULLS NOT DISTINCT")?;
2916 }
2917 }
2918 if !self.with.is_empty() {
2919 write!(f, " WITH ({})", display_comma_separated(&self.with))?;
2920 }
2921 if let Some(predicate) = &self.predicate {
2922 write!(f, " WHERE {predicate}")?;
2923 }
2924 if !self.index_options.is_empty() {
2925 write!(f, " {}", display_separated(&self.index_options, " "))?;
2926 }
2927 if !self.alter_options.is_empty() {
2928 write!(f, " {}", display_separated(&self.alter_options, " "))?;
2929 }
2930 Ok(())
2931 }
2932}
2933
2934#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2936#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2937#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2938pub struct CreateTable {
2939 pub or_replace: bool,
2941 pub temporary: bool,
2943 pub external: bool,
2945 pub dynamic: bool,
2947 pub global: Option<bool>,
2949 pub if_not_exists: bool,
2951 pub transient: bool,
2953 pub volatile: bool,
2955 pub iceberg: bool,
2957 pub snapshot: bool,
2960 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2962 pub name: ObjectName,
2963 pub columns: Vec<ColumnDef>,
2965 pub constraints: Vec<TableConstraint>,
2967 pub hive_distribution: HiveDistributionStyle,
2969 pub hive_formats: Option<HiveFormat>,
2971 pub table_options: CreateTableOptions,
2973 pub file_format: Option<FileFormat>,
2975 pub location: Option<String>,
2977 pub query: Option<Box<Query>>,
2979 pub without_rowid: bool,
2981 pub like: Option<CreateTableLikeKind>,
2983 pub clone: Option<ObjectName>,
2985 pub version: Option<TableVersion>,
2987 pub comment: Option<CommentDef>,
2991 pub on_commit: Option<OnCommit>,
2994 pub on_cluster: Option<Ident>,
2997 pub primary_key: Option<Box<Expr>>,
3000 pub order_by: Option<OneOrManyWithParens<Expr>>,
3004 pub partition_by: Option<Box<Expr>>,
3007 pub cluster_by: Option<WrappedCollection<Vec<Expr>>>,
3012 pub clustered_by: Option<ClusteredBy>,
3015 pub inherits: Option<Vec<ObjectName>>,
3020 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3024 pub partition_of: Option<ObjectName>,
3025 pub for_values: Option<ForValues>,
3028 pub strict: bool,
3032 pub copy_grants: bool,
3035 pub enable_schema_evolution: Option<bool>,
3038 pub change_tracking: Option<bool>,
3041 pub data_retention_time_in_days: Option<u64>,
3044 pub max_data_extension_time_in_days: Option<u64>,
3047 pub default_ddl_collation: Option<String>,
3050 pub with_aggregation_policy: Option<ObjectName>,
3053 pub with_row_access_policy: Option<RowAccessPolicy>,
3056 pub with_storage_lifecycle_policy: Option<StorageLifecyclePolicy>,
3059 pub with_tags: Option<Vec<Tag>>,
3062 pub external_volume: Option<String>,
3065 pub with_connection: Option<ObjectName>,
3068 pub base_location: Option<String>,
3071 pub catalog: Option<String>,
3074 pub catalog_sync: Option<String>,
3077 pub storage_serialization_policy: Option<StorageSerializationPolicy>,
3080 pub target_lag: Option<String>,
3083 pub warehouse: Option<Ident>,
3086 pub refresh_mode: Option<RefreshModeKind>,
3089 pub initialize: Option<InitializeKind>,
3092 pub require_user: bool,
3095 pub diststyle: Option<DistStyle>,
3098 pub distkey: Option<Expr>,
3101 pub sortkey: Option<Vec<Expr>>,
3104 pub backup: Option<bool>,
3107 pub multiset: Option<bool>,
3112 pub fallback: Option<bool>,
3117 pub with_data: Option<WithData>,
3121}
3122
3123impl fmt::Display for CreateTable {
3124 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3125 write!(
3133 f,
3134 "CREATE {or_replace}{external}{global}{multiset}{temporary}{transient}{volatile}{dynamic}{iceberg}{snapshot}TABLE {if_not_exists}{name}",
3135 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3136 external = if self.external { "EXTERNAL " } else { "" },
3137 snapshot = if self.snapshot { "SNAPSHOT " } else { "" },
3138 global = self.global
3139 .map(|global| {
3140 if global {
3141 "GLOBAL "
3142 } else {
3143 "LOCAL "
3144 }
3145 })
3146 .unwrap_or(""),
3147 if_not_exists = if self.if_not_exists { "IF NOT EXISTS " } else { "" },
3148 multiset = self
3149 .multiset
3150 .map(|m| if m { "MULTISET " } else { "SET " })
3151 .unwrap_or(""),
3152 temporary = if self.temporary { "TEMPORARY " } else { "" },
3153 transient = if self.transient { "TRANSIENT " } else { "" },
3154 volatile = if self.volatile { "VOLATILE " } else { "" },
3155 iceberg = if self.iceberg { "ICEBERG " } else { "" },
3156 dynamic = if self.dynamic { "DYNAMIC " } else { "" },
3157 name = self.name,
3158 )?;
3159 if let Some(fallback) = self.fallback {
3160 write!(f, ", {}", if fallback { "FALLBACK" } else { "NO FALLBACK" })?;
3161 }
3162 if let Some(partition_of) = &self.partition_of {
3163 write!(f, " PARTITION OF {partition_of}")?;
3164 }
3165 if let Some(on_cluster) = &self.on_cluster {
3166 write!(f, " ON CLUSTER {on_cluster}")?;
3167 }
3168 if !self.columns.is_empty() || !self.constraints.is_empty() {
3169 f.write_str(" (")?;
3170 NewLine.fmt(f)?;
3171 Indent(DisplayCommaSeparated(&self.columns)).fmt(f)?;
3172 if !self.columns.is_empty() && !self.constraints.is_empty() {
3173 f.write_str(",")?;
3174 SpaceOrNewline.fmt(f)?;
3175 }
3176 Indent(DisplayCommaSeparated(&self.constraints)).fmt(f)?;
3177 NewLine.fmt(f)?;
3178 f.write_str(")")?;
3179 } else if self.query.is_none()
3180 && self.like.is_none()
3181 && self.clone.is_none()
3182 && self.partition_of.is_none()
3183 {
3184 f.write_str(" ()")?;
3186 } else if let Some(CreateTableLikeKind::Parenthesized(like_in_columns_list)) = &self.like {
3187 write!(f, " ({like_in_columns_list})")?;
3188 }
3189 if let Some(for_values) = &self.for_values {
3190 write!(f, " {for_values}")?;
3191 }
3192
3193 if let Some(comment) = &self.comment {
3196 write!(f, " COMMENT '{comment}'")?;
3197 }
3198
3199 if self.without_rowid {
3201 write!(f, " WITHOUT ROWID")?;
3202 }
3203
3204 if let Some(CreateTableLikeKind::Plain(like)) = &self.like {
3205 write!(f, " {like}")?;
3206 }
3207
3208 if let Some(c) = &self.clone {
3209 write!(f, " CLONE {c}")?;
3210 }
3211
3212 if let Some(version) = &self.version {
3213 write!(f, " {version}")?;
3214 }
3215
3216 match &self.hive_distribution {
3217 HiveDistributionStyle::PARTITIONED { columns } => {
3218 write!(f, " PARTITIONED BY ({})", display_comma_separated(columns))?;
3219 }
3220 HiveDistributionStyle::SKEWED {
3221 columns,
3222 on,
3223 stored_as_directories,
3224 } => {
3225 write!(
3226 f,
3227 " SKEWED BY ({})) ON ({})",
3228 display_comma_separated(columns),
3229 display_comma_separated(on)
3230 )?;
3231 if *stored_as_directories {
3232 write!(f, " STORED AS DIRECTORIES")?;
3233 }
3234 }
3235 _ => (),
3236 }
3237
3238 if let Some(clustered_by) = &self.clustered_by {
3239 write!(f, " {clustered_by}")?;
3240 }
3241
3242 if let Some(HiveFormat {
3243 row_format,
3244 serde_properties,
3245 storage,
3246 location,
3247 }) = &self.hive_formats
3248 {
3249 match row_format {
3250 Some(HiveRowFormat::SERDE { class }) => write!(f, " ROW FORMAT SERDE '{class}'")?,
3251 Some(HiveRowFormat::DELIMITED { delimiters }) => {
3252 write!(f, " ROW FORMAT DELIMITED")?;
3253 if !delimiters.is_empty() {
3254 write!(f, " {}", display_separated(delimiters, " "))?;
3255 }
3256 }
3257 None => (),
3258 }
3259 match storage {
3260 Some(HiveIOFormat::IOF {
3261 input_format,
3262 output_format,
3263 }) => write!(
3264 f,
3265 " STORED AS INPUTFORMAT {input_format} OUTPUTFORMAT {output_format}"
3266 )?,
3267 Some(HiveIOFormat::FileFormat { format }) if !self.external => {
3268 write!(f, " STORED AS {format}")?
3269 }
3270 Some(HiveIOFormat::Using { format }) => write!(f, " USING {format}")?,
3271 _ => (),
3272 }
3273 if let Some(serde_properties) = serde_properties.as_ref() {
3274 write!(
3275 f,
3276 " WITH SERDEPROPERTIES ({})",
3277 display_comma_separated(serde_properties)
3278 )?;
3279 }
3280 if !self.external {
3281 if let Some(loc) = location {
3282 write!(f, " LOCATION '{loc}'")?;
3283 }
3284 }
3285 }
3286 if self.external {
3287 if let Some(file_format) = self.file_format {
3288 write!(f, " STORED AS {file_format}")?;
3289 }
3290 if let Some(location) = &self.location {
3291 write!(f, " LOCATION '{location}'")?;
3292 }
3293 }
3294
3295 match &self.table_options {
3296 options @ CreateTableOptions::With(_)
3297 | options @ CreateTableOptions::Plain(_)
3298 | options @ CreateTableOptions::TableProperties(_) => write!(f, " {options}")?,
3299 _ => (),
3300 }
3301
3302 if let Some(primary_key) = &self.primary_key {
3303 write!(f, " PRIMARY KEY {primary_key}")?;
3304 }
3305 if let Some(order_by) = &self.order_by {
3306 write!(f, " ORDER BY {order_by}")?;
3307 }
3308 if let Some(inherits) = &self.inherits {
3309 write!(f, " INHERITS ({})", display_comma_separated(inherits))?;
3310 }
3311 if let Some(partition_by) = self.partition_by.as_ref() {
3312 write!(f, " PARTITION BY {partition_by}")?;
3313 }
3314 if let Some(cluster_by) = self.cluster_by.as_ref() {
3315 write!(f, " CLUSTER BY {cluster_by}")?;
3316 }
3317 if let Some(with_connection) = &self.with_connection {
3318 write!(f, " WITH CONNECTION {with_connection}")?;
3319 }
3320 if let options @ CreateTableOptions::Options(_) = &self.table_options {
3321 write!(f, " {options}")?;
3322 }
3323 if let Some(external_volume) = self.external_volume.as_ref() {
3324 write!(f, " EXTERNAL_VOLUME='{external_volume}'")?;
3325 }
3326
3327 if let Some(catalog) = self.catalog.as_ref() {
3328 write!(f, " CATALOG='{catalog}'")?;
3329 }
3330
3331 if self.iceberg {
3332 if let Some(base_location) = self.base_location.as_ref() {
3333 write!(f, " BASE_LOCATION='{base_location}'")?;
3334 }
3335 }
3336
3337 if let Some(catalog_sync) = self.catalog_sync.as_ref() {
3338 write!(f, " CATALOG_SYNC='{catalog_sync}'")?;
3339 }
3340
3341 if let Some(storage_serialization_policy) = self.storage_serialization_policy.as_ref() {
3342 write!(
3343 f,
3344 " STORAGE_SERIALIZATION_POLICY={storage_serialization_policy}"
3345 )?;
3346 }
3347
3348 if self.copy_grants {
3349 write!(f, " COPY GRANTS")?;
3350 }
3351
3352 if let Some(is_enabled) = self.enable_schema_evolution {
3353 write!(
3354 f,
3355 " ENABLE_SCHEMA_EVOLUTION={}",
3356 if is_enabled { "TRUE" } else { "FALSE" }
3357 )?;
3358 }
3359
3360 if let Some(is_enabled) = self.change_tracking {
3361 write!(
3362 f,
3363 " CHANGE_TRACKING={}",
3364 if is_enabled { "TRUE" } else { "FALSE" }
3365 )?;
3366 }
3367
3368 if let Some(data_retention_time_in_days) = self.data_retention_time_in_days {
3369 write!(
3370 f,
3371 " DATA_RETENTION_TIME_IN_DAYS={data_retention_time_in_days}",
3372 )?;
3373 }
3374
3375 if let Some(max_data_extension_time_in_days) = self.max_data_extension_time_in_days {
3376 write!(
3377 f,
3378 " MAX_DATA_EXTENSION_TIME_IN_DAYS={max_data_extension_time_in_days}",
3379 )?;
3380 }
3381
3382 if let Some(default_ddl_collation) = &self.default_ddl_collation {
3383 write!(f, " DEFAULT_DDL_COLLATION='{default_ddl_collation}'",)?;
3384 }
3385
3386 if let Some(with_aggregation_policy) = &self.with_aggregation_policy {
3387 write!(f, " WITH AGGREGATION POLICY {with_aggregation_policy}",)?;
3388 }
3389
3390 if let Some(row_access_policy) = &self.with_row_access_policy {
3391 write!(f, " {row_access_policy}",)?;
3392 }
3393
3394 if let Some(storage_lifecycle_policy) = &self.with_storage_lifecycle_policy {
3395 write!(f, " {storage_lifecycle_policy}",)?;
3396 }
3397
3398 if let Some(tag) = &self.with_tags {
3399 write!(f, " WITH TAG ({})", display_comma_separated(tag.as_slice()))?;
3400 }
3401
3402 if let Some(target_lag) = &self.target_lag {
3403 write!(f, " TARGET_LAG='{target_lag}'")?;
3404 }
3405
3406 if let Some(warehouse) = &self.warehouse {
3407 write!(f, " WAREHOUSE={warehouse}")?;
3408 }
3409
3410 if let Some(refresh_mode) = &self.refresh_mode {
3411 write!(f, " REFRESH_MODE={refresh_mode}")?;
3412 }
3413
3414 if let Some(initialize) = &self.initialize {
3415 write!(f, " INITIALIZE={initialize}")?;
3416 }
3417
3418 if self.require_user {
3419 write!(f, " REQUIRE USER")?;
3420 }
3421
3422 if self.on_commit.is_some() {
3423 let on_commit = match self.on_commit {
3424 Some(OnCommit::DeleteRows) => "ON COMMIT DELETE ROWS",
3425 Some(OnCommit::PreserveRows) => "ON COMMIT PRESERVE ROWS",
3426 Some(OnCommit::Drop) => "ON COMMIT DROP",
3427 None => "",
3428 };
3429 write!(f, " {on_commit}")?;
3430 }
3431 if self.strict {
3432 write!(f, " STRICT")?;
3433 }
3434 if let Some(backup) = self.backup {
3435 write!(f, " BACKUP {}", if backup { "YES" } else { "NO" })?;
3436 }
3437 if let Some(diststyle) = &self.diststyle {
3438 write!(f, " DISTSTYLE {diststyle}")?;
3439 }
3440 if let Some(distkey) = &self.distkey {
3441 write!(f, " DISTKEY({distkey})")?;
3442 }
3443 if let Some(sortkey) = &self.sortkey {
3444 write!(f, " SORTKEY({})", display_comma_separated(sortkey))?;
3445 }
3446 if let Some(query) = &self.query {
3447 write!(f, " AS {query}")?;
3448 }
3449 if let Some(with_data) = &self.with_data {
3450 write!(f, " {with_data}")?;
3451 }
3452 Ok(())
3453 }
3454}
3455
3456#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
3460#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3461#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3462pub struct WithData {
3463 pub data: bool,
3465 pub statistics: Option<bool>,
3468}
3469
3470impl fmt::Display for WithData {
3471 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3472 f.write_str("WITH ")?;
3473 if !self.data {
3474 f.write_str("NO ")?;
3475 }
3476 f.write_str("DATA")?;
3477 if let Some(stats) = self.statistics {
3478 f.write_str(" AND ")?;
3479 if !stats {
3480 f.write_str("NO ")?;
3481 }
3482 f.write_str("STATISTICS")?;
3483 }
3484 Ok(())
3485 }
3486}
3487
3488#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3494#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3495#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3496pub enum ForValues {
3497 In(Vec<Expr>),
3499 From {
3501 from: Vec<PartitionBoundValue>,
3503 to: Vec<PartitionBoundValue>,
3505 },
3506 With {
3508 modulus: u64,
3510 remainder: u64,
3512 },
3513 Default,
3515}
3516
3517impl fmt::Display for ForValues {
3518 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3519 match self {
3520 ForValues::In(values) => {
3521 write!(f, "FOR VALUES IN ({})", display_comma_separated(values))
3522 }
3523 ForValues::From { from, to } => {
3524 write!(
3525 f,
3526 "FOR VALUES FROM ({}) TO ({})",
3527 display_comma_separated(from),
3528 display_comma_separated(to)
3529 )
3530 }
3531 ForValues::With { modulus, remainder } => {
3532 write!(
3533 f,
3534 "FOR VALUES WITH (MODULUS {modulus}, REMAINDER {remainder})"
3535 )
3536 }
3537 ForValues::Default => write!(f, "DEFAULT"),
3538 }
3539 }
3540}
3541
3542#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3547#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3548#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3549pub enum PartitionBoundValue {
3550 Expr(Expr),
3552 MinValue,
3554 MaxValue,
3556}
3557
3558impl fmt::Display for PartitionBoundValue {
3559 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3560 match self {
3561 PartitionBoundValue::Expr(expr) => write!(f, "{expr}"),
3562 PartitionBoundValue::MinValue => write!(f, "MINVALUE"),
3563 PartitionBoundValue::MaxValue => write!(f, "MAXVALUE"),
3564 }
3565 }
3566}
3567
3568#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3572#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3573#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3574pub enum DistStyle {
3575 Auto,
3577 Even,
3579 Key,
3581 All,
3583}
3584
3585impl fmt::Display for DistStyle {
3586 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3587 match self {
3588 DistStyle::Auto => write!(f, "AUTO"),
3589 DistStyle::Even => write!(f, "EVEN"),
3590 DistStyle::Key => write!(f, "KEY"),
3591 DistStyle::All => write!(f, "ALL"),
3592 }
3593 }
3594}
3595
3596#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3597#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3598#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3599pub struct CreateDomain {
3612 pub name: ObjectName,
3614 pub data_type: DataType,
3616 pub collation: Option<Ident>,
3618 pub default: Option<Expr>,
3620 pub constraints: Vec<TableConstraint>,
3622}
3623
3624impl fmt::Display for CreateDomain {
3625 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3626 write!(
3627 f,
3628 "CREATE DOMAIN {name} AS {data_type}",
3629 name = self.name,
3630 data_type = self.data_type
3631 )?;
3632 if let Some(collation) = &self.collation {
3633 write!(f, " COLLATE {collation}")?;
3634 }
3635 if let Some(default) = &self.default {
3636 write!(f, " DEFAULT {default}")?;
3637 }
3638 if !self.constraints.is_empty() {
3639 write!(f, " {}", display_separated(&self.constraints, " "))?;
3640 }
3641 Ok(())
3642 }
3643}
3644
3645#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3647#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3648#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3649pub enum FunctionReturnType {
3650 DataType(DataType),
3652 SetOf(DataType),
3656}
3657
3658impl fmt::Display for FunctionReturnType {
3659 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3660 match self {
3661 FunctionReturnType::DataType(data_type) => write!(f, "{data_type}"),
3662 FunctionReturnType::SetOf(data_type) => write!(f, "SETOF {data_type}"),
3663 }
3664 }
3665}
3666
3667#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3668#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3669#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3670pub struct CreateFunction {
3672 pub or_alter: bool,
3676 pub or_replace: bool,
3678 pub temporary: bool,
3680 pub if_not_exists: bool,
3682 pub name: ObjectName,
3684 pub args: Option<Vec<OperateFunctionArg>>,
3686 pub return_type: Option<FunctionReturnType>,
3688 pub function_body: Option<CreateFunctionBody>,
3696 pub behavior: Option<FunctionBehavior>,
3702 pub called_on_null: Option<FunctionCalledOnNull>,
3706 pub parallel: Option<FunctionParallel>,
3710 pub security: Option<FunctionSecurity>,
3714 pub set_params: Vec<FunctionDefinitionSetParam>,
3718 pub using: Option<CreateFunctionUsing>,
3720 pub language: Option<Ident>,
3728 pub determinism_specifier: Option<FunctionDeterminismSpecifier>,
3732 pub options: Option<Vec<SqlOption>>,
3736 pub remote_connection: Option<ObjectName>,
3746}
3747
3748impl fmt::Display for CreateFunction {
3749 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3750 write!(
3751 f,
3752 "CREATE {or_alter}{or_replace}{temp}FUNCTION {if_not_exists}{name}",
3753 name = self.name,
3754 temp = if self.temporary { "TEMPORARY " } else { "" },
3755 or_alter = if self.or_alter { "OR ALTER " } else { "" },
3756 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3757 if_not_exists = if self.if_not_exists {
3758 "IF NOT EXISTS "
3759 } else {
3760 ""
3761 },
3762 )?;
3763 if let Some(args) = &self.args {
3764 write!(f, "({})", display_comma_separated(args))?;
3765 }
3766 if let Some(return_type) = &self.return_type {
3767 write!(f, " RETURNS {return_type}")?;
3768 }
3769 if let Some(determinism_specifier) = &self.determinism_specifier {
3770 write!(f, " {determinism_specifier}")?;
3771 }
3772 if let Some(language) = &self.language {
3773 write!(f, " LANGUAGE {language}")?;
3774 }
3775 if let Some(behavior) = &self.behavior {
3776 write!(f, " {behavior}")?;
3777 }
3778 if let Some(called_on_null) = &self.called_on_null {
3779 write!(f, " {called_on_null}")?;
3780 }
3781 if let Some(parallel) = &self.parallel {
3782 write!(f, " {parallel}")?;
3783 }
3784 if let Some(security) = &self.security {
3785 write!(f, " {security}")?;
3786 }
3787 for set_param in &self.set_params {
3788 write!(f, " {set_param}")?;
3789 }
3790 if let Some(remote_connection) = &self.remote_connection {
3791 write!(f, " REMOTE WITH CONNECTION {remote_connection}")?;
3792 }
3793 if let Some(CreateFunctionBody::AsBeforeOptions { body, link_symbol }) = &self.function_body
3794 {
3795 write!(f, " AS {body}")?;
3796 if let Some(link_symbol) = link_symbol {
3797 write!(f, ", {link_symbol}")?;
3798 }
3799 }
3800 if let Some(CreateFunctionBody::Return(function_body)) = &self.function_body {
3801 write!(f, " RETURN {function_body}")?;
3802 }
3803 if let Some(CreateFunctionBody::AsReturnExpr(function_body)) = &self.function_body {
3804 write!(f, " AS RETURN {function_body}")?;
3805 }
3806 if let Some(CreateFunctionBody::AsReturnSelect(function_body)) = &self.function_body {
3807 write!(f, " AS RETURN {function_body}")?;
3808 }
3809 if let Some(using) = &self.using {
3810 write!(f, " {using}")?;
3811 }
3812 if let Some(options) = &self.options {
3813 write!(
3814 f,
3815 " OPTIONS({})",
3816 display_comma_separated(options.as_slice())
3817 )?;
3818 }
3819 if let Some(CreateFunctionBody::AsAfterOptions(function_body)) = &self.function_body {
3820 write!(f, " AS {function_body}")?;
3821 }
3822 if let Some(CreateFunctionBody::AsBeginEnd(bes)) = &self.function_body {
3823 write!(f, " AS {bes}")?;
3824 }
3825 Ok(())
3826 }
3827}
3828
3829#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3839#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3840#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3841pub struct CreateConnector {
3842 pub name: Ident,
3844 pub if_not_exists: bool,
3846 pub connector_type: Option<String>,
3848 pub url: Option<String>,
3850 pub comment: Option<CommentDef>,
3852 pub with_dcproperties: Option<Vec<SqlOption>>,
3854}
3855
3856impl fmt::Display for CreateConnector {
3857 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3858 write!(
3859 f,
3860 "CREATE CONNECTOR {if_not_exists}{name}",
3861 if_not_exists = if self.if_not_exists {
3862 "IF NOT EXISTS "
3863 } else {
3864 ""
3865 },
3866 name = self.name,
3867 )?;
3868
3869 if let Some(connector_type) = &self.connector_type {
3870 write!(f, " TYPE '{connector_type}'")?;
3871 }
3872
3873 if let Some(url) = &self.url {
3874 write!(f, " URL '{url}'")?;
3875 }
3876
3877 if let Some(comment) = &self.comment {
3878 write!(f, " COMMENT = '{comment}'")?;
3879 }
3880
3881 if let Some(with_dcproperties) = &self.with_dcproperties {
3882 write!(
3883 f,
3884 " WITH DCPROPERTIES({})",
3885 display_comma_separated(with_dcproperties)
3886 )?;
3887 }
3888
3889 Ok(())
3890 }
3891}
3892
3893#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3898#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3899#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3900pub enum AlterSchemaOperation {
3901 SetDefaultCollate {
3903 collate: Expr,
3905 },
3906 AddReplica {
3908 replica: Ident,
3910 options: Option<Vec<SqlOption>>,
3912 },
3913 DropReplica {
3915 replica: Ident,
3917 },
3918 SetOptionsParens {
3920 options: Vec<SqlOption>,
3922 },
3923 Rename {
3925 name: ObjectName,
3927 },
3928 OwnerTo {
3930 owner: Owner,
3932 },
3933}
3934
3935impl fmt::Display for AlterSchemaOperation {
3936 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3937 match self {
3938 AlterSchemaOperation::SetDefaultCollate { collate } => {
3939 write!(f, "SET DEFAULT COLLATE {collate}")
3940 }
3941 AlterSchemaOperation::AddReplica { replica, options } => {
3942 write!(f, "ADD REPLICA {replica}")?;
3943 if let Some(options) = options {
3944 write!(f, " OPTIONS ({})", display_comma_separated(options))?;
3945 }
3946 Ok(())
3947 }
3948 AlterSchemaOperation::DropReplica { replica } => write!(f, "DROP REPLICA {replica}"),
3949 AlterSchemaOperation::SetOptionsParens { options } => {
3950 write!(f, "SET OPTIONS ({})", display_comma_separated(options))
3951 }
3952 AlterSchemaOperation::Rename { name } => write!(f, "RENAME TO {name}"),
3953 AlterSchemaOperation::OwnerTo { owner } => write!(f, "OWNER TO {owner}"),
3954 }
3955 }
3956}
3957#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3963#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3964#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3965pub enum RenameTableNameKind {
3966 As(ObjectName),
3968 To(ObjectName),
3970}
3971
3972impl fmt::Display for RenameTableNameKind {
3973 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3974 match self {
3975 RenameTableNameKind::As(name) => write!(f, "AS {name}"),
3976 RenameTableNameKind::To(name) => write!(f, "TO {name}"),
3977 }
3978 }
3979}
3980
3981#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3982#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3983#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3984pub struct AlterSchema {
3986 pub name: ObjectName,
3988 pub if_exists: bool,
3990 pub operations: Vec<AlterSchemaOperation>,
3992}
3993
3994impl fmt::Display for AlterSchema {
3995 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3996 write!(f, "ALTER SCHEMA ")?;
3997 if self.if_exists {
3998 write!(f, "IF EXISTS ")?;
3999 }
4000 write!(f, "{}", self.name)?;
4001 for operation in &self.operations {
4002 write!(f, " {operation}")?;
4003 }
4004
4005 Ok(())
4006 }
4007}
4008
4009impl Spanned for RenameTableNameKind {
4010 fn span(&self) -> Span {
4011 match self {
4012 RenameTableNameKind::As(name) => name.span(),
4013 RenameTableNameKind::To(name) => name.span(),
4014 }
4015 }
4016}
4017
4018#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
4019#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4020#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4021pub enum TriggerObjectKind {
4023 For(TriggerObject),
4025 ForEach(TriggerObject),
4027}
4028
4029impl Display for TriggerObjectKind {
4030 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4031 match self {
4032 TriggerObjectKind::For(obj) => write!(f, "FOR {obj}"),
4033 TriggerObjectKind::ForEach(obj) => write!(f, "FOR EACH {obj}"),
4034 }
4035 }
4036}
4037
4038#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4039#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4040#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4041pub struct CreateTrigger {
4055 pub or_alter: bool,
4059 pub temporary: bool,
4076 pub or_replace: bool,
4086 pub is_constraint: bool,
4088 pub name: ObjectName,
4090 pub period: Option<TriggerPeriod>,
4119 pub period_before_table: bool,
4130 pub events: Vec<TriggerEvent>,
4132 pub table_name: ObjectName,
4134 pub referenced_table_name: Option<ObjectName>,
4137 pub referencing: Vec<TriggerReferencing>,
4139 pub trigger_object: Option<TriggerObjectKind>,
4144 pub condition: Option<Expr>,
4146 pub exec_body: Option<TriggerExecBody>,
4148 pub statements_as: bool,
4150 pub statements: Option<ConditionalStatements>,
4152 pub characteristics: Option<ConstraintCharacteristics>,
4154}
4155
4156impl Display for CreateTrigger {
4157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4158 let CreateTrigger {
4159 or_alter,
4160 temporary,
4161 or_replace,
4162 is_constraint,
4163 name,
4164 period_before_table,
4165 period,
4166 events,
4167 table_name,
4168 referenced_table_name,
4169 referencing,
4170 trigger_object,
4171 condition,
4172 exec_body,
4173 statements_as,
4174 statements,
4175 characteristics,
4176 } = self;
4177 write!(
4178 f,
4179 "CREATE {temporary}{or_alter}{or_replace}{is_constraint}TRIGGER {name} ",
4180 temporary = if *temporary { "TEMPORARY " } else { "" },
4181 or_alter = if *or_alter { "OR ALTER " } else { "" },
4182 or_replace = if *or_replace { "OR REPLACE " } else { "" },
4183 is_constraint = if *is_constraint { "CONSTRAINT " } else { "" },
4184 )?;
4185
4186 if *period_before_table {
4187 if let Some(p) = period {
4188 write!(f, "{p} ")?;
4189 }
4190 if !events.is_empty() {
4191 write!(f, "{} ", display_separated(events, " OR "))?;
4192 }
4193 write!(f, "ON {table_name}")?;
4194 } else {
4195 write!(f, "ON {table_name} ")?;
4196 if let Some(p) = period {
4197 write!(f, "{p}")?;
4198 }
4199 if !events.is_empty() {
4200 write!(f, " {}", display_separated(events, ", "))?;
4201 }
4202 }
4203
4204 if let Some(referenced_table_name) = referenced_table_name {
4205 write!(f, " FROM {referenced_table_name}")?;
4206 }
4207
4208 if let Some(characteristics) = characteristics {
4209 write!(f, " {characteristics}")?;
4210 }
4211
4212 if !referencing.is_empty() {
4213 write!(f, " REFERENCING {}", display_separated(referencing, " "))?;
4214 }
4215
4216 if let Some(trigger_object) = trigger_object {
4217 write!(f, " {trigger_object}")?;
4218 }
4219 if let Some(condition) = condition {
4220 write!(f, " WHEN {condition}")?;
4221 }
4222 if let Some(exec_body) = exec_body {
4223 write!(f, " EXECUTE {exec_body}")?;
4224 }
4225 if let Some(statements) = statements {
4226 if *statements_as {
4227 write!(f, " AS")?;
4228 }
4229 write!(f, " {statements}")?;
4230 }
4231 Ok(())
4232 }
4233}
4234
4235#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4236#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4237#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4238pub struct DropTrigger {
4245 pub if_exists: bool,
4247 pub trigger_name: ObjectName,
4249 pub table_name: Option<ObjectName>,
4251 pub option: Option<ReferentialAction>,
4253}
4254
4255impl fmt::Display for DropTrigger {
4256 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4257 let DropTrigger {
4258 if_exists,
4259 trigger_name,
4260 table_name,
4261 option,
4262 } = self;
4263 write!(f, "DROP TRIGGER")?;
4264 if *if_exists {
4265 write!(f, " IF EXISTS")?;
4266 }
4267 match &table_name {
4268 Some(table_name) => write!(f, " {trigger_name} ON {table_name}")?,
4269 None => write!(f, " {trigger_name}")?,
4270 };
4271 if let Some(option) = option {
4272 write!(f, " {option}")?;
4273 }
4274 Ok(())
4275 }
4276}
4277
4278#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4284#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4285#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4286pub struct Truncate {
4287 pub table_names: Vec<super::TruncateTableTarget>,
4289 pub partitions: Option<Vec<Expr>>,
4291 pub table: bool,
4293 pub if_exists: bool,
4295 pub identity: Option<super::TruncateIdentityOption>,
4297 pub cascade: Option<super::CascadeOption>,
4299 pub on_cluster: Option<Ident>,
4302}
4303
4304impl fmt::Display for Truncate {
4305 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4306 let table = if self.table { "TABLE " } else { "" };
4307 let if_exists = if self.if_exists { "IF EXISTS " } else { "" };
4308
4309 write!(
4310 f,
4311 "TRUNCATE {table}{if_exists}{table_names}",
4312 table_names = display_comma_separated(&self.table_names)
4313 )?;
4314
4315 if let Some(identity) = &self.identity {
4316 match identity {
4317 super::TruncateIdentityOption::Restart => write!(f, " RESTART IDENTITY")?,
4318 super::TruncateIdentityOption::Continue => write!(f, " CONTINUE IDENTITY")?,
4319 }
4320 }
4321 if let Some(cascade) = &self.cascade {
4322 match cascade {
4323 super::CascadeOption::Cascade => write!(f, " CASCADE")?,
4324 super::CascadeOption::Restrict => write!(f, " RESTRICT")?,
4325 }
4326 }
4327
4328 if let Some(ref parts) = &self.partitions {
4329 if !parts.is_empty() {
4330 write!(f, " PARTITION ({})", display_comma_separated(parts))?;
4331 }
4332 }
4333 if let Some(on_cluster) = &self.on_cluster {
4334 write!(f, " ON CLUSTER {on_cluster}")?;
4335 }
4336 Ok(())
4337 }
4338}
4339
4340impl Spanned for Truncate {
4341 fn span(&self) -> Span {
4342 Span::union_iter(
4343 self.table_names.iter().map(|i| i.name.span()).chain(
4344 self.partitions
4345 .iter()
4346 .flat_map(|i| i.iter().map(|k| k.span())),
4347 ),
4348 )
4349 }
4350}
4351
4352#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4359#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4360#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4361pub struct Msck {
4362 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4364 pub table_name: ObjectName,
4365 pub repair: bool,
4367 pub partition_action: Option<super::AddDropSync>,
4369}
4370
4371impl fmt::Display for Msck {
4372 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4373 write!(
4374 f,
4375 "MSCK {repair}TABLE {table}",
4376 repair = if self.repair { "REPAIR " } else { "" },
4377 table = self.table_name
4378 )?;
4379 if let Some(pa) = &self.partition_action {
4380 write!(f, " {pa}")?;
4381 }
4382 Ok(())
4383 }
4384}
4385
4386impl Spanned for Msck {
4387 fn span(&self) -> Span {
4388 self.table_name.span()
4389 }
4390}
4391
4392#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4394#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4395#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4396pub struct CreateView {
4397 pub or_alter: bool,
4401 pub or_replace: bool,
4403 pub materialized: bool,
4405 pub secure: bool,
4408 pub name: ObjectName,
4410 pub name_before_not_exists: bool,
4421 pub columns: Vec<ViewColumnDef>,
4423 pub query: Box<Query>,
4425 pub options: CreateTableOptions,
4427 pub cluster_by: Vec<Ident>,
4429 pub comment: Option<String>,
4432 pub with_no_schema_binding: bool,
4434 pub if_not_exists: bool,
4436 pub temporary: bool,
4438 pub copy_grants: bool,
4441 pub to: Option<ObjectName>,
4444 pub params: Option<CreateViewParams>,
4446}
4447
4448impl fmt::Display for CreateView {
4449 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4450 write!(
4451 f,
4452 "CREATE {or_alter}{or_replace}",
4453 or_alter = if self.or_alter { "OR ALTER " } else { "" },
4454 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
4455 )?;
4456 if let Some(ref params) = self.params {
4457 params.fmt(f)?;
4458 }
4459 write!(
4460 f,
4461 "{secure}{materialized}{temporary}VIEW {if_not_and_name}{to}",
4462 if_not_and_name = if self.if_not_exists {
4463 if self.name_before_not_exists {
4464 format!("{} IF NOT EXISTS", self.name)
4465 } else {
4466 format!("IF NOT EXISTS {}", self.name)
4467 }
4468 } else {
4469 format!("{}", self.name)
4470 },
4471 secure = if self.secure { "SECURE " } else { "" },
4472 materialized = if self.materialized {
4473 "MATERIALIZED "
4474 } else {
4475 ""
4476 },
4477 temporary = if self.temporary { "TEMPORARY " } else { "" },
4478 to = self
4479 .to
4480 .as_ref()
4481 .map(|to| format!(" TO {to}"))
4482 .unwrap_or_default()
4483 )?;
4484 if self.copy_grants {
4485 write!(f, " COPY GRANTS")?;
4486 }
4487 if !self.columns.is_empty() {
4488 write!(f, " ({})", display_comma_separated(&self.columns))?;
4489 }
4490 if matches!(self.options, CreateTableOptions::With(_)) {
4491 write!(f, " {}", self.options)?;
4492 }
4493 if let Some(ref comment) = self.comment {
4494 write!(f, " COMMENT = '{}'", escape_single_quote_string(comment))?;
4495 }
4496 if !self.cluster_by.is_empty() {
4497 write!(
4498 f,
4499 " CLUSTER BY ({})",
4500 display_comma_separated(&self.cluster_by)
4501 )?;
4502 }
4503 if matches!(self.options, CreateTableOptions::Options(_)) {
4504 write!(f, " {}", self.options)?;
4505 }
4506 f.write_str(" AS")?;
4507 SpaceOrNewline.fmt(f)?;
4508 self.query.fmt(f)?;
4509 if self.with_no_schema_binding {
4510 write!(f, " WITH NO SCHEMA BINDING")?;
4511 }
4512 Ok(())
4513 }
4514}
4515
4516#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4519#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4520#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4521pub struct CreateExtension {
4522 pub name: Ident,
4524 pub if_not_exists: bool,
4526 pub cascade: bool,
4528 pub schema: Option<Ident>,
4530 pub version: Option<Ident>,
4532}
4533
4534impl fmt::Display for CreateExtension {
4535 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4536 write!(
4537 f,
4538 "CREATE EXTENSION {if_not_exists}{name}",
4539 if_not_exists = if self.if_not_exists {
4540 "IF NOT EXISTS "
4541 } else {
4542 ""
4543 },
4544 name = self.name
4545 )?;
4546 if self.cascade || self.schema.is_some() || self.version.is_some() {
4547 write!(f, " WITH")?;
4548
4549 if let Some(name) = &self.schema {
4550 write!(f, " SCHEMA {name}")?;
4551 }
4552 if let Some(version) = &self.version {
4553 write!(f, " VERSION {version}")?;
4554 }
4555 if self.cascade {
4556 write!(f, " CASCADE")?;
4557 }
4558 }
4559
4560 Ok(())
4561 }
4562}
4563
4564impl Spanned for CreateExtension {
4565 fn span(&self) -> Span {
4566 Span::empty()
4567 }
4568}
4569
4570#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4578#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4579#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4580pub struct DropExtension {
4581 pub names: Vec<Ident>,
4583 pub if_exists: bool,
4585 pub cascade_or_restrict: Option<ReferentialAction>,
4587}
4588
4589impl fmt::Display for DropExtension {
4590 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4591 write!(f, "DROP EXTENSION")?;
4592 if self.if_exists {
4593 write!(f, " IF EXISTS")?;
4594 }
4595 write!(f, " {}", display_comma_separated(&self.names))?;
4596 if let Some(cascade_or_restrict) = &self.cascade_or_restrict {
4597 write!(f, " {cascade_or_restrict}")?;
4598 }
4599 Ok(())
4600 }
4601}
4602
4603impl Spanned for DropExtension {
4604 fn span(&self) -> Span {
4605 Span::empty()
4606 }
4607}
4608
4609#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4612#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4613#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4614pub struct CreateCollation {
4615 pub if_not_exists: bool,
4617 pub name: ObjectName,
4619 pub definition: CreateCollationDefinition,
4621}
4622
4623#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4625#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4626#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4627pub enum CreateCollationDefinition {
4628 From(ObjectName),
4634 Options(Vec<SqlOption>),
4640}
4641
4642impl fmt::Display for CreateCollation {
4643 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4644 write!(
4645 f,
4646 "CREATE COLLATION {if_not_exists}{name}",
4647 if_not_exists = if self.if_not_exists {
4648 "IF NOT EXISTS "
4649 } else {
4650 ""
4651 },
4652 name = self.name
4653 )?;
4654 match &self.definition {
4655 CreateCollationDefinition::From(existing_collation) => {
4656 write!(f, " FROM {existing_collation}")
4657 }
4658 CreateCollationDefinition::Options(options) => {
4659 write!(f, " ({})", display_comma_separated(options))
4660 }
4661 }
4662 }
4663}
4664
4665impl Spanned for CreateCollation {
4666 fn span(&self) -> Span {
4667 Span::empty()
4668 }
4669}
4670
4671#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4674#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4675#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4676pub struct AlterCollation {
4677 pub name: ObjectName,
4679 pub operation: AlterCollationOperation,
4681}
4682
4683#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4685#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4686#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4687pub enum AlterCollationOperation {
4688 RenameTo {
4694 new_name: Ident,
4696 },
4697 OwnerTo(Owner),
4703 SetSchema {
4709 schema_name: ObjectName,
4711 },
4712 RefreshVersion,
4718}
4719
4720impl fmt::Display for AlterCollationOperation {
4721 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4722 match self {
4723 AlterCollationOperation::RenameTo { new_name } => write!(f, "RENAME TO {new_name}"),
4724 AlterCollationOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
4725 AlterCollationOperation::SetSchema { schema_name } => {
4726 write!(f, "SET SCHEMA {schema_name}")
4727 }
4728 AlterCollationOperation::RefreshVersion => write!(f, "REFRESH VERSION"),
4729 }
4730 }
4731}
4732
4733impl fmt::Display for AlterCollation {
4734 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4735 write!(f, "ALTER COLLATION {} {}", self.name, self.operation)
4736 }
4737}
4738
4739impl Spanned for AlterCollation {
4740 fn span(&self) -> Span {
4741 Span::empty()
4742 }
4743}
4744
4745#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4748#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4749#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4750pub enum AlterTableType {
4751 Iceberg,
4754 Dynamic,
4757 External,
4760}
4761
4762#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4764#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4765#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4766pub struct AlterTable {
4767 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4769 pub name: ObjectName,
4770 pub r#async: bool,
4776 pub if_exists: bool,
4778 pub only: bool,
4780 pub operations: Vec<AlterTableOperation>,
4782 pub location: Option<HiveSetLocation>,
4784 pub on_cluster: Option<Ident>,
4788 pub table_type: Option<AlterTableType>,
4790 pub end_token: AttachedToken,
4792}
4793
4794impl fmt::Display for AlterTable {
4795 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4796 match &self.table_type {
4797 Some(AlterTableType::Iceberg) => write!(f, "ALTER ICEBERG TABLE ")?,
4798 Some(AlterTableType::Dynamic) => write!(f, "ALTER DYNAMIC TABLE ")?,
4799 Some(AlterTableType::External) => write!(f, "ALTER EXTERNAL TABLE ")?,
4800 None => write!(f, "ALTER TABLE ")?,
4801 }
4802
4803 if self.r#async {
4804 write!(f, "ASYNC ")?;
4805 }
4806 if self.if_exists {
4807 write!(f, "IF EXISTS ")?;
4808 }
4809 if self.only {
4810 write!(f, "ONLY ")?;
4811 }
4812 write!(f, "{} ", self.name)?;
4813 if let Some(cluster) = &self.on_cluster {
4814 write!(f, "ON CLUSTER {cluster} ")?;
4815 }
4816 write!(f, "{}", display_comma_separated(&self.operations))?;
4817 if let Some(loc) = &self.location {
4818 write!(f, " {loc}")?
4819 }
4820 Ok(())
4821 }
4822}
4823
4824#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4826#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4827#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4828pub struct DropFunction {
4829 pub if_exists: bool,
4831 pub func_desc: Vec<FunctionDesc>,
4833 pub drop_behavior: Option<DropBehavior>,
4835}
4836
4837impl fmt::Display for DropFunction {
4838 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4839 write!(
4840 f,
4841 "DROP FUNCTION{} {}",
4842 if self.if_exists { " IF EXISTS" } else { "" },
4843 display_comma_separated(&self.func_desc),
4844 )?;
4845 if let Some(op) = &self.drop_behavior {
4846 write!(f, " {op}")?;
4847 }
4848 Ok(())
4849 }
4850}
4851
4852impl Spanned for DropFunction {
4853 fn span(&self) -> Span {
4854 Span::empty()
4855 }
4856}
4857
4858#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4861#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4862#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4863pub struct CreateOperator {
4864 pub name: ObjectName,
4866 pub function: ObjectName,
4868 pub is_procedure: bool,
4870 pub left_arg: Option<DataType>,
4872 pub right_arg: Option<DataType>,
4874 pub options: Vec<OperatorOption>,
4876}
4877
4878#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4881#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4882#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4883pub struct CreateOperatorFamily {
4884 pub name: ObjectName,
4886 pub using: Ident,
4888}
4889
4890#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4893#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4894#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4895pub struct CreateOperatorClass {
4896 pub name: ObjectName,
4898 pub default: bool,
4900 pub for_type: DataType,
4902 pub using: Ident,
4904 pub family: Option<ObjectName>,
4906 pub items: Vec<OperatorClassItem>,
4908}
4909
4910impl fmt::Display for CreateOperator {
4911 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4912 write!(f, "CREATE OPERATOR {} (", self.name)?;
4913
4914 let function_keyword = if self.is_procedure {
4915 "PROCEDURE"
4916 } else {
4917 "FUNCTION"
4918 };
4919 let mut params = vec![format!("{} = {}", function_keyword, self.function)];
4920
4921 if let Some(left_arg) = &self.left_arg {
4922 params.push(format!("LEFTARG = {}", left_arg));
4923 }
4924 if let Some(right_arg) = &self.right_arg {
4925 params.push(format!("RIGHTARG = {}", right_arg));
4926 }
4927
4928 for option in &self.options {
4929 params.push(option.to_string());
4930 }
4931
4932 write!(f, "{}", params.join(", "))?;
4933 write!(f, ")")
4934 }
4935}
4936
4937impl fmt::Display for CreateOperatorFamily {
4938 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4939 write!(
4940 f,
4941 "CREATE OPERATOR FAMILY {} USING {}",
4942 self.name, self.using
4943 )
4944 }
4945}
4946
4947impl fmt::Display for CreateOperatorClass {
4948 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4949 write!(f, "CREATE OPERATOR CLASS {}", self.name)?;
4950 if self.default {
4951 write!(f, " DEFAULT")?;
4952 }
4953 write!(f, " FOR TYPE {} USING {}", self.for_type, self.using)?;
4954 if let Some(family) = &self.family {
4955 write!(f, " FAMILY {}", family)?;
4956 }
4957 write!(f, " AS {}", display_comma_separated(&self.items))
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 struct OperatorArgTypes {
4966 pub left: DataType,
4968 pub right: DataType,
4970}
4971
4972impl fmt::Display for OperatorArgTypes {
4973 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4974 write!(f, "{}, {}", self.left, self.right)
4975 }
4976}
4977
4978#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4980#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4981#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4982pub enum OperatorClassItem {
4983 Operator {
4985 strategy_number: u64,
4987 operator_name: ObjectName,
4989 op_types: Option<OperatorArgTypes>,
4991 purpose: Option<OperatorPurpose>,
4993 },
4994 Function {
4996 support_number: u64,
4998 op_types: Option<Vec<DataType>>,
5000 function_name: ObjectName,
5002 argument_types: Vec<DataType>,
5004 },
5005 Storage {
5007 storage_type: DataType,
5009 },
5010}
5011
5012#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5014#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5015#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5016pub enum OperatorPurpose {
5017 ForSearch,
5019 ForOrderBy {
5021 sort_family: ObjectName,
5023 },
5024}
5025
5026impl fmt::Display for OperatorClassItem {
5027 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5028 match self {
5029 OperatorClassItem::Operator {
5030 strategy_number,
5031 operator_name,
5032 op_types,
5033 purpose,
5034 } => {
5035 write!(f, "OPERATOR {strategy_number} {operator_name}")?;
5036 if let Some(types) = op_types {
5037 write!(f, " ({types})")?;
5038 }
5039 if let Some(purpose) = purpose {
5040 write!(f, " {purpose}")?;
5041 }
5042 Ok(())
5043 }
5044 OperatorClassItem::Function {
5045 support_number,
5046 op_types,
5047 function_name,
5048 argument_types,
5049 } => {
5050 write!(f, "FUNCTION {support_number}")?;
5051 if let Some(types) = op_types {
5052 write!(f, " ({})", display_comma_separated(types))?;
5053 }
5054 write!(f, " {function_name}")?;
5055 if !argument_types.is_empty() {
5056 write!(f, "({})", display_comma_separated(argument_types))?;
5057 }
5058 Ok(())
5059 }
5060 OperatorClassItem::Storage { storage_type } => {
5061 write!(f, "STORAGE {storage_type}")
5062 }
5063 }
5064 }
5065}
5066
5067impl fmt::Display for OperatorPurpose {
5068 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5069 match self {
5070 OperatorPurpose::ForSearch => write!(f, "FOR SEARCH"),
5071 OperatorPurpose::ForOrderBy { sort_family } => {
5072 write!(f, "FOR ORDER BY {sort_family}")
5073 }
5074 }
5075 }
5076}
5077
5078#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5081#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5082#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5083pub struct DropOperator {
5084 pub if_exists: bool,
5086 pub operators: Vec<DropOperatorSignature>,
5088 pub drop_behavior: Option<DropBehavior>,
5090}
5091
5092#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5094#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5095#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5096pub struct DropOperatorSignature {
5097 pub name: ObjectName,
5099 pub left_type: Option<DataType>,
5101 pub right_type: DataType,
5103}
5104
5105impl fmt::Display for DropOperatorSignature {
5106 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5107 write!(f, "{} (", self.name)?;
5108 if let Some(left_type) = &self.left_type {
5109 write!(f, "{}", left_type)?;
5110 } else {
5111 write!(f, "NONE")?;
5112 }
5113 write!(f, ", {})", self.right_type)
5114 }
5115}
5116
5117impl fmt::Display for DropOperator {
5118 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5119 write!(f, "DROP OPERATOR")?;
5120 if self.if_exists {
5121 write!(f, " IF EXISTS")?;
5122 }
5123 write!(f, " {}", display_comma_separated(&self.operators))?;
5124 if let Some(drop_behavior) = &self.drop_behavior {
5125 write!(f, " {}", drop_behavior)?;
5126 }
5127 Ok(())
5128 }
5129}
5130
5131impl Spanned for DropOperator {
5132 fn span(&self) -> Span {
5133 Span::empty()
5134 }
5135}
5136
5137#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5140#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5141#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5142pub struct DropOperatorFamily {
5143 pub if_exists: bool,
5145 pub names: Vec<ObjectName>,
5147 pub using: Ident,
5149 pub drop_behavior: Option<DropBehavior>,
5151}
5152
5153impl fmt::Display for DropOperatorFamily {
5154 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5155 write!(f, "DROP OPERATOR FAMILY")?;
5156 if self.if_exists {
5157 write!(f, " IF EXISTS")?;
5158 }
5159 write!(f, " {}", display_comma_separated(&self.names))?;
5160 write!(f, " USING {}", self.using)?;
5161 if let Some(drop_behavior) = &self.drop_behavior {
5162 write!(f, " {}", drop_behavior)?;
5163 }
5164 Ok(())
5165 }
5166}
5167
5168impl Spanned for DropOperatorFamily {
5169 fn span(&self) -> Span {
5170 Span::empty()
5171 }
5172}
5173
5174#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5177#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5178#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5179pub struct DropOperatorClass {
5180 pub if_exists: bool,
5182 pub names: Vec<ObjectName>,
5184 pub using: Ident,
5186 pub drop_behavior: Option<DropBehavior>,
5188}
5189
5190impl fmt::Display for DropOperatorClass {
5191 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5192 write!(f, "DROP OPERATOR CLASS")?;
5193 if self.if_exists {
5194 write!(f, " IF EXISTS")?;
5195 }
5196 write!(f, " {}", display_comma_separated(&self.names))?;
5197 write!(f, " USING {}", self.using)?;
5198 if let Some(drop_behavior) = &self.drop_behavior {
5199 write!(f, " {}", drop_behavior)?;
5200 }
5201 Ok(())
5202 }
5203}
5204
5205impl Spanned for DropOperatorClass {
5206 fn span(&self) -> Span {
5207 Span::empty()
5208 }
5209}
5210
5211#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5213#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5214#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5215pub enum OperatorFamilyItem {
5216 Operator {
5218 strategy_number: u64,
5220 operator_name: ObjectName,
5222 op_types: Vec<DataType>,
5224 purpose: Option<OperatorPurpose>,
5226 },
5227 Function {
5229 support_number: u64,
5231 op_types: Option<Vec<DataType>>,
5233 function_name: ObjectName,
5235 argument_types: Vec<DataType>,
5237 },
5238}
5239
5240#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5242#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5243#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5244pub enum OperatorFamilyDropItem {
5245 Operator {
5247 strategy_number: u64,
5249 op_types: Vec<DataType>,
5251 },
5252 Function {
5254 support_number: u64,
5256 op_types: Vec<DataType>,
5258 },
5259}
5260
5261impl fmt::Display for OperatorFamilyItem {
5262 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5263 match self {
5264 OperatorFamilyItem::Operator {
5265 strategy_number,
5266 operator_name,
5267 op_types,
5268 purpose,
5269 } => {
5270 write!(
5271 f,
5272 "OPERATOR {strategy_number} {operator_name} ({})",
5273 display_comma_separated(op_types)
5274 )?;
5275 if let Some(purpose) = purpose {
5276 write!(f, " {purpose}")?;
5277 }
5278 Ok(())
5279 }
5280 OperatorFamilyItem::Function {
5281 support_number,
5282 op_types,
5283 function_name,
5284 argument_types,
5285 } => {
5286 write!(f, "FUNCTION {support_number}")?;
5287 if let Some(types) = op_types {
5288 write!(f, " ({})", display_comma_separated(types))?;
5289 }
5290 write!(f, " {function_name}")?;
5291 if !argument_types.is_empty() {
5292 write!(f, "({})", display_comma_separated(argument_types))?;
5293 }
5294 Ok(())
5295 }
5296 }
5297 }
5298}
5299
5300impl fmt::Display for OperatorFamilyDropItem {
5301 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5302 match self {
5303 OperatorFamilyDropItem::Operator {
5304 strategy_number,
5305 op_types,
5306 } => {
5307 write!(
5308 f,
5309 "OPERATOR {strategy_number} ({})",
5310 display_comma_separated(op_types)
5311 )
5312 }
5313 OperatorFamilyDropItem::Function {
5314 support_number,
5315 op_types,
5316 } => {
5317 write!(
5318 f,
5319 "FUNCTION {support_number} ({})",
5320 display_comma_separated(op_types)
5321 )
5322 }
5323 }
5324 }
5325}
5326
5327#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5330#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5331#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5332pub struct AlterOperatorFamily {
5333 pub name: ObjectName,
5335 pub using: Ident,
5337 pub operation: AlterOperatorFamilyOperation,
5339}
5340
5341#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5343#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5344#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5345pub enum AlterOperatorFamilyOperation {
5346 Add {
5348 items: Vec<OperatorFamilyItem>,
5350 },
5351 Drop {
5353 items: Vec<OperatorFamilyDropItem>,
5355 },
5356 RenameTo {
5358 new_name: ObjectName,
5360 },
5361 OwnerTo(Owner),
5363 SetSchema {
5365 schema_name: ObjectName,
5367 },
5368}
5369
5370impl fmt::Display for AlterOperatorFamily {
5371 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5372 write!(
5373 f,
5374 "ALTER OPERATOR FAMILY {} USING {}",
5375 self.name, self.using
5376 )?;
5377 write!(f, " {}", self.operation)
5378 }
5379}
5380
5381impl fmt::Display for AlterOperatorFamilyOperation {
5382 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5383 match self {
5384 AlterOperatorFamilyOperation::Add { items } => {
5385 write!(f, "ADD {}", display_comma_separated(items))
5386 }
5387 AlterOperatorFamilyOperation::Drop { items } => {
5388 write!(f, "DROP {}", display_comma_separated(items))
5389 }
5390 AlterOperatorFamilyOperation::RenameTo { new_name } => {
5391 write!(f, "RENAME TO {new_name}")
5392 }
5393 AlterOperatorFamilyOperation::OwnerTo(owner) => {
5394 write!(f, "OWNER TO {owner}")
5395 }
5396 AlterOperatorFamilyOperation::SetSchema { schema_name } => {
5397 write!(f, "SET SCHEMA {schema_name}")
5398 }
5399 }
5400 }
5401}
5402
5403impl Spanned for AlterOperatorFamily {
5404 fn span(&self) -> Span {
5405 Span::empty()
5406 }
5407}
5408
5409#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5412#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5413#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5414pub struct AlterOperatorClass {
5415 pub name: ObjectName,
5417 pub using: Ident,
5419 pub operation: AlterOperatorClassOperation,
5421}
5422
5423#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5425#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5426#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5427pub enum AlterOperatorClassOperation {
5428 RenameTo {
5431 new_name: ObjectName,
5433 },
5434 OwnerTo(Owner),
5436 SetSchema {
5439 schema_name: ObjectName,
5441 },
5442}
5443
5444impl fmt::Display for AlterOperatorClass {
5445 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5446 write!(f, "ALTER OPERATOR CLASS {} USING {}", self.name, self.using)?;
5447 write!(f, " {}", self.operation)
5448 }
5449}
5450
5451impl fmt::Display for AlterOperatorClassOperation {
5452 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5453 match self {
5454 AlterOperatorClassOperation::RenameTo { new_name } => {
5455 write!(f, "RENAME TO {new_name}")
5456 }
5457 AlterOperatorClassOperation::OwnerTo(owner) => {
5458 write!(f, "OWNER TO {owner}")
5459 }
5460 AlterOperatorClassOperation::SetSchema { schema_name } => {
5461 write!(f, "SET SCHEMA {schema_name}")
5462 }
5463 }
5464 }
5465}
5466
5467impl Spanned for AlterOperatorClass {
5468 fn span(&self) -> Span {
5469 Span::empty()
5470 }
5471}
5472
5473#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5475#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5476#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5477pub struct AlterFunction {
5478 pub kind: AlterFunctionKind,
5480 pub function: FunctionDesc,
5482 pub aggregate_order_by: Option<Vec<OperateFunctionArg>>,
5486 pub aggregate_star: bool,
5490 pub operation: AlterFunctionOperation,
5492}
5493
5494#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5496#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5497#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5498pub enum AlterFunctionKind {
5499 Function,
5501 Aggregate,
5503}
5504
5505impl fmt::Display for AlterFunctionKind {
5506 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5507 match self {
5508 Self::Function => write!(f, "FUNCTION"),
5509 Self::Aggregate => write!(f, "AGGREGATE"),
5510 }
5511 }
5512}
5513
5514#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5516#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5517#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5518pub enum AlterFunctionOperation {
5519 RenameTo {
5521 new_name: Ident,
5523 },
5524 OwnerTo(Owner),
5526 SetSchema {
5528 schema_name: ObjectName,
5530 },
5531 DependsOnExtension {
5533 no: bool,
5535 extension_name: ObjectName,
5537 },
5538 Actions {
5540 actions: Vec<AlterFunctionAction>,
5542 restrict: bool,
5544 },
5545}
5546
5547#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5549#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5550#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5551pub enum AlterFunctionAction {
5552 CalledOnNull(FunctionCalledOnNull),
5554 Behavior(FunctionBehavior),
5556 Leakproof(bool),
5558 Security {
5560 external: bool,
5562 security: FunctionSecurity,
5564 },
5565 Parallel(FunctionParallel),
5567 Cost(Expr),
5569 Rows(Expr),
5571 Support(ObjectName),
5573 Set(FunctionDefinitionSetParam),
5576 Reset(ResetConfig),
5578}
5579
5580impl fmt::Display for AlterFunction {
5581 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5582 write!(f, "ALTER {} ", self.kind)?;
5583 match self.kind {
5584 AlterFunctionKind::Function => {
5585 write!(f, "{} ", self.function)?;
5586 }
5587 AlterFunctionKind::Aggregate => {
5588 write!(f, "{}(", self.function.name)?;
5589 if self.aggregate_star {
5590 write!(f, "*")?;
5591 } else {
5592 if let Some(args) = &self.function.args {
5593 write!(f, "{}", display_comma_separated(args))?;
5594 }
5595 if let Some(order_by_args) = &self.aggregate_order_by {
5596 if self
5597 .function
5598 .args
5599 .as_ref()
5600 .is_some_and(|args| !args.is_empty())
5601 {
5602 write!(f, " ")?;
5603 }
5604 write!(f, "ORDER BY {}", display_comma_separated(order_by_args))?;
5605 }
5606 }
5607 write!(f, ") ")?;
5608 }
5609 }
5610 write!(f, "{}", self.operation)
5611 }
5612}
5613
5614impl fmt::Display for AlterFunctionOperation {
5615 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5616 match self {
5617 AlterFunctionOperation::RenameTo { new_name } => {
5618 write!(f, "RENAME TO {new_name}")
5619 }
5620 AlterFunctionOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
5621 AlterFunctionOperation::SetSchema { schema_name } => {
5622 write!(f, "SET SCHEMA {schema_name}")
5623 }
5624 AlterFunctionOperation::DependsOnExtension { no, extension_name } => {
5625 if *no {
5626 write!(f, "NO DEPENDS ON EXTENSION {extension_name}")
5627 } else {
5628 write!(f, "DEPENDS ON EXTENSION {extension_name}")
5629 }
5630 }
5631 AlterFunctionOperation::Actions { actions, restrict } => {
5632 write!(f, "{}", display_separated(actions, " "))?;
5633 if *restrict {
5634 write!(f, " RESTRICT")?;
5635 }
5636 Ok(())
5637 }
5638 }
5639 }
5640}
5641
5642impl fmt::Display for AlterFunctionAction {
5643 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5644 match self {
5645 AlterFunctionAction::CalledOnNull(called_on_null) => write!(f, "{called_on_null}"),
5646 AlterFunctionAction::Behavior(behavior) => write!(f, "{behavior}"),
5647 AlterFunctionAction::Leakproof(leakproof) => {
5648 if *leakproof {
5649 write!(f, "LEAKPROOF")
5650 } else {
5651 write!(f, "NOT LEAKPROOF")
5652 }
5653 }
5654 AlterFunctionAction::Security { external, security } => {
5655 if *external {
5656 write!(f, "EXTERNAL ")?;
5657 }
5658 write!(f, "{security}")
5659 }
5660 AlterFunctionAction::Parallel(parallel) => write!(f, "{parallel}"),
5661 AlterFunctionAction::Cost(execution_cost) => write!(f, "COST {execution_cost}"),
5662 AlterFunctionAction::Rows(result_rows) => write!(f, "ROWS {result_rows}"),
5663 AlterFunctionAction::Support(support_function) => {
5664 write!(f, "SUPPORT {support_function}")
5665 }
5666 AlterFunctionAction::Set(set_param) => write!(f, "{set_param}"),
5667 AlterFunctionAction::Reset(reset_config) => match reset_config {
5668 ResetConfig::ALL => write!(f, "RESET ALL"),
5669 ResetConfig::ConfigName(name) => write!(f, "RESET {name}"),
5670 },
5671 }
5672 }
5673}
5674
5675impl Spanned for AlterFunction {
5676 fn span(&self) -> Span {
5677 Span::empty()
5678 }
5679}
5680
5681#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5685#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5686#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5687pub struct CreatePolicy {
5688 pub name: Ident,
5690 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5692 pub table_name: ObjectName,
5693 pub policy_type: Option<CreatePolicyType>,
5695 pub command: Option<CreatePolicyCommand>,
5697 pub to: Option<Vec<Owner>>,
5699 pub using: Option<Expr>,
5701 pub with_check: Option<Expr>,
5703}
5704
5705impl fmt::Display for CreatePolicy {
5706 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5707 write!(
5708 f,
5709 "CREATE POLICY {name} ON {table_name}",
5710 name = self.name,
5711 table_name = self.table_name,
5712 )?;
5713 if let Some(ref policy_type) = self.policy_type {
5714 write!(f, " AS {policy_type}")?;
5715 }
5716 if let Some(ref command) = self.command {
5717 write!(f, " FOR {command}")?;
5718 }
5719 if let Some(ref to) = self.to {
5720 write!(f, " TO {}", display_comma_separated(to))?;
5721 }
5722 if let Some(ref using) = self.using {
5723 write!(f, " USING ({using})")?;
5724 }
5725 if let Some(ref with_check) = self.with_check {
5726 write!(f, " WITH CHECK ({with_check})")?;
5727 }
5728 Ok(())
5729 }
5730}
5731
5732#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5738#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5739#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5740pub enum CreatePolicyType {
5741 Permissive,
5743 Restrictive,
5745}
5746
5747impl fmt::Display for CreatePolicyType {
5748 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5749 match self {
5750 CreatePolicyType::Permissive => write!(f, "PERMISSIVE"),
5751 CreatePolicyType::Restrictive => write!(f, "RESTRICTIVE"),
5752 }
5753 }
5754}
5755
5756#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5762#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5763#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5764pub enum CreatePolicyCommand {
5765 All,
5767 Select,
5769 Insert,
5771 Update,
5773 Delete,
5775}
5776
5777impl fmt::Display for CreatePolicyCommand {
5778 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5779 match self {
5780 CreatePolicyCommand::All => write!(f, "ALL"),
5781 CreatePolicyCommand::Select => write!(f, "SELECT"),
5782 CreatePolicyCommand::Insert => write!(f, "INSERT"),
5783 CreatePolicyCommand::Update => write!(f, "UPDATE"),
5784 CreatePolicyCommand::Delete => write!(f, "DELETE"),
5785 }
5786 }
5787}
5788
5789#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5793#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5794#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5795pub struct DropPolicy {
5796 pub if_exists: bool,
5798 pub name: Ident,
5800 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5802 pub table_name: ObjectName,
5803 pub drop_behavior: Option<DropBehavior>,
5805}
5806
5807impl fmt::Display for DropPolicy {
5808 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5809 write!(
5810 f,
5811 "DROP POLICY {if_exists}{name} ON {table_name}",
5812 if_exists = if self.if_exists { "IF EXISTS " } else { "" },
5813 name = self.name,
5814 table_name = self.table_name
5815 )?;
5816 if let Some(ref behavior) = self.drop_behavior {
5817 write!(f, " {behavior}")?;
5818 }
5819 Ok(())
5820 }
5821}
5822
5823impl From<CreatePolicy> for crate::ast::Statement {
5824 fn from(v: CreatePolicy) -> Self {
5825 crate::ast::Statement::CreatePolicy(v)
5826 }
5827}
5828
5829impl From<DropPolicy> for crate::ast::Statement {
5830 fn from(v: DropPolicy) -> Self {
5831 crate::ast::Statement::DropPolicy(v)
5832 }
5833}
5834
5835#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5842#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5843#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5844pub struct AlterPolicy {
5845 pub name: Ident,
5847 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5849 pub table_name: ObjectName,
5850 pub operation: AlterPolicyOperation,
5852}
5853
5854impl fmt::Display for AlterPolicy {
5855 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5856 write!(
5857 f,
5858 "ALTER POLICY {name} ON {table_name}{operation}",
5859 name = self.name,
5860 table_name = self.table_name,
5861 operation = self.operation
5862 )
5863 }
5864}
5865
5866impl From<AlterPolicy> for crate::ast::Statement {
5867 fn from(v: AlterPolicy) -> Self {
5868 crate::ast::Statement::AlterPolicy(v)
5869 }
5870}