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 Storage(AlterColumnStorage),
1940
1941 Materialized(Expr),
1946 Ephemeral(Option<Expr>),
1950 Alias(Expr),
1954
1955 PrimaryKey(PrimaryKeyConstraint),
1957 Unique(UniqueConstraint),
1959 ForeignKey(ForeignKeyConstraint),
1967 Check(CheckConstraint),
1969 DialectSpecific(Vec<Token>),
1973 CharacterSet(ObjectName),
1975 Collation(ObjectName),
1977 Comment(String),
1979 OnUpdate(Expr),
1981 Generated {
1984 generated_as: GeneratedAs,
1986 sequence_options: Option<Vec<SequenceOptions>>,
1988 generation_expr: Option<Expr>,
1990 generation_expr_mode: Option<GeneratedExpressionMode>,
1992 generated_keyword: bool,
1994 },
1995 Options(Vec<SqlOption>),
2003 Identity(IdentityPropertyKind),
2011 OnConflict(Keyword),
2014 Policy(ColumnPolicy),
2022 Tags(TagsColumnOption),
2029 Srid(Box<Expr>),
2036 Invisible,
2043}
2044
2045impl From<UniqueConstraint> for ColumnOption {
2046 fn from(c: UniqueConstraint) -> Self {
2047 ColumnOption::Unique(c)
2048 }
2049}
2050
2051impl From<PrimaryKeyConstraint> for ColumnOption {
2052 fn from(c: PrimaryKeyConstraint) -> Self {
2053 ColumnOption::PrimaryKey(c)
2054 }
2055}
2056
2057impl From<CheckConstraint> for ColumnOption {
2058 fn from(c: CheckConstraint) -> Self {
2059 ColumnOption::Check(c)
2060 }
2061}
2062impl From<ForeignKeyConstraint> for ColumnOption {
2063 fn from(fk: ForeignKeyConstraint) -> Self {
2064 ColumnOption::ForeignKey(fk)
2065 }
2066}
2067
2068impl fmt::Display for ColumnOption {
2069 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2070 use ColumnOption::*;
2071 match self {
2072 Null => write!(f, "NULL"),
2073 NotNull => write!(f, "NOT NULL"),
2074 Default(expr) => write!(f, "DEFAULT {expr}"),
2075 Storage(storage) => write!(f, "STORAGE {storage}"),
2076 Materialized(expr) => write!(f, "MATERIALIZED {expr}"),
2077 Ephemeral(expr) => {
2078 if let Some(e) = expr {
2079 write!(f, "EPHEMERAL {e}")
2080 } else {
2081 write!(f, "EPHEMERAL")
2082 }
2083 }
2084 Alias(expr) => write!(f, "ALIAS {expr}"),
2085 PrimaryKey(constraint) => {
2086 write!(f, "PRIMARY KEY")?;
2087 if let Some(characteristics) = &constraint.characteristics {
2088 write!(f, " {characteristics}")?;
2089 }
2090 Ok(())
2091 }
2092 Unique(constraint) => {
2093 write!(f, "UNIQUE{:>}", constraint.index_type_display)?;
2094 if let Some(characteristics) = &constraint.characteristics {
2095 write!(f, " {characteristics}")?;
2096 }
2097 Ok(())
2098 }
2099 ForeignKey(constraint) => {
2100 write!(f, "REFERENCES {}", constraint.foreign_table)?;
2101 if !constraint.referred_columns.is_empty() {
2102 write!(
2103 f,
2104 " ({})",
2105 display_comma_separated(&constraint.referred_columns)
2106 )?;
2107 }
2108 if let Some(match_kind) = &constraint.match_kind {
2109 write!(f, " {match_kind}")?;
2110 }
2111 if let Some(action) = &constraint.on_delete {
2112 write!(f, " ON DELETE {action}")?;
2113 }
2114 if let Some(action) = &constraint.on_update {
2115 write!(f, " ON UPDATE {action}")?;
2116 }
2117 if let Some(characteristics) = &constraint.characteristics {
2118 write!(f, " {characteristics}")?;
2119 }
2120 Ok(())
2121 }
2122 Check(constraint) => write!(f, "{constraint}"),
2123 DialectSpecific(val) => write!(f, "{}", display_separated(val, " ")),
2124 CharacterSet(n) => write!(f, "CHARACTER SET {n}"),
2125 Collation(n) => write!(f, "COLLATE {n}"),
2126 Comment(v) => write!(f, "COMMENT '{}'", escape_single_quote_string(v)),
2127 OnUpdate(expr) => write!(f, "ON UPDATE {expr}"),
2128 Generated {
2129 generated_as,
2130 sequence_options,
2131 generation_expr,
2132 generation_expr_mode,
2133 generated_keyword,
2134 } => {
2135 if let Some(expr) = generation_expr {
2136 let modifier = match generation_expr_mode {
2137 None => "",
2138 Some(GeneratedExpressionMode::Virtual) => " VIRTUAL",
2139 Some(GeneratedExpressionMode::Stored) => " STORED",
2140 };
2141 if *generated_keyword {
2142 write!(f, "GENERATED ALWAYS AS ({expr}){modifier}")?;
2143 } else {
2144 write!(f, "AS ({expr}){modifier}")?;
2145 }
2146 Ok(())
2147 } else {
2148 let when = match generated_as {
2150 GeneratedAs::Always => "ALWAYS",
2151 GeneratedAs::ByDefault => "BY DEFAULT",
2152 GeneratedAs::ExpStored => "",
2154 };
2155 write!(f, "GENERATED {when} AS IDENTITY")?;
2156 if let Some(so) = sequence_options {
2157 if !so.is_empty() {
2158 write!(f, " (")?;
2159 }
2160 for sequence_option in so {
2161 write!(f, "{sequence_option}")?;
2162 }
2163 if !so.is_empty() {
2164 write!(f, " )")?;
2165 }
2166 }
2167 Ok(())
2168 }
2169 }
2170 Options(options) => {
2171 write!(f, "OPTIONS({})", display_comma_separated(options))
2172 }
2173 Identity(parameters) => {
2174 write!(f, "{parameters}")
2175 }
2176 OnConflict(keyword) => {
2177 write!(f, "ON CONFLICT {keyword:?}")?;
2178 Ok(())
2179 }
2180 Policy(parameters) => {
2181 write!(f, "{parameters}")
2182 }
2183 Tags(tags) => {
2184 write!(f, "{tags}")
2185 }
2186 Srid(srid) => {
2187 write!(f, "SRID {srid}")
2188 }
2189 Invisible => {
2190 write!(f, "INVISIBLE")
2191 }
2192 }
2193 }
2194}
2195
2196#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2199#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2200#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2201pub enum GeneratedAs {
2202 Always,
2204 ByDefault,
2206 ExpStored,
2208}
2209
2210#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2213#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2214#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2215pub enum GeneratedExpressionMode {
2216 Virtual,
2218 Stored,
2220}
2221
2222#[must_use]
2223pub(crate) fn display_constraint_name(name: &'_ Option<Ident>) -> impl fmt::Display + '_ {
2224 struct ConstraintName<'a>(&'a Option<Ident>);
2225 impl fmt::Display for ConstraintName<'_> {
2226 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2227 if let Some(name) = self.0 {
2228 write!(f, "CONSTRAINT {name} ")?;
2229 }
2230 Ok(())
2231 }
2232 }
2233 ConstraintName(name)
2234}
2235
2236#[must_use]
2240pub(crate) fn display_option<'a, T: fmt::Display>(
2241 prefix: &'a str,
2242 postfix: &'a str,
2243 option: &'a Option<T>,
2244) -> impl fmt::Display + 'a {
2245 struct OptionDisplay<'a, T>(&'a str, &'a str, &'a Option<T>);
2246 impl<T: fmt::Display> fmt::Display for OptionDisplay<'_, T> {
2247 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2248 if let Some(inner) = self.2 {
2249 let (prefix, postfix) = (self.0, self.1);
2250 write!(f, "{prefix}{inner}{postfix}")?;
2251 }
2252 Ok(())
2253 }
2254 }
2255 OptionDisplay(prefix, postfix, option)
2256}
2257
2258#[must_use]
2262pub(crate) fn display_option_spaced<T: fmt::Display>(option: &Option<T>) -> impl fmt::Display + '_ {
2263 display_option(" ", "", option)
2264}
2265
2266#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Default, Eq, Ord, Hash)]
2270#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2271#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2272pub struct ConstraintCharacteristics {
2273 pub deferrable: Option<bool>,
2275 pub initially: Option<DeferrableInitial>,
2277 pub enforced: Option<bool>,
2279}
2280
2281#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2283#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2284#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2285pub enum DeferrableInitial {
2286 Immediate,
2288 Deferred,
2290}
2291
2292impl ConstraintCharacteristics {
2293 fn deferrable_text(&self) -> Option<&'static str> {
2294 self.deferrable.map(|deferrable| {
2295 if deferrable {
2296 "DEFERRABLE"
2297 } else {
2298 "NOT DEFERRABLE"
2299 }
2300 })
2301 }
2302
2303 fn initially_immediate_text(&self) -> Option<&'static str> {
2304 self.initially
2305 .map(|initially_immediate| match initially_immediate {
2306 DeferrableInitial::Immediate => "INITIALLY IMMEDIATE",
2307 DeferrableInitial::Deferred => "INITIALLY DEFERRED",
2308 })
2309 }
2310
2311 fn enforced_text(&self) -> Option<&'static str> {
2312 self.enforced.map(
2313 |enforced| {
2314 if enforced {
2315 "ENFORCED"
2316 } else {
2317 "NOT ENFORCED"
2318 }
2319 },
2320 )
2321 }
2322}
2323
2324impl fmt::Display for ConstraintCharacteristics {
2325 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2326 let deferrable = self.deferrable_text();
2327 let initially_immediate = self.initially_immediate_text();
2328 let enforced = self.enforced_text();
2329
2330 match (deferrable, initially_immediate, enforced) {
2331 (None, None, None) => Ok(()),
2332 (None, None, Some(enforced)) => write!(f, "{enforced}"),
2333 (None, Some(initial), None) => write!(f, "{initial}"),
2334 (None, Some(initial), Some(enforced)) => write!(f, "{initial} {enforced}"),
2335 (Some(deferrable), None, None) => write!(f, "{deferrable}"),
2336 (Some(deferrable), None, Some(enforced)) => write!(f, "{deferrable} {enforced}"),
2337 (Some(deferrable), Some(initial), None) => write!(f, "{deferrable} {initial}"),
2338 (Some(deferrable), Some(initial), Some(enforced)) => {
2339 write!(f, "{deferrable} {initial} {enforced}")
2340 }
2341 }
2342 }
2343}
2344
2345#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2350#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2351#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2352pub enum ReferentialAction {
2353 Restrict,
2355 Cascade,
2357 SetNull,
2359 NoAction,
2361 SetDefault,
2363}
2364
2365impl fmt::Display for ReferentialAction {
2366 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2367 f.write_str(match self {
2368 ReferentialAction::Restrict => "RESTRICT",
2369 ReferentialAction::Cascade => "CASCADE",
2370 ReferentialAction::SetNull => "SET NULL",
2371 ReferentialAction::NoAction => "NO ACTION",
2372 ReferentialAction::SetDefault => "SET DEFAULT",
2373 })
2374 }
2375}
2376
2377#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2381#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2382#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2383pub enum DropBehavior {
2384 Restrict,
2386 Cascade,
2388}
2389
2390impl fmt::Display for DropBehavior {
2391 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2392 f.write_str(match self {
2393 DropBehavior::Restrict => "RESTRICT",
2394 DropBehavior::Cascade => "CASCADE",
2395 })
2396 }
2397}
2398
2399#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2401#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2402#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2403pub enum UserDefinedTypeRepresentation {
2404 Composite {
2406 attributes: Vec<UserDefinedTypeCompositeAttributeDef>,
2408 },
2409 Enum {
2414 labels: Vec<Ident>,
2416 },
2417 Range {
2421 options: Vec<UserDefinedTypeRangeOption>,
2423 },
2424 SqlDefinition {
2430 options: Vec<UserDefinedTypeSqlDefinitionOption>,
2432 },
2433}
2434
2435impl fmt::Display for UserDefinedTypeRepresentation {
2436 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2437 match self {
2438 Self::Composite { attributes } => {
2439 write!(f, "AS ({})", display_comma_separated(attributes))
2440 }
2441 Self::Enum { labels } => {
2442 write!(f, "AS ENUM ({})", display_comma_separated(labels))
2443 }
2444 Self::Range { options } => {
2445 write!(f, "AS RANGE ({})", display_comma_separated(options))
2446 }
2447 Self::SqlDefinition { options } => {
2448 write!(f, "({})", display_comma_separated(options))
2449 }
2450 }
2451 }
2452}
2453
2454#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2456#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2457#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2458pub struct UserDefinedTypeCompositeAttributeDef {
2459 pub name: Ident,
2461 pub data_type: DataType,
2463 pub collation: Option<ObjectName>,
2465}
2466
2467impl fmt::Display for UserDefinedTypeCompositeAttributeDef {
2468 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2469 write!(f, "{} {}", self.name, self.data_type)?;
2470 if let Some(collation) = &self.collation {
2471 write!(f, " COLLATE {collation}")?;
2472 }
2473 Ok(())
2474 }
2475}
2476
2477#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2500#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2501#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2502pub enum UserDefinedTypeInternalLength {
2503 Fixed(u64),
2505 Variable,
2507}
2508
2509impl fmt::Display for UserDefinedTypeInternalLength {
2510 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2511 match self {
2512 UserDefinedTypeInternalLength::Fixed(n) => write!(f, "{}", n),
2513 UserDefinedTypeInternalLength::Variable => write!(f, "VARIABLE"),
2514 }
2515 }
2516}
2517
2518#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2537#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2538#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2539pub enum Alignment {
2540 Char,
2542 Int2,
2544 Int4,
2546 Double,
2548}
2549
2550impl fmt::Display for Alignment {
2551 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2552 match self {
2553 Alignment::Char => write!(f, "char"),
2554 Alignment::Int2 => write!(f, "int2"),
2555 Alignment::Int4 => write!(f, "int4"),
2556 Alignment::Double => write!(f, "double"),
2557 }
2558 }
2559}
2560
2561#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2581#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2582#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2583pub enum UserDefinedTypeStorage {
2584 Plain,
2586 External,
2588 Extended,
2590 Main,
2592}
2593
2594impl fmt::Display for UserDefinedTypeStorage {
2595 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2596 match self {
2597 UserDefinedTypeStorage::Plain => write!(f, "plain"),
2598 UserDefinedTypeStorage::External => write!(f, "external"),
2599 UserDefinedTypeStorage::Extended => write!(f, "extended"),
2600 UserDefinedTypeStorage::Main => write!(f, "main"),
2601 }
2602 }
2603}
2604
2605#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2623#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2624#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2625pub enum UserDefinedTypeRangeOption {
2626 Subtype(DataType),
2628 SubtypeOpClass(ObjectName),
2630 Collation(ObjectName),
2632 Canonical(ObjectName),
2634 SubtypeDiff(ObjectName),
2636 MultirangeTypeName(ObjectName),
2638}
2639
2640impl fmt::Display for UserDefinedTypeRangeOption {
2641 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2642 match self {
2643 UserDefinedTypeRangeOption::Subtype(dt) => write!(f, "SUBTYPE = {}", dt),
2644 UserDefinedTypeRangeOption::SubtypeOpClass(name) => {
2645 write!(f, "SUBTYPE_OPCLASS = {}", name)
2646 }
2647 UserDefinedTypeRangeOption::Collation(name) => write!(f, "COLLATION = {}", name),
2648 UserDefinedTypeRangeOption::Canonical(name) => write!(f, "CANONICAL = {}", name),
2649 UserDefinedTypeRangeOption::SubtypeDiff(name) => write!(f, "SUBTYPE_DIFF = {}", name),
2650 UserDefinedTypeRangeOption::MultirangeTypeName(name) => {
2651 write!(f, "MULTIRANGE_TYPE_NAME = {}", name)
2652 }
2653 }
2654 }
2655}
2656
2657#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2678#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2679#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2680pub enum UserDefinedTypeSqlDefinitionOption {
2681 Input(ObjectName),
2683 Output(ObjectName),
2685 Receive(ObjectName),
2687 Send(ObjectName),
2689 TypmodIn(ObjectName),
2691 TypmodOut(ObjectName),
2693 Analyze(ObjectName),
2695 Subscript(ObjectName),
2697 InternalLength(UserDefinedTypeInternalLength),
2699 PassedByValue,
2701 Alignment(Alignment),
2703 Storage(UserDefinedTypeStorage),
2705 Like(ObjectName),
2707 Category(char),
2709 Preferred(bool),
2711 Default(Expr),
2713 Element(DataType),
2715 Delimiter(String),
2717 Collatable(bool),
2719}
2720
2721impl fmt::Display for UserDefinedTypeSqlDefinitionOption {
2722 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2723 match self {
2724 UserDefinedTypeSqlDefinitionOption::Input(name) => write!(f, "INPUT = {}", name),
2725 UserDefinedTypeSqlDefinitionOption::Output(name) => write!(f, "OUTPUT = {}", name),
2726 UserDefinedTypeSqlDefinitionOption::Receive(name) => write!(f, "RECEIVE = {}", name),
2727 UserDefinedTypeSqlDefinitionOption::Send(name) => write!(f, "SEND = {}", name),
2728 UserDefinedTypeSqlDefinitionOption::TypmodIn(name) => write!(f, "TYPMOD_IN = {}", name),
2729 UserDefinedTypeSqlDefinitionOption::TypmodOut(name) => {
2730 write!(f, "TYPMOD_OUT = {}", name)
2731 }
2732 UserDefinedTypeSqlDefinitionOption::Analyze(name) => write!(f, "ANALYZE = {}", name),
2733 UserDefinedTypeSqlDefinitionOption::Subscript(name) => {
2734 write!(f, "SUBSCRIPT = {}", name)
2735 }
2736 UserDefinedTypeSqlDefinitionOption::InternalLength(len) => {
2737 write!(f, "INTERNALLENGTH = {}", len)
2738 }
2739 UserDefinedTypeSqlDefinitionOption::PassedByValue => write!(f, "PASSEDBYVALUE"),
2740 UserDefinedTypeSqlDefinitionOption::Alignment(align) => {
2741 write!(f, "ALIGNMENT = {}", align)
2742 }
2743 UserDefinedTypeSqlDefinitionOption::Storage(storage) => {
2744 write!(f, "STORAGE = {}", storage)
2745 }
2746 UserDefinedTypeSqlDefinitionOption::Like(name) => write!(f, "LIKE = {}", name),
2747 UserDefinedTypeSqlDefinitionOption::Category(c) => write!(f, "CATEGORY = '{}'", c),
2748 UserDefinedTypeSqlDefinitionOption::Preferred(b) => write!(f, "PREFERRED = {}", b),
2749 UserDefinedTypeSqlDefinitionOption::Default(expr) => write!(f, "DEFAULT = {}", expr),
2750 UserDefinedTypeSqlDefinitionOption::Element(dt) => write!(f, "ELEMENT = {}", dt),
2751 UserDefinedTypeSqlDefinitionOption::Delimiter(s) => {
2752 write!(f, "DELIMITER = '{}'", escape_single_quote_string(s))
2753 }
2754 UserDefinedTypeSqlDefinitionOption::Collatable(b) => write!(f, "COLLATABLE = {}", b),
2755 }
2756 }
2757}
2758
2759#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2763#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2764#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2765pub enum Partition {
2766 Identifier(Ident),
2768 Expr(Expr),
2770 Part(Expr),
2773 Partitions(Vec<Expr>),
2775}
2776
2777impl fmt::Display for Partition {
2778 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2779 match self {
2780 Partition::Identifier(id) => write!(f, "PARTITION ID {id}"),
2781 Partition::Expr(expr) => write!(f, "PARTITION {expr}"),
2782 Partition::Part(expr) => write!(f, "PART {expr}"),
2783 Partition::Partitions(partitions) => {
2784 write!(f, "PARTITION ({})", display_comma_separated(partitions))
2785 }
2786 }
2787 }
2788}
2789
2790#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2793#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2794#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2795pub enum Deduplicate {
2796 All,
2798 ByExpression(Expr),
2800}
2801
2802impl fmt::Display for Deduplicate {
2803 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2804 match self {
2805 Deduplicate::All => write!(f, "DEDUPLICATE"),
2806 Deduplicate::ByExpression(expr) => write!(f, "DEDUPLICATE BY {expr}"),
2807 }
2808 }
2809}
2810
2811#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2816#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2817#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2818pub struct ClusteredBy {
2819 pub columns: Vec<Ident>,
2821 pub sorted_by: Option<Vec<OrderByExpr>>,
2823 pub num_buckets: Value,
2825}
2826
2827impl fmt::Display for ClusteredBy {
2828 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2829 write!(
2830 f,
2831 "CLUSTERED BY ({})",
2832 display_comma_separated(&self.columns)
2833 )?;
2834 if let Some(ref sorted_by) = self.sorted_by {
2835 write!(f, " SORTED BY ({})", display_comma_separated(sorted_by))?;
2836 }
2837 write!(f, " INTO {} BUCKETS", self.num_buckets)
2838 }
2839}
2840
2841#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2843#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2844#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2845pub struct CreateIndex {
2846 pub name: Option<ObjectName>,
2848 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2849 pub table_name: ObjectName,
2851 pub using: Option<IndexType>,
2854 pub columns: Vec<IndexColumn>,
2856 pub unique: bool,
2858 pub concurrently: bool,
2860 pub r#async: bool,
2864 pub if_not_exists: bool,
2866 pub include: Vec<Ident>,
2868 pub nulls_distinct: Option<bool>,
2870 pub with: Vec<Expr>,
2872 pub predicate: Option<Expr>,
2874 pub index_options: Vec<IndexOption>,
2876 pub alter_options: Vec<AlterTableOperation>,
2883}
2884
2885impl fmt::Display for CreateIndex {
2886 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2887 write!(
2888 f,
2889 "CREATE {unique}INDEX {concurrently}{async_}{if_not_exists}",
2890 unique = if self.unique { "UNIQUE " } else { "" },
2891 concurrently = if self.concurrently {
2892 "CONCURRENTLY "
2893 } else {
2894 ""
2895 },
2896 async_ = if self.r#async { "ASYNC " } else { "" },
2897 if_not_exists = if self.if_not_exists {
2898 "IF NOT EXISTS "
2899 } else {
2900 ""
2901 },
2902 )?;
2903 if let Some(value) = &self.name {
2904 write!(f, "{value} ")?;
2905 }
2906 write!(f, "ON {}", self.table_name)?;
2907 if let Some(value) = &self.using {
2908 write!(f, " USING {value} ")?;
2909 }
2910 write!(f, "({})", display_comma_separated(&self.columns))?;
2911 if !self.include.is_empty() {
2912 write!(f, " INCLUDE ({})", display_comma_separated(&self.include))?;
2913 }
2914 if let Some(value) = self.nulls_distinct {
2915 if value {
2916 write!(f, " NULLS DISTINCT")?;
2917 } else {
2918 write!(f, " NULLS NOT DISTINCT")?;
2919 }
2920 }
2921 if !self.with.is_empty() {
2922 write!(f, " WITH ({})", display_comma_separated(&self.with))?;
2923 }
2924 if let Some(predicate) = &self.predicate {
2925 write!(f, " WHERE {predicate}")?;
2926 }
2927 if !self.index_options.is_empty() {
2928 write!(f, " {}", display_separated(&self.index_options, " "))?;
2929 }
2930 if !self.alter_options.is_empty() {
2931 write!(f, " {}", display_separated(&self.alter_options, " "))?;
2932 }
2933 Ok(())
2934 }
2935}
2936
2937#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2939#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2940#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2941pub struct CreateTable {
2942 pub or_replace: bool,
2944 pub temporary: bool,
2946 pub external: bool,
2948 pub dynamic: bool,
2950 pub global: Option<bool>,
2952 pub if_not_exists: bool,
2954 pub transient: bool,
2956 pub volatile: bool,
2958 pub iceberg: bool,
2960 pub snapshot: bool,
2963 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2965 pub name: ObjectName,
2966 pub columns: Vec<ColumnDef>,
2968 pub constraints: Vec<TableConstraint>,
2970 pub hive_distribution: HiveDistributionStyle,
2972 pub hive_formats: Option<HiveFormat>,
2974 pub table_options: CreateTableOptions,
2976 pub file_format: Option<FileFormat>,
2978 pub location: Option<String>,
2980 pub query: Option<Box<Query>>,
2982 pub without_rowid: bool,
2984 pub like: Option<CreateTableLikeKind>,
2986 pub clone: Option<ObjectName>,
2988 pub version: Option<TableVersion>,
2990 pub comment: Option<CommentDef>,
2994 pub on_commit: Option<OnCommit>,
2997 pub on_cluster: Option<Ident>,
3000 pub primary_key: Option<Box<Expr>>,
3003 pub order_by: Option<OneOrManyWithParens<Expr>>,
3007 pub partition_by: Option<Box<Expr>>,
3010 pub cluster_by: Option<WrappedCollection<Vec<Expr>>>,
3015 pub clustered_by: Option<ClusteredBy>,
3018 pub inherits: Option<Vec<ObjectName>>,
3023 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3027 pub partition_of: Option<ObjectName>,
3028 pub for_values: Option<ForValues>,
3031 pub strict: bool,
3035 pub copy_grants: bool,
3038 pub enable_schema_evolution: Option<bool>,
3041 pub change_tracking: Option<bool>,
3044 pub data_retention_time_in_days: Option<u64>,
3047 pub max_data_extension_time_in_days: Option<u64>,
3050 pub default_ddl_collation: Option<String>,
3053 pub with_aggregation_policy: Option<ObjectName>,
3056 pub with_row_access_policy: Option<RowAccessPolicy>,
3059 pub with_storage_lifecycle_policy: Option<StorageLifecyclePolicy>,
3062 pub with_tags: Option<Vec<Tag>>,
3065 pub external_volume: Option<String>,
3068 pub with_connection: Option<ObjectName>,
3071 pub base_location: Option<String>,
3074 pub catalog: Option<String>,
3077 pub catalog_sync: Option<String>,
3080 pub storage_serialization_policy: Option<StorageSerializationPolicy>,
3083 pub target_lag: Option<String>,
3086 pub warehouse: Option<Ident>,
3089 pub refresh_mode: Option<RefreshModeKind>,
3092 pub initialize: Option<InitializeKind>,
3095 pub require_user: bool,
3098 pub diststyle: Option<DistStyle>,
3101 pub distkey: Option<Expr>,
3104 pub sortkey: Option<Vec<Expr>>,
3107 pub backup: Option<bool>,
3110 pub multiset: Option<bool>,
3115 pub fallback: Option<bool>,
3120 pub with_data: Option<WithData>,
3124}
3125
3126impl fmt::Display for CreateTable {
3127 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3128 write!(
3136 f,
3137 "CREATE {or_replace}{external}{global}{multiset}{temporary}{transient}{volatile}{dynamic}{iceberg}{snapshot}TABLE {if_not_exists}{name}",
3138 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3139 external = if self.external { "EXTERNAL " } else { "" },
3140 snapshot = if self.snapshot { "SNAPSHOT " } else { "" },
3141 global = self.global
3142 .map(|global| {
3143 if global {
3144 "GLOBAL "
3145 } else {
3146 "LOCAL "
3147 }
3148 })
3149 .unwrap_or(""),
3150 if_not_exists = if self.if_not_exists { "IF NOT EXISTS " } else { "" },
3151 multiset = self
3152 .multiset
3153 .map(|m| if m { "MULTISET " } else { "SET " })
3154 .unwrap_or(""),
3155 temporary = if self.temporary { "TEMPORARY " } else { "" },
3156 transient = if self.transient { "TRANSIENT " } else { "" },
3157 volatile = if self.volatile { "VOLATILE " } else { "" },
3158 iceberg = if self.iceberg { "ICEBERG " } else { "" },
3159 dynamic = if self.dynamic { "DYNAMIC " } else { "" },
3160 name = self.name,
3161 )?;
3162 if let Some(fallback) = self.fallback {
3163 write!(f, ", {}", if fallback { "FALLBACK" } else { "NO FALLBACK" })?;
3164 }
3165 if let Some(partition_of) = &self.partition_of {
3166 write!(f, " PARTITION OF {partition_of}")?;
3167 }
3168 if let Some(on_cluster) = &self.on_cluster {
3169 write!(f, " ON CLUSTER {on_cluster}")?;
3170 }
3171 if !self.columns.is_empty() || !self.constraints.is_empty() {
3172 f.write_str(" (")?;
3173 NewLine.fmt(f)?;
3174 Indent(DisplayCommaSeparated(&self.columns)).fmt(f)?;
3175 if !self.columns.is_empty() && !self.constraints.is_empty() {
3176 f.write_str(",")?;
3177 SpaceOrNewline.fmt(f)?;
3178 }
3179 Indent(DisplayCommaSeparated(&self.constraints)).fmt(f)?;
3180 NewLine.fmt(f)?;
3181 f.write_str(")")?;
3182 } else if self.query.is_none()
3183 && self.like.is_none()
3184 && self.clone.is_none()
3185 && self.partition_of.is_none()
3186 {
3187 f.write_str(" ()")?;
3189 } else if let Some(CreateTableLikeKind::Parenthesized(like_in_columns_list)) = &self.like {
3190 write!(f, " ({like_in_columns_list})")?;
3191 }
3192 if let Some(for_values) = &self.for_values {
3193 write!(f, " {for_values}")?;
3194 }
3195
3196 if let Some(comment) = &self.comment {
3199 write!(f, " COMMENT '{comment}'")?;
3200 }
3201
3202 if self.without_rowid {
3204 write!(f, " WITHOUT ROWID")?;
3205 }
3206
3207 if let Some(CreateTableLikeKind::Plain(like)) = &self.like {
3208 write!(f, " {like}")?;
3209 }
3210
3211 if let Some(c) = &self.clone {
3212 write!(f, " CLONE {c}")?;
3213 }
3214
3215 if let Some(version) = &self.version {
3216 write!(f, " {version}")?;
3217 }
3218
3219 match &self.hive_distribution {
3220 HiveDistributionStyle::PARTITIONED { columns } => {
3221 write!(f, " PARTITIONED BY ({})", display_comma_separated(columns))?;
3222 }
3223 HiveDistributionStyle::SKEWED {
3224 columns,
3225 on,
3226 stored_as_directories,
3227 } => {
3228 write!(
3229 f,
3230 " SKEWED BY ({})) ON ({})",
3231 display_comma_separated(columns),
3232 display_comma_separated(on)
3233 )?;
3234 if *stored_as_directories {
3235 write!(f, " STORED AS DIRECTORIES")?;
3236 }
3237 }
3238 _ => (),
3239 }
3240
3241 if let Some(clustered_by) = &self.clustered_by {
3242 write!(f, " {clustered_by}")?;
3243 }
3244
3245 if let Some(HiveFormat {
3246 row_format,
3247 serde_properties,
3248 storage,
3249 location,
3250 }) = &self.hive_formats
3251 {
3252 match row_format {
3253 Some(HiveRowFormat::SERDE { class }) => write!(f, " ROW FORMAT SERDE '{class}'")?,
3254 Some(HiveRowFormat::DELIMITED { delimiters }) => {
3255 write!(f, " ROW FORMAT DELIMITED")?;
3256 if !delimiters.is_empty() {
3257 write!(f, " {}", display_separated(delimiters, " "))?;
3258 }
3259 }
3260 None => (),
3261 }
3262 match storage {
3263 Some(HiveIOFormat::IOF {
3264 input_format,
3265 output_format,
3266 }) => write!(
3267 f,
3268 " STORED AS INPUTFORMAT {input_format} OUTPUTFORMAT {output_format}"
3269 )?,
3270 Some(HiveIOFormat::FileFormat { format }) if !self.external => {
3271 write!(f, " STORED AS {format}")?
3272 }
3273 Some(HiveIOFormat::Using { format }) => write!(f, " USING {format}")?,
3274 _ => (),
3275 }
3276 if let Some(serde_properties) = serde_properties.as_ref() {
3277 write!(
3278 f,
3279 " WITH SERDEPROPERTIES ({})",
3280 display_comma_separated(serde_properties)
3281 )?;
3282 }
3283 if !self.external {
3284 if let Some(loc) = location {
3285 write!(f, " LOCATION '{loc}'")?;
3286 }
3287 }
3288 }
3289 if self.external {
3290 if let Some(file_format) = self.file_format {
3291 write!(f, " STORED AS {file_format}")?;
3292 }
3293 if let Some(location) = &self.location {
3294 write!(f, " LOCATION '{location}'")?;
3295 }
3296 }
3297
3298 match &self.table_options {
3299 options @ CreateTableOptions::With(_)
3300 | options @ CreateTableOptions::Plain(_)
3301 | options @ CreateTableOptions::TableProperties(_) => write!(f, " {options}")?,
3302 _ => (),
3303 }
3304
3305 if let Some(primary_key) = &self.primary_key {
3306 write!(f, " PRIMARY KEY {primary_key}")?;
3307 }
3308 if let Some(order_by) = &self.order_by {
3309 write!(f, " ORDER BY {order_by}")?;
3310 }
3311 if let Some(inherits) = &self.inherits {
3312 write!(f, " INHERITS ({})", display_comma_separated(inherits))?;
3313 }
3314 if let Some(partition_by) = self.partition_by.as_ref() {
3315 write!(f, " PARTITION BY {partition_by}")?;
3316 }
3317 if let Some(cluster_by) = self.cluster_by.as_ref() {
3318 write!(f, " CLUSTER BY {cluster_by}")?;
3319 }
3320 if let Some(with_connection) = &self.with_connection {
3321 write!(f, " WITH CONNECTION {with_connection}")?;
3322 }
3323 if let options @ CreateTableOptions::Options(_) = &self.table_options {
3324 write!(f, " {options}")?;
3325 }
3326 if let Some(external_volume) = self.external_volume.as_ref() {
3327 write!(f, " EXTERNAL_VOLUME='{external_volume}'")?;
3328 }
3329
3330 if let Some(catalog) = self.catalog.as_ref() {
3331 write!(f, " CATALOG='{catalog}'")?;
3332 }
3333
3334 if self.iceberg {
3335 if let Some(base_location) = self.base_location.as_ref() {
3336 write!(f, " BASE_LOCATION='{base_location}'")?;
3337 }
3338 }
3339
3340 if let Some(catalog_sync) = self.catalog_sync.as_ref() {
3341 write!(f, " CATALOG_SYNC='{catalog_sync}'")?;
3342 }
3343
3344 if let Some(storage_serialization_policy) = self.storage_serialization_policy.as_ref() {
3345 write!(
3346 f,
3347 " STORAGE_SERIALIZATION_POLICY={storage_serialization_policy}"
3348 )?;
3349 }
3350
3351 if self.copy_grants {
3352 write!(f, " COPY GRANTS")?;
3353 }
3354
3355 if let Some(is_enabled) = self.enable_schema_evolution {
3356 write!(
3357 f,
3358 " ENABLE_SCHEMA_EVOLUTION={}",
3359 if is_enabled { "TRUE" } else { "FALSE" }
3360 )?;
3361 }
3362
3363 if let Some(is_enabled) = self.change_tracking {
3364 write!(
3365 f,
3366 " CHANGE_TRACKING={}",
3367 if is_enabled { "TRUE" } else { "FALSE" }
3368 )?;
3369 }
3370
3371 if let Some(data_retention_time_in_days) = self.data_retention_time_in_days {
3372 write!(
3373 f,
3374 " DATA_RETENTION_TIME_IN_DAYS={data_retention_time_in_days}",
3375 )?;
3376 }
3377
3378 if let Some(max_data_extension_time_in_days) = self.max_data_extension_time_in_days {
3379 write!(
3380 f,
3381 " MAX_DATA_EXTENSION_TIME_IN_DAYS={max_data_extension_time_in_days}",
3382 )?;
3383 }
3384
3385 if let Some(default_ddl_collation) = &self.default_ddl_collation {
3386 write!(f, " DEFAULT_DDL_COLLATION='{default_ddl_collation}'",)?;
3387 }
3388
3389 if let Some(with_aggregation_policy) = &self.with_aggregation_policy {
3390 write!(f, " WITH AGGREGATION POLICY {with_aggregation_policy}",)?;
3391 }
3392
3393 if let Some(row_access_policy) = &self.with_row_access_policy {
3394 write!(f, " {row_access_policy}",)?;
3395 }
3396
3397 if let Some(storage_lifecycle_policy) = &self.with_storage_lifecycle_policy {
3398 write!(f, " {storage_lifecycle_policy}",)?;
3399 }
3400
3401 if let Some(tag) = &self.with_tags {
3402 write!(f, " WITH TAG ({})", display_comma_separated(tag.as_slice()))?;
3403 }
3404
3405 if let Some(target_lag) = &self.target_lag {
3406 write!(f, " TARGET_LAG='{target_lag}'")?;
3407 }
3408
3409 if let Some(warehouse) = &self.warehouse {
3410 write!(f, " WAREHOUSE={warehouse}")?;
3411 }
3412
3413 if let Some(refresh_mode) = &self.refresh_mode {
3414 write!(f, " REFRESH_MODE={refresh_mode}")?;
3415 }
3416
3417 if let Some(initialize) = &self.initialize {
3418 write!(f, " INITIALIZE={initialize}")?;
3419 }
3420
3421 if self.require_user {
3422 write!(f, " REQUIRE USER")?;
3423 }
3424
3425 if self.on_commit.is_some() {
3426 let on_commit = match self.on_commit {
3427 Some(OnCommit::DeleteRows) => "ON COMMIT DELETE ROWS",
3428 Some(OnCommit::PreserveRows) => "ON COMMIT PRESERVE ROWS",
3429 Some(OnCommit::Drop) => "ON COMMIT DROP",
3430 None => "",
3431 };
3432 write!(f, " {on_commit}")?;
3433 }
3434 if self.strict {
3435 write!(f, " STRICT")?;
3436 }
3437 if let Some(backup) = self.backup {
3438 write!(f, " BACKUP {}", if backup { "YES" } else { "NO" })?;
3439 }
3440 if let Some(diststyle) = &self.diststyle {
3441 write!(f, " DISTSTYLE {diststyle}")?;
3442 }
3443 if let Some(distkey) = &self.distkey {
3444 write!(f, " DISTKEY({distkey})")?;
3445 }
3446 if let Some(sortkey) = &self.sortkey {
3447 write!(f, " SORTKEY({})", display_comma_separated(sortkey))?;
3448 }
3449 if let Some(query) = &self.query {
3450 write!(f, " AS {query}")?;
3451 }
3452 if let Some(with_data) = &self.with_data {
3453 write!(f, " {with_data}")?;
3454 }
3455 Ok(())
3456 }
3457}
3458
3459#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
3463#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3464#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3465pub struct WithData {
3466 pub data: bool,
3468 pub statistics: Option<bool>,
3471}
3472
3473impl fmt::Display for WithData {
3474 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3475 f.write_str("WITH ")?;
3476 if !self.data {
3477 f.write_str("NO ")?;
3478 }
3479 f.write_str("DATA")?;
3480 if let Some(stats) = self.statistics {
3481 f.write_str(" AND ")?;
3482 if !stats {
3483 f.write_str("NO ")?;
3484 }
3485 f.write_str("STATISTICS")?;
3486 }
3487 Ok(())
3488 }
3489}
3490
3491#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3497#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3498#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3499pub enum ForValues {
3500 In(Vec<Expr>),
3502 From {
3504 from: Vec<PartitionBoundValue>,
3506 to: Vec<PartitionBoundValue>,
3508 },
3509 With {
3511 modulus: u64,
3513 remainder: u64,
3515 },
3516 Default,
3518}
3519
3520impl fmt::Display for ForValues {
3521 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3522 match self {
3523 ForValues::In(values) => {
3524 write!(f, "FOR VALUES IN ({})", display_comma_separated(values))
3525 }
3526 ForValues::From { from, to } => {
3527 write!(
3528 f,
3529 "FOR VALUES FROM ({}) TO ({})",
3530 display_comma_separated(from),
3531 display_comma_separated(to)
3532 )
3533 }
3534 ForValues::With { modulus, remainder } => {
3535 write!(
3536 f,
3537 "FOR VALUES WITH (MODULUS {modulus}, REMAINDER {remainder})"
3538 )
3539 }
3540 ForValues::Default => write!(f, "DEFAULT"),
3541 }
3542 }
3543}
3544
3545#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3550#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3551#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3552pub enum PartitionBoundValue {
3553 Expr(Expr),
3555 MinValue,
3557 MaxValue,
3559}
3560
3561impl fmt::Display for PartitionBoundValue {
3562 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3563 match self {
3564 PartitionBoundValue::Expr(expr) => write!(f, "{expr}"),
3565 PartitionBoundValue::MinValue => write!(f, "MINVALUE"),
3566 PartitionBoundValue::MaxValue => write!(f, "MAXVALUE"),
3567 }
3568 }
3569}
3570
3571#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3575#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3576#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3577pub enum DistStyle {
3578 Auto,
3580 Even,
3582 Key,
3584 All,
3586}
3587
3588impl fmt::Display for DistStyle {
3589 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3590 match self {
3591 DistStyle::Auto => write!(f, "AUTO"),
3592 DistStyle::Even => write!(f, "EVEN"),
3593 DistStyle::Key => write!(f, "KEY"),
3594 DistStyle::All => write!(f, "ALL"),
3595 }
3596 }
3597}
3598
3599#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3600#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3601#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3602pub struct CreateDomain {
3615 pub name: ObjectName,
3617 pub data_type: DataType,
3619 pub collation: Option<Ident>,
3621 pub default: Option<Expr>,
3623 pub constraints: Vec<TableConstraint>,
3625}
3626
3627impl fmt::Display for CreateDomain {
3628 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3629 write!(
3630 f,
3631 "CREATE DOMAIN {name} AS {data_type}",
3632 name = self.name,
3633 data_type = self.data_type
3634 )?;
3635 if let Some(collation) = &self.collation {
3636 write!(f, " COLLATE {collation}")?;
3637 }
3638 if let Some(default) = &self.default {
3639 write!(f, " DEFAULT {default}")?;
3640 }
3641 if !self.constraints.is_empty() {
3642 write!(f, " {}", display_separated(&self.constraints, " "))?;
3643 }
3644 Ok(())
3645 }
3646}
3647
3648#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3650#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3651#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3652pub enum FunctionReturnType {
3653 DataType(DataType),
3655 SetOf(DataType),
3659}
3660
3661impl fmt::Display for FunctionReturnType {
3662 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3663 match self {
3664 FunctionReturnType::DataType(data_type) => write!(f, "{data_type}"),
3665 FunctionReturnType::SetOf(data_type) => write!(f, "SETOF {data_type}"),
3666 }
3667 }
3668}
3669
3670#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3671#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3672#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3673pub struct CreateFunction {
3675 pub or_alter: bool,
3679 pub or_replace: bool,
3681 pub temporary: bool,
3683 pub if_not_exists: bool,
3685 pub name: ObjectName,
3687 pub args: Option<Vec<OperateFunctionArg>>,
3689 pub return_type: Option<FunctionReturnType>,
3691 pub function_body: Option<CreateFunctionBody>,
3699 pub behavior: Option<FunctionBehavior>,
3705 pub called_on_null: Option<FunctionCalledOnNull>,
3709 pub parallel: Option<FunctionParallel>,
3713 pub security: Option<FunctionSecurity>,
3717 pub set_params: Vec<FunctionDefinitionSetParam>,
3721 pub using: Option<CreateFunctionUsing>,
3723 pub language: Option<Ident>,
3731 pub determinism_specifier: Option<FunctionDeterminismSpecifier>,
3735 pub options: Option<Vec<SqlOption>>,
3739 pub remote_connection: Option<ObjectName>,
3749}
3750
3751impl fmt::Display for CreateFunction {
3752 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3753 write!(
3754 f,
3755 "CREATE {or_alter}{or_replace}{temp}FUNCTION {if_not_exists}{name}",
3756 name = self.name,
3757 temp = if self.temporary { "TEMPORARY " } else { "" },
3758 or_alter = if self.or_alter { "OR ALTER " } else { "" },
3759 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3760 if_not_exists = if self.if_not_exists {
3761 "IF NOT EXISTS "
3762 } else {
3763 ""
3764 },
3765 )?;
3766 if let Some(args) = &self.args {
3767 write!(f, "({})", display_comma_separated(args))?;
3768 }
3769 if let Some(return_type) = &self.return_type {
3770 write!(f, " RETURNS {return_type}")?;
3771 }
3772 if let Some(determinism_specifier) = &self.determinism_specifier {
3773 write!(f, " {determinism_specifier}")?;
3774 }
3775 if let Some(language) = &self.language {
3776 write!(f, " LANGUAGE {language}")?;
3777 }
3778 if let Some(behavior) = &self.behavior {
3779 write!(f, " {behavior}")?;
3780 }
3781 if let Some(called_on_null) = &self.called_on_null {
3782 write!(f, " {called_on_null}")?;
3783 }
3784 if let Some(parallel) = &self.parallel {
3785 write!(f, " {parallel}")?;
3786 }
3787 if let Some(security) = &self.security {
3788 write!(f, " {security}")?;
3789 }
3790 for set_param in &self.set_params {
3791 write!(f, " {set_param}")?;
3792 }
3793 if let Some(remote_connection) = &self.remote_connection {
3794 write!(f, " REMOTE WITH CONNECTION {remote_connection}")?;
3795 }
3796 if let Some(CreateFunctionBody::AsBeforeOptions { body, link_symbol }) = &self.function_body
3797 {
3798 write!(f, " AS {body}")?;
3799 if let Some(link_symbol) = link_symbol {
3800 write!(f, ", {link_symbol}")?;
3801 }
3802 }
3803 if let Some(CreateFunctionBody::Return(function_body)) = &self.function_body {
3804 write!(f, " RETURN {function_body}")?;
3805 }
3806 if let Some(CreateFunctionBody::AsReturnExpr(function_body)) = &self.function_body {
3807 write!(f, " AS RETURN {function_body}")?;
3808 }
3809 if let Some(CreateFunctionBody::AsReturnSelect(function_body)) = &self.function_body {
3810 write!(f, " AS RETURN {function_body}")?;
3811 }
3812 if let Some(using) = &self.using {
3813 write!(f, " {using}")?;
3814 }
3815 if let Some(options) = &self.options {
3816 write!(
3817 f,
3818 " OPTIONS({})",
3819 display_comma_separated(options.as_slice())
3820 )?;
3821 }
3822 if let Some(CreateFunctionBody::AsAfterOptions(function_body)) = &self.function_body {
3823 write!(f, " AS {function_body}")?;
3824 }
3825 if let Some(CreateFunctionBody::AsBeginEnd(bes)) = &self.function_body {
3826 write!(f, " AS {bes}")?;
3827 }
3828 Ok(())
3829 }
3830}
3831
3832#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3842#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3843#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3844pub struct CreateConnector {
3845 pub name: Ident,
3847 pub if_not_exists: bool,
3849 pub connector_type: Option<String>,
3851 pub url: Option<String>,
3853 pub comment: Option<CommentDef>,
3855 pub with_dcproperties: Option<Vec<SqlOption>>,
3857}
3858
3859impl fmt::Display for CreateConnector {
3860 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3861 write!(
3862 f,
3863 "CREATE CONNECTOR {if_not_exists}{name}",
3864 if_not_exists = if self.if_not_exists {
3865 "IF NOT EXISTS "
3866 } else {
3867 ""
3868 },
3869 name = self.name,
3870 )?;
3871
3872 if let Some(connector_type) = &self.connector_type {
3873 write!(f, " TYPE '{connector_type}'")?;
3874 }
3875
3876 if let Some(url) = &self.url {
3877 write!(f, " URL '{url}'")?;
3878 }
3879
3880 if let Some(comment) = &self.comment {
3881 write!(f, " COMMENT = '{comment}'")?;
3882 }
3883
3884 if let Some(with_dcproperties) = &self.with_dcproperties {
3885 write!(
3886 f,
3887 " WITH DCPROPERTIES({})",
3888 display_comma_separated(with_dcproperties)
3889 )?;
3890 }
3891
3892 Ok(())
3893 }
3894}
3895
3896#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3901#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3902#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3903pub enum AlterSchemaOperation {
3904 SetDefaultCollate {
3906 collate: Expr,
3908 },
3909 AddReplica {
3911 replica: Ident,
3913 options: Option<Vec<SqlOption>>,
3915 },
3916 DropReplica {
3918 replica: Ident,
3920 },
3921 SetOptionsParens {
3923 options: Vec<SqlOption>,
3925 },
3926 Rename {
3928 name: ObjectName,
3930 },
3931 OwnerTo {
3933 owner: Owner,
3935 },
3936}
3937
3938impl fmt::Display for AlterSchemaOperation {
3939 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3940 match self {
3941 AlterSchemaOperation::SetDefaultCollate { collate } => {
3942 write!(f, "SET DEFAULT COLLATE {collate}")
3943 }
3944 AlterSchemaOperation::AddReplica { replica, options } => {
3945 write!(f, "ADD REPLICA {replica}")?;
3946 if let Some(options) = options {
3947 write!(f, " OPTIONS ({})", display_comma_separated(options))?;
3948 }
3949 Ok(())
3950 }
3951 AlterSchemaOperation::DropReplica { replica } => write!(f, "DROP REPLICA {replica}"),
3952 AlterSchemaOperation::SetOptionsParens { options } => {
3953 write!(f, "SET OPTIONS ({})", display_comma_separated(options))
3954 }
3955 AlterSchemaOperation::Rename { name } => write!(f, "RENAME TO {name}"),
3956 AlterSchemaOperation::OwnerTo { owner } => write!(f, "OWNER TO {owner}"),
3957 }
3958 }
3959}
3960#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3966#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3967#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3968pub enum RenameTableNameKind {
3969 As(ObjectName),
3971 To(ObjectName),
3973}
3974
3975impl fmt::Display for RenameTableNameKind {
3976 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3977 match self {
3978 RenameTableNameKind::As(name) => write!(f, "AS {name}"),
3979 RenameTableNameKind::To(name) => write!(f, "TO {name}"),
3980 }
3981 }
3982}
3983
3984#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3985#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3986#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3987pub struct AlterSchema {
3989 pub name: ObjectName,
3991 pub if_exists: bool,
3993 pub operations: Vec<AlterSchemaOperation>,
3995}
3996
3997impl fmt::Display for AlterSchema {
3998 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3999 write!(f, "ALTER SCHEMA ")?;
4000 if self.if_exists {
4001 write!(f, "IF EXISTS ")?;
4002 }
4003 write!(f, "{}", self.name)?;
4004 for operation in &self.operations {
4005 write!(f, " {operation}")?;
4006 }
4007
4008 Ok(())
4009 }
4010}
4011
4012impl Spanned for RenameTableNameKind {
4013 fn span(&self) -> Span {
4014 match self {
4015 RenameTableNameKind::As(name) => name.span(),
4016 RenameTableNameKind::To(name) => name.span(),
4017 }
4018 }
4019}
4020
4021#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
4022#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4023#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4024pub enum TriggerObjectKind {
4026 For(TriggerObject),
4028 ForEach(TriggerObject),
4030}
4031
4032impl Display for TriggerObjectKind {
4033 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4034 match self {
4035 TriggerObjectKind::For(obj) => write!(f, "FOR {obj}"),
4036 TriggerObjectKind::ForEach(obj) => write!(f, "FOR EACH {obj}"),
4037 }
4038 }
4039}
4040
4041#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4042#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4043#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4044pub struct CreateTrigger {
4058 pub or_alter: bool,
4062 pub temporary: bool,
4079 pub or_replace: bool,
4089 pub is_constraint: bool,
4091 pub name: ObjectName,
4093 pub period: Option<TriggerPeriod>,
4122 pub period_before_table: bool,
4133 pub events: Vec<TriggerEvent>,
4135 pub table_name: ObjectName,
4137 pub referenced_table_name: Option<ObjectName>,
4140 pub referencing: Vec<TriggerReferencing>,
4142 pub trigger_object: Option<TriggerObjectKind>,
4147 pub condition: Option<Expr>,
4149 pub exec_body: Option<TriggerExecBody>,
4151 pub statements_as: bool,
4153 pub statements: Option<ConditionalStatements>,
4155 pub characteristics: Option<ConstraintCharacteristics>,
4157}
4158
4159impl Display for CreateTrigger {
4160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4161 let CreateTrigger {
4162 or_alter,
4163 temporary,
4164 or_replace,
4165 is_constraint,
4166 name,
4167 period_before_table,
4168 period,
4169 events,
4170 table_name,
4171 referenced_table_name,
4172 referencing,
4173 trigger_object,
4174 condition,
4175 exec_body,
4176 statements_as,
4177 statements,
4178 characteristics,
4179 } = self;
4180 write!(
4181 f,
4182 "CREATE {temporary}{or_alter}{or_replace}{is_constraint}TRIGGER {name} ",
4183 temporary = if *temporary { "TEMPORARY " } else { "" },
4184 or_alter = if *or_alter { "OR ALTER " } else { "" },
4185 or_replace = if *or_replace { "OR REPLACE " } else { "" },
4186 is_constraint = if *is_constraint { "CONSTRAINT " } else { "" },
4187 )?;
4188
4189 if *period_before_table {
4190 if let Some(p) = period {
4191 write!(f, "{p} ")?;
4192 }
4193 if !events.is_empty() {
4194 write!(f, "{} ", display_separated(events, " OR "))?;
4195 }
4196 write!(f, "ON {table_name}")?;
4197 } else {
4198 write!(f, "ON {table_name} ")?;
4199 if let Some(p) = period {
4200 write!(f, "{p}")?;
4201 }
4202 if !events.is_empty() {
4203 write!(f, " {}", display_separated(events, ", "))?;
4204 }
4205 }
4206
4207 if let Some(referenced_table_name) = referenced_table_name {
4208 write!(f, " FROM {referenced_table_name}")?;
4209 }
4210
4211 if let Some(characteristics) = characteristics {
4212 write!(f, " {characteristics}")?;
4213 }
4214
4215 if !referencing.is_empty() {
4216 write!(f, " REFERENCING {}", display_separated(referencing, " "))?;
4217 }
4218
4219 if let Some(trigger_object) = trigger_object {
4220 write!(f, " {trigger_object}")?;
4221 }
4222 if let Some(condition) = condition {
4223 write!(f, " WHEN {condition}")?;
4224 }
4225 if let Some(exec_body) = exec_body {
4226 write!(f, " EXECUTE {exec_body}")?;
4227 }
4228 if let Some(statements) = statements {
4229 if *statements_as {
4230 write!(f, " AS")?;
4231 }
4232 write!(f, " {statements}")?;
4233 }
4234 Ok(())
4235 }
4236}
4237
4238#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4239#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4240#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4241pub struct DropTrigger {
4248 pub if_exists: bool,
4250 pub trigger_name: ObjectName,
4252 pub table_name: Option<ObjectName>,
4254 pub option: Option<ReferentialAction>,
4256}
4257
4258impl fmt::Display for DropTrigger {
4259 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4260 let DropTrigger {
4261 if_exists,
4262 trigger_name,
4263 table_name,
4264 option,
4265 } = self;
4266 write!(f, "DROP TRIGGER")?;
4267 if *if_exists {
4268 write!(f, " IF EXISTS")?;
4269 }
4270 match &table_name {
4271 Some(table_name) => write!(f, " {trigger_name} ON {table_name}")?,
4272 None => write!(f, " {trigger_name}")?,
4273 };
4274 if let Some(option) = option {
4275 write!(f, " {option}")?;
4276 }
4277 Ok(())
4278 }
4279}
4280
4281#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4287#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4288#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4289pub struct Truncate {
4290 pub table_names: Vec<super::TruncateTableTarget>,
4292 pub partitions: Option<Vec<Expr>>,
4294 pub table: bool,
4296 pub if_exists: bool,
4298 pub identity: Option<super::TruncateIdentityOption>,
4300 pub cascade: Option<super::CascadeOption>,
4302 pub on_cluster: Option<Ident>,
4305}
4306
4307impl fmt::Display for Truncate {
4308 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4309 let table = if self.table { "TABLE " } else { "" };
4310 let if_exists = if self.if_exists { "IF EXISTS " } else { "" };
4311
4312 write!(
4313 f,
4314 "TRUNCATE {table}{if_exists}{table_names}",
4315 table_names = display_comma_separated(&self.table_names)
4316 )?;
4317
4318 if let Some(identity) = &self.identity {
4319 match identity {
4320 super::TruncateIdentityOption::Restart => write!(f, " RESTART IDENTITY")?,
4321 super::TruncateIdentityOption::Continue => write!(f, " CONTINUE IDENTITY")?,
4322 }
4323 }
4324 if let Some(cascade) = &self.cascade {
4325 match cascade {
4326 super::CascadeOption::Cascade => write!(f, " CASCADE")?,
4327 super::CascadeOption::Restrict => write!(f, " RESTRICT")?,
4328 }
4329 }
4330
4331 if let Some(ref parts) = &self.partitions {
4332 if !parts.is_empty() {
4333 write!(f, " PARTITION ({})", display_comma_separated(parts))?;
4334 }
4335 }
4336 if let Some(on_cluster) = &self.on_cluster {
4337 write!(f, " ON CLUSTER {on_cluster}")?;
4338 }
4339 Ok(())
4340 }
4341}
4342
4343impl Spanned for Truncate {
4344 fn span(&self) -> Span {
4345 Span::union_iter(
4346 self.table_names.iter().map(|i| i.name.span()).chain(
4347 self.partitions
4348 .iter()
4349 .flat_map(|i| i.iter().map(|k| k.span())),
4350 ),
4351 )
4352 }
4353}
4354
4355#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4362#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4363#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4364pub struct Msck {
4365 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4367 pub table_name: ObjectName,
4368 pub repair: bool,
4370 pub partition_action: Option<super::AddDropSync>,
4372}
4373
4374impl fmt::Display for Msck {
4375 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4376 write!(
4377 f,
4378 "MSCK {repair}TABLE {table}",
4379 repair = if self.repair { "REPAIR " } else { "" },
4380 table = self.table_name
4381 )?;
4382 if let Some(pa) = &self.partition_action {
4383 write!(f, " {pa}")?;
4384 }
4385 Ok(())
4386 }
4387}
4388
4389impl Spanned for Msck {
4390 fn span(&self) -> Span {
4391 self.table_name.span()
4392 }
4393}
4394
4395#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4397#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4398#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4399pub struct CreateView {
4400 pub or_alter: bool,
4404 pub or_replace: bool,
4406 pub materialized: bool,
4408 pub secure: bool,
4411 pub name: ObjectName,
4413 pub name_before_not_exists: bool,
4424 pub columns: Vec<ViewColumnDef>,
4426 pub query: Box<Query>,
4428 pub options: CreateTableOptions,
4430 pub cluster_by: Vec<Ident>,
4432 pub comment: Option<String>,
4435 pub with_no_schema_binding: bool,
4437 pub if_not_exists: bool,
4439 pub temporary: bool,
4441 pub copy_grants: bool,
4444 pub to: Option<ObjectName>,
4447 pub params: Option<CreateViewParams>,
4449}
4450
4451impl fmt::Display for CreateView {
4452 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4453 write!(
4454 f,
4455 "CREATE {or_alter}{or_replace}",
4456 or_alter = if self.or_alter { "OR ALTER " } else { "" },
4457 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
4458 )?;
4459 if let Some(ref params) = self.params {
4460 params.fmt(f)?;
4461 }
4462 write!(
4463 f,
4464 "{secure}{materialized}{temporary}VIEW {if_not_and_name}{to}",
4465 if_not_and_name = if self.if_not_exists {
4466 if self.name_before_not_exists {
4467 format!("{} IF NOT EXISTS", self.name)
4468 } else {
4469 format!("IF NOT EXISTS {}", self.name)
4470 }
4471 } else {
4472 format!("{}", self.name)
4473 },
4474 secure = if self.secure { "SECURE " } else { "" },
4475 materialized = if self.materialized {
4476 "MATERIALIZED "
4477 } else {
4478 ""
4479 },
4480 temporary = if self.temporary { "TEMPORARY " } else { "" },
4481 to = self
4482 .to
4483 .as_ref()
4484 .map(|to| format!(" TO {to}"))
4485 .unwrap_or_default()
4486 )?;
4487 if self.copy_grants {
4488 write!(f, " COPY GRANTS")?;
4489 }
4490 if !self.columns.is_empty() {
4491 write!(f, " ({})", display_comma_separated(&self.columns))?;
4492 }
4493 if matches!(self.options, CreateTableOptions::With(_)) {
4494 write!(f, " {}", self.options)?;
4495 }
4496 if let Some(ref comment) = self.comment {
4497 write!(f, " COMMENT = '{}'", escape_single_quote_string(comment))?;
4498 }
4499 if !self.cluster_by.is_empty() {
4500 write!(
4501 f,
4502 " CLUSTER BY ({})",
4503 display_comma_separated(&self.cluster_by)
4504 )?;
4505 }
4506 if matches!(self.options, CreateTableOptions::Options(_)) {
4507 write!(f, " {}", self.options)?;
4508 }
4509 f.write_str(" AS")?;
4510 SpaceOrNewline.fmt(f)?;
4511 self.query.fmt(f)?;
4512 if self.with_no_schema_binding {
4513 write!(f, " WITH NO SCHEMA BINDING")?;
4514 }
4515 Ok(())
4516 }
4517}
4518
4519#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4522#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4523#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4524pub struct CreateExtension {
4525 pub name: Ident,
4527 pub if_not_exists: bool,
4529 pub cascade: bool,
4531 pub schema: Option<Ident>,
4533 pub version: Option<Ident>,
4535}
4536
4537impl fmt::Display for CreateExtension {
4538 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4539 write!(
4540 f,
4541 "CREATE EXTENSION {if_not_exists}{name}",
4542 if_not_exists = if self.if_not_exists {
4543 "IF NOT EXISTS "
4544 } else {
4545 ""
4546 },
4547 name = self.name
4548 )?;
4549 if self.cascade || self.schema.is_some() || self.version.is_some() {
4550 write!(f, " WITH")?;
4551
4552 if let Some(name) = &self.schema {
4553 write!(f, " SCHEMA {name}")?;
4554 }
4555 if let Some(version) = &self.version {
4556 write!(f, " VERSION {version}")?;
4557 }
4558 if self.cascade {
4559 write!(f, " CASCADE")?;
4560 }
4561 }
4562
4563 Ok(())
4564 }
4565}
4566
4567impl Spanned for CreateExtension {
4568 fn span(&self) -> Span {
4569 Span::empty()
4570 }
4571}
4572
4573#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4581#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4582#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4583pub struct DropExtension {
4584 pub names: Vec<Ident>,
4586 pub if_exists: bool,
4588 pub cascade_or_restrict: Option<ReferentialAction>,
4590}
4591
4592impl fmt::Display for DropExtension {
4593 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4594 write!(f, "DROP EXTENSION")?;
4595 if self.if_exists {
4596 write!(f, " IF EXISTS")?;
4597 }
4598 write!(f, " {}", display_comma_separated(&self.names))?;
4599 if let Some(cascade_or_restrict) = &self.cascade_or_restrict {
4600 write!(f, " {cascade_or_restrict}")?;
4601 }
4602 Ok(())
4603 }
4604}
4605
4606impl Spanned for DropExtension {
4607 fn span(&self) -> Span {
4608 Span::empty()
4609 }
4610}
4611
4612#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4615#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4616#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4617pub struct CreateCollation {
4618 pub if_not_exists: bool,
4620 pub name: ObjectName,
4622 pub definition: CreateCollationDefinition,
4624}
4625
4626#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4628#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4629#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4630pub enum CreateCollationDefinition {
4631 From(ObjectName),
4637 Options(Vec<SqlOption>),
4643}
4644
4645impl fmt::Display for CreateCollation {
4646 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4647 write!(
4648 f,
4649 "CREATE COLLATION {if_not_exists}{name}",
4650 if_not_exists = if self.if_not_exists {
4651 "IF NOT EXISTS "
4652 } else {
4653 ""
4654 },
4655 name = self.name
4656 )?;
4657 match &self.definition {
4658 CreateCollationDefinition::From(existing_collation) => {
4659 write!(f, " FROM {existing_collation}")
4660 }
4661 CreateCollationDefinition::Options(options) => {
4662 write!(f, " ({})", display_comma_separated(options))
4663 }
4664 }
4665 }
4666}
4667
4668impl Spanned for CreateCollation {
4669 fn span(&self) -> Span {
4670 Span::empty()
4671 }
4672}
4673
4674#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4677#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4678#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4679pub struct AlterCollation {
4680 pub name: ObjectName,
4682 pub operation: AlterCollationOperation,
4684}
4685
4686#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4688#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4689#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4690pub enum AlterCollationOperation {
4691 RenameTo {
4697 new_name: Ident,
4699 },
4700 OwnerTo(Owner),
4706 SetSchema {
4712 schema_name: ObjectName,
4714 },
4715 RefreshVersion,
4721}
4722
4723impl fmt::Display for AlterCollationOperation {
4724 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4725 match self {
4726 AlterCollationOperation::RenameTo { new_name } => write!(f, "RENAME TO {new_name}"),
4727 AlterCollationOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
4728 AlterCollationOperation::SetSchema { schema_name } => {
4729 write!(f, "SET SCHEMA {schema_name}")
4730 }
4731 AlterCollationOperation::RefreshVersion => write!(f, "REFRESH VERSION"),
4732 }
4733 }
4734}
4735
4736impl fmt::Display for AlterCollation {
4737 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4738 write!(f, "ALTER COLLATION {} {}", self.name, self.operation)
4739 }
4740}
4741
4742impl Spanned for AlterCollation {
4743 fn span(&self) -> Span {
4744 Span::empty()
4745 }
4746}
4747
4748#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4751#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4752#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4753pub enum AlterTableType {
4754 Iceberg,
4757 Dynamic,
4760 External,
4763}
4764
4765#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4767#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4768#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4769pub struct AlterTable {
4770 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4772 pub name: ObjectName,
4773 pub r#async: bool,
4779 pub if_exists: bool,
4781 pub only: bool,
4783 pub operations: Vec<AlterTableOperation>,
4785 pub location: Option<HiveSetLocation>,
4787 pub on_cluster: Option<Ident>,
4791 pub table_type: Option<AlterTableType>,
4793 pub end_token: AttachedToken,
4795}
4796
4797impl fmt::Display for AlterTable {
4798 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4799 match &self.table_type {
4800 Some(AlterTableType::Iceberg) => write!(f, "ALTER ICEBERG TABLE ")?,
4801 Some(AlterTableType::Dynamic) => write!(f, "ALTER DYNAMIC TABLE ")?,
4802 Some(AlterTableType::External) => write!(f, "ALTER EXTERNAL TABLE ")?,
4803 None => write!(f, "ALTER TABLE ")?,
4804 }
4805
4806 if self.r#async {
4807 write!(f, "ASYNC ")?;
4808 }
4809 if self.if_exists {
4810 write!(f, "IF EXISTS ")?;
4811 }
4812 if self.only {
4813 write!(f, "ONLY ")?;
4814 }
4815 write!(f, "{} ", self.name)?;
4816 if let Some(cluster) = &self.on_cluster {
4817 write!(f, "ON CLUSTER {cluster} ")?;
4818 }
4819 write!(f, "{}", display_comma_separated(&self.operations))?;
4820 if let Some(loc) = &self.location {
4821 write!(f, " {loc}")?
4822 }
4823 Ok(())
4824 }
4825}
4826
4827#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4829#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4830#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4831pub struct DropFunction {
4832 pub if_exists: bool,
4834 pub func_desc: Vec<FunctionDesc>,
4836 pub drop_behavior: Option<DropBehavior>,
4838}
4839
4840impl fmt::Display for DropFunction {
4841 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4842 write!(
4843 f,
4844 "DROP FUNCTION{} {}",
4845 if self.if_exists { " IF EXISTS" } else { "" },
4846 display_comma_separated(&self.func_desc),
4847 )?;
4848 if let Some(op) = &self.drop_behavior {
4849 write!(f, " {op}")?;
4850 }
4851 Ok(())
4852 }
4853}
4854
4855impl Spanned for DropFunction {
4856 fn span(&self) -> Span {
4857 Span::empty()
4858 }
4859}
4860
4861#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4864#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4865#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4866pub struct CreateOperator {
4867 pub name: ObjectName,
4869 pub function: ObjectName,
4871 pub is_procedure: bool,
4873 pub left_arg: Option<DataType>,
4875 pub right_arg: Option<DataType>,
4877 pub options: Vec<OperatorOption>,
4879}
4880
4881#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4884#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4885#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4886pub struct CreateOperatorFamily {
4887 pub name: ObjectName,
4889 pub using: Ident,
4891}
4892
4893#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4896#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4897#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4898pub struct CreateOperatorClass {
4899 pub name: ObjectName,
4901 pub default: bool,
4903 pub for_type: DataType,
4905 pub using: Ident,
4907 pub family: Option<ObjectName>,
4909 pub items: Vec<OperatorClassItem>,
4911}
4912
4913impl fmt::Display for CreateOperator {
4914 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4915 write!(f, "CREATE OPERATOR {} (", self.name)?;
4916
4917 let function_keyword = if self.is_procedure {
4918 "PROCEDURE"
4919 } else {
4920 "FUNCTION"
4921 };
4922 let mut params = vec![format!("{} = {}", function_keyword, self.function)];
4923
4924 if let Some(left_arg) = &self.left_arg {
4925 params.push(format!("LEFTARG = {}", left_arg));
4926 }
4927 if let Some(right_arg) = &self.right_arg {
4928 params.push(format!("RIGHTARG = {}", right_arg));
4929 }
4930
4931 for option in &self.options {
4932 params.push(option.to_string());
4933 }
4934
4935 write!(f, "{}", params.join(", "))?;
4936 write!(f, ")")
4937 }
4938}
4939
4940impl fmt::Display for CreateOperatorFamily {
4941 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4942 write!(
4943 f,
4944 "CREATE OPERATOR FAMILY {} USING {}",
4945 self.name, self.using
4946 )
4947 }
4948}
4949
4950impl fmt::Display for CreateOperatorClass {
4951 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4952 write!(f, "CREATE OPERATOR CLASS {}", self.name)?;
4953 if self.default {
4954 write!(f, " DEFAULT")?;
4955 }
4956 write!(f, " FOR TYPE {} USING {}", self.for_type, self.using)?;
4957 if let Some(family) = &self.family {
4958 write!(f, " FAMILY {}", family)?;
4959 }
4960 write!(f, " AS {}", display_comma_separated(&self.items))
4961 }
4962}
4963
4964#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4966#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4967#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4968pub struct OperatorArgTypes {
4969 pub left: DataType,
4971 pub right: DataType,
4973}
4974
4975impl fmt::Display for OperatorArgTypes {
4976 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4977 write!(f, "{}, {}", self.left, self.right)
4978 }
4979}
4980
4981#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4983#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4984#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4985pub enum OperatorClassItem {
4986 Operator {
4988 strategy_number: u64,
4990 operator_name: ObjectName,
4992 op_types: Option<OperatorArgTypes>,
4994 purpose: Option<OperatorPurpose>,
4996 },
4997 Function {
4999 support_number: u64,
5001 op_types: Option<Vec<DataType>>,
5003 function_name: ObjectName,
5005 argument_types: Vec<DataType>,
5007 },
5008 Storage {
5010 storage_type: DataType,
5012 },
5013}
5014
5015#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5017#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5018#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5019pub enum OperatorPurpose {
5020 ForSearch,
5022 ForOrderBy {
5024 sort_family: ObjectName,
5026 },
5027}
5028
5029impl fmt::Display for OperatorClassItem {
5030 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5031 match self {
5032 OperatorClassItem::Operator {
5033 strategy_number,
5034 operator_name,
5035 op_types,
5036 purpose,
5037 } => {
5038 write!(f, "OPERATOR {strategy_number} {operator_name}")?;
5039 if let Some(types) = op_types {
5040 write!(f, " ({types})")?;
5041 }
5042 if let Some(purpose) = purpose {
5043 write!(f, " {purpose}")?;
5044 }
5045 Ok(())
5046 }
5047 OperatorClassItem::Function {
5048 support_number,
5049 op_types,
5050 function_name,
5051 argument_types,
5052 } => {
5053 write!(f, "FUNCTION {support_number}")?;
5054 if let Some(types) = op_types {
5055 write!(f, " ({})", display_comma_separated(types))?;
5056 }
5057 write!(f, " {function_name}")?;
5058 if !argument_types.is_empty() {
5059 write!(f, "({})", display_comma_separated(argument_types))?;
5060 }
5061 Ok(())
5062 }
5063 OperatorClassItem::Storage { storage_type } => {
5064 write!(f, "STORAGE {storage_type}")
5065 }
5066 }
5067 }
5068}
5069
5070impl fmt::Display for OperatorPurpose {
5071 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5072 match self {
5073 OperatorPurpose::ForSearch => write!(f, "FOR SEARCH"),
5074 OperatorPurpose::ForOrderBy { sort_family } => {
5075 write!(f, "FOR ORDER BY {sort_family}")
5076 }
5077 }
5078 }
5079}
5080
5081#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5084#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5085#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5086pub struct DropOperator {
5087 pub if_exists: bool,
5089 pub operators: Vec<DropOperatorSignature>,
5091 pub drop_behavior: Option<DropBehavior>,
5093}
5094
5095#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5097#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5098#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5099pub struct DropOperatorSignature {
5100 pub name: ObjectName,
5102 pub left_type: Option<DataType>,
5104 pub right_type: DataType,
5106}
5107
5108impl fmt::Display for DropOperatorSignature {
5109 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5110 write!(f, "{} (", self.name)?;
5111 if let Some(left_type) = &self.left_type {
5112 write!(f, "{}", left_type)?;
5113 } else {
5114 write!(f, "NONE")?;
5115 }
5116 write!(f, ", {})", self.right_type)
5117 }
5118}
5119
5120impl fmt::Display for DropOperator {
5121 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5122 write!(f, "DROP OPERATOR")?;
5123 if self.if_exists {
5124 write!(f, " IF EXISTS")?;
5125 }
5126 write!(f, " {}", display_comma_separated(&self.operators))?;
5127 if let Some(drop_behavior) = &self.drop_behavior {
5128 write!(f, " {}", drop_behavior)?;
5129 }
5130 Ok(())
5131 }
5132}
5133
5134impl Spanned for DropOperator {
5135 fn span(&self) -> Span {
5136 Span::empty()
5137 }
5138}
5139
5140#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5143#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5144#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5145pub struct DropOperatorFamily {
5146 pub if_exists: bool,
5148 pub names: Vec<ObjectName>,
5150 pub using: Ident,
5152 pub drop_behavior: Option<DropBehavior>,
5154}
5155
5156impl fmt::Display for DropOperatorFamily {
5157 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5158 write!(f, "DROP OPERATOR FAMILY")?;
5159 if self.if_exists {
5160 write!(f, " IF EXISTS")?;
5161 }
5162 write!(f, " {}", display_comma_separated(&self.names))?;
5163 write!(f, " USING {}", self.using)?;
5164 if let Some(drop_behavior) = &self.drop_behavior {
5165 write!(f, " {}", drop_behavior)?;
5166 }
5167 Ok(())
5168 }
5169}
5170
5171impl Spanned for DropOperatorFamily {
5172 fn span(&self) -> Span {
5173 Span::empty()
5174 }
5175}
5176
5177#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5180#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5181#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5182pub struct DropOperatorClass {
5183 pub if_exists: bool,
5185 pub names: Vec<ObjectName>,
5187 pub using: Ident,
5189 pub drop_behavior: Option<DropBehavior>,
5191}
5192
5193impl fmt::Display for DropOperatorClass {
5194 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5195 write!(f, "DROP OPERATOR CLASS")?;
5196 if self.if_exists {
5197 write!(f, " IF EXISTS")?;
5198 }
5199 write!(f, " {}", display_comma_separated(&self.names))?;
5200 write!(f, " USING {}", self.using)?;
5201 if let Some(drop_behavior) = &self.drop_behavior {
5202 write!(f, " {}", drop_behavior)?;
5203 }
5204 Ok(())
5205 }
5206}
5207
5208impl Spanned for DropOperatorClass {
5209 fn span(&self) -> Span {
5210 Span::empty()
5211 }
5212}
5213
5214#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5216#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5217#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5218pub enum OperatorFamilyItem {
5219 Operator {
5221 strategy_number: u64,
5223 operator_name: ObjectName,
5225 op_types: Vec<DataType>,
5227 purpose: Option<OperatorPurpose>,
5229 },
5230 Function {
5232 support_number: u64,
5234 op_types: Option<Vec<DataType>>,
5236 function_name: ObjectName,
5238 argument_types: Vec<DataType>,
5240 },
5241}
5242
5243#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5245#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5246#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5247pub enum OperatorFamilyDropItem {
5248 Operator {
5250 strategy_number: u64,
5252 op_types: Vec<DataType>,
5254 },
5255 Function {
5257 support_number: u64,
5259 op_types: Vec<DataType>,
5261 },
5262}
5263
5264impl fmt::Display for OperatorFamilyItem {
5265 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5266 match self {
5267 OperatorFamilyItem::Operator {
5268 strategy_number,
5269 operator_name,
5270 op_types,
5271 purpose,
5272 } => {
5273 write!(
5274 f,
5275 "OPERATOR {strategy_number} {operator_name} ({})",
5276 display_comma_separated(op_types)
5277 )?;
5278 if let Some(purpose) = purpose {
5279 write!(f, " {purpose}")?;
5280 }
5281 Ok(())
5282 }
5283 OperatorFamilyItem::Function {
5284 support_number,
5285 op_types,
5286 function_name,
5287 argument_types,
5288 } => {
5289 write!(f, "FUNCTION {support_number}")?;
5290 if let Some(types) = op_types {
5291 write!(f, " ({})", display_comma_separated(types))?;
5292 }
5293 write!(f, " {function_name}")?;
5294 if !argument_types.is_empty() {
5295 write!(f, "({})", display_comma_separated(argument_types))?;
5296 }
5297 Ok(())
5298 }
5299 }
5300 }
5301}
5302
5303impl fmt::Display for OperatorFamilyDropItem {
5304 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5305 match self {
5306 OperatorFamilyDropItem::Operator {
5307 strategy_number,
5308 op_types,
5309 } => {
5310 write!(
5311 f,
5312 "OPERATOR {strategy_number} ({})",
5313 display_comma_separated(op_types)
5314 )
5315 }
5316 OperatorFamilyDropItem::Function {
5317 support_number,
5318 op_types,
5319 } => {
5320 write!(
5321 f,
5322 "FUNCTION {support_number} ({})",
5323 display_comma_separated(op_types)
5324 )
5325 }
5326 }
5327 }
5328}
5329
5330#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5333#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5334#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5335pub struct AlterOperatorFamily {
5336 pub name: ObjectName,
5338 pub using: Ident,
5340 pub operation: AlterOperatorFamilyOperation,
5342}
5343
5344#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5346#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5347#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5348pub enum AlterOperatorFamilyOperation {
5349 Add {
5351 items: Vec<OperatorFamilyItem>,
5353 },
5354 Drop {
5356 items: Vec<OperatorFamilyDropItem>,
5358 },
5359 RenameTo {
5361 new_name: ObjectName,
5363 },
5364 OwnerTo(Owner),
5366 SetSchema {
5368 schema_name: ObjectName,
5370 },
5371}
5372
5373impl fmt::Display for AlterOperatorFamily {
5374 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5375 write!(
5376 f,
5377 "ALTER OPERATOR FAMILY {} USING {}",
5378 self.name, self.using
5379 )?;
5380 write!(f, " {}", self.operation)
5381 }
5382}
5383
5384impl fmt::Display for AlterOperatorFamilyOperation {
5385 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5386 match self {
5387 AlterOperatorFamilyOperation::Add { items } => {
5388 write!(f, "ADD {}", display_comma_separated(items))
5389 }
5390 AlterOperatorFamilyOperation::Drop { items } => {
5391 write!(f, "DROP {}", display_comma_separated(items))
5392 }
5393 AlterOperatorFamilyOperation::RenameTo { new_name } => {
5394 write!(f, "RENAME TO {new_name}")
5395 }
5396 AlterOperatorFamilyOperation::OwnerTo(owner) => {
5397 write!(f, "OWNER TO {owner}")
5398 }
5399 AlterOperatorFamilyOperation::SetSchema { schema_name } => {
5400 write!(f, "SET SCHEMA {schema_name}")
5401 }
5402 }
5403 }
5404}
5405
5406impl Spanned for AlterOperatorFamily {
5407 fn span(&self) -> Span {
5408 Span::empty()
5409 }
5410}
5411
5412#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5415#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5416#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5417pub struct AlterOperatorClass {
5418 pub name: ObjectName,
5420 pub using: Ident,
5422 pub operation: AlterOperatorClassOperation,
5424}
5425
5426#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5428#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5429#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5430pub enum AlterOperatorClassOperation {
5431 RenameTo {
5434 new_name: ObjectName,
5436 },
5437 OwnerTo(Owner),
5439 SetSchema {
5442 schema_name: ObjectName,
5444 },
5445}
5446
5447impl fmt::Display for AlterOperatorClass {
5448 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5449 write!(f, "ALTER OPERATOR CLASS {} USING {}", self.name, self.using)?;
5450 write!(f, " {}", self.operation)
5451 }
5452}
5453
5454impl fmt::Display for AlterOperatorClassOperation {
5455 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5456 match self {
5457 AlterOperatorClassOperation::RenameTo { new_name } => {
5458 write!(f, "RENAME TO {new_name}")
5459 }
5460 AlterOperatorClassOperation::OwnerTo(owner) => {
5461 write!(f, "OWNER TO {owner}")
5462 }
5463 AlterOperatorClassOperation::SetSchema { schema_name } => {
5464 write!(f, "SET SCHEMA {schema_name}")
5465 }
5466 }
5467 }
5468}
5469
5470impl Spanned for AlterOperatorClass {
5471 fn span(&self) -> Span {
5472 Span::empty()
5473 }
5474}
5475
5476#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5478#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5479#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5480pub struct AlterFunction {
5481 pub kind: AlterFunctionKind,
5483 pub function: FunctionDesc,
5485 pub aggregate_order_by: Option<Vec<OperateFunctionArg>>,
5489 pub aggregate_star: bool,
5493 pub operation: AlterFunctionOperation,
5495}
5496
5497#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5499#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5500#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5501pub enum AlterFunctionKind {
5502 Function,
5504 Aggregate,
5506}
5507
5508impl fmt::Display for AlterFunctionKind {
5509 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5510 match self {
5511 Self::Function => write!(f, "FUNCTION"),
5512 Self::Aggregate => write!(f, "AGGREGATE"),
5513 }
5514 }
5515}
5516
5517#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5519#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5520#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5521pub enum AlterFunctionOperation {
5522 RenameTo {
5524 new_name: Ident,
5526 },
5527 OwnerTo(Owner),
5529 SetSchema {
5531 schema_name: ObjectName,
5533 },
5534 DependsOnExtension {
5536 no: bool,
5538 extension_name: ObjectName,
5540 },
5541 Actions {
5543 actions: Vec<AlterFunctionAction>,
5545 restrict: bool,
5547 },
5548}
5549
5550#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5552#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5553#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5554pub enum AlterFunctionAction {
5555 CalledOnNull(FunctionCalledOnNull),
5557 Behavior(FunctionBehavior),
5559 Leakproof(bool),
5561 Security {
5563 external: bool,
5565 security: FunctionSecurity,
5567 },
5568 Parallel(FunctionParallel),
5570 Cost(Expr),
5572 Rows(Expr),
5574 Support(ObjectName),
5576 Set(FunctionDefinitionSetParam),
5579 Reset(ResetConfig),
5581}
5582
5583impl fmt::Display for AlterFunction {
5584 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5585 write!(f, "ALTER {} ", self.kind)?;
5586 match self.kind {
5587 AlterFunctionKind::Function => {
5588 write!(f, "{} ", self.function)?;
5589 }
5590 AlterFunctionKind::Aggregate => {
5591 write!(f, "{}(", self.function.name)?;
5592 if self.aggregate_star {
5593 write!(f, "*")?;
5594 } else {
5595 if let Some(args) = &self.function.args {
5596 write!(f, "{}", display_comma_separated(args))?;
5597 }
5598 if let Some(order_by_args) = &self.aggregate_order_by {
5599 if self
5600 .function
5601 .args
5602 .as_ref()
5603 .is_some_and(|args| !args.is_empty())
5604 {
5605 write!(f, " ")?;
5606 }
5607 write!(f, "ORDER BY {}", display_comma_separated(order_by_args))?;
5608 }
5609 }
5610 write!(f, ") ")?;
5611 }
5612 }
5613 write!(f, "{}", self.operation)
5614 }
5615}
5616
5617impl fmt::Display for AlterFunctionOperation {
5618 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5619 match self {
5620 AlterFunctionOperation::RenameTo { new_name } => {
5621 write!(f, "RENAME TO {new_name}")
5622 }
5623 AlterFunctionOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
5624 AlterFunctionOperation::SetSchema { schema_name } => {
5625 write!(f, "SET SCHEMA {schema_name}")
5626 }
5627 AlterFunctionOperation::DependsOnExtension { no, extension_name } => {
5628 if *no {
5629 write!(f, "NO DEPENDS ON EXTENSION {extension_name}")
5630 } else {
5631 write!(f, "DEPENDS ON EXTENSION {extension_name}")
5632 }
5633 }
5634 AlterFunctionOperation::Actions { actions, restrict } => {
5635 write!(f, "{}", display_separated(actions, " "))?;
5636 if *restrict {
5637 write!(f, " RESTRICT")?;
5638 }
5639 Ok(())
5640 }
5641 }
5642 }
5643}
5644
5645impl fmt::Display for AlterFunctionAction {
5646 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5647 match self {
5648 AlterFunctionAction::CalledOnNull(called_on_null) => write!(f, "{called_on_null}"),
5649 AlterFunctionAction::Behavior(behavior) => write!(f, "{behavior}"),
5650 AlterFunctionAction::Leakproof(leakproof) => {
5651 if *leakproof {
5652 write!(f, "LEAKPROOF")
5653 } else {
5654 write!(f, "NOT LEAKPROOF")
5655 }
5656 }
5657 AlterFunctionAction::Security { external, security } => {
5658 if *external {
5659 write!(f, "EXTERNAL ")?;
5660 }
5661 write!(f, "{security}")
5662 }
5663 AlterFunctionAction::Parallel(parallel) => write!(f, "{parallel}"),
5664 AlterFunctionAction::Cost(execution_cost) => write!(f, "COST {execution_cost}"),
5665 AlterFunctionAction::Rows(result_rows) => write!(f, "ROWS {result_rows}"),
5666 AlterFunctionAction::Support(support_function) => {
5667 write!(f, "SUPPORT {support_function}")
5668 }
5669 AlterFunctionAction::Set(set_param) => write!(f, "{set_param}"),
5670 AlterFunctionAction::Reset(reset_config) => match reset_config {
5671 ResetConfig::ALL => write!(f, "RESET ALL"),
5672 ResetConfig::ConfigName(name) => write!(f, "RESET {name}"),
5673 },
5674 }
5675 }
5676}
5677
5678impl Spanned for AlterFunction {
5679 fn span(&self) -> Span {
5680 Span::empty()
5681 }
5682}
5683
5684#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5688#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5689#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5690pub struct CreatePolicy {
5691 pub name: Ident,
5693 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5695 pub table_name: ObjectName,
5696 pub policy_type: Option<CreatePolicyType>,
5698 pub command: Option<CreatePolicyCommand>,
5700 pub to: Option<Vec<Owner>>,
5702 pub using: Option<Expr>,
5704 pub with_check: Option<Expr>,
5706}
5707
5708impl fmt::Display for CreatePolicy {
5709 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5710 write!(
5711 f,
5712 "CREATE POLICY {name} ON {table_name}",
5713 name = self.name,
5714 table_name = self.table_name,
5715 )?;
5716 if let Some(ref policy_type) = self.policy_type {
5717 write!(f, " AS {policy_type}")?;
5718 }
5719 if let Some(ref command) = self.command {
5720 write!(f, " FOR {command}")?;
5721 }
5722 if let Some(ref to) = self.to {
5723 write!(f, " TO {}", display_comma_separated(to))?;
5724 }
5725 if let Some(ref using) = self.using {
5726 write!(f, " USING ({using})")?;
5727 }
5728 if let Some(ref with_check) = self.with_check {
5729 write!(f, " WITH CHECK ({with_check})")?;
5730 }
5731 Ok(())
5732 }
5733}
5734
5735#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5741#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5742#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5743pub enum CreatePolicyType {
5744 Permissive,
5746 Restrictive,
5748}
5749
5750impl fmt::Display for CreatePolicyType {
5751 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5752 match self {
5753 CreatePolicyType::Permissive => write!(f, "PERMISSIVE"),
5754 CreatePolicyType::Restrictive => write!(f, "RESTRICTIVE"),
5755 }
5756 }
5757}
5758
5759#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5765#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5766#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5767pub enum CreatePolicyCommand {
5768 All,
5770 Select,
5772 Insert,
5774 Update,
5776 Delete,
5778}
5779
5780impl fmt::Display for CreatePolicyCommand {
5781 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5782 match self {
5783 CreatePolicyCommand::All => write!(f, "ALL"),
5784 CreatePolicyCommand::Select => write!(f, "SELECT"),
5785 CreatePolicyCommand::Insert => write!(f, "INSERT"),
5786 CreatePolicyCommand::Update => write!(f, "UPDATE"),
5787 CreatePolicyCommand::Delete => write!(f, "DELETE"),
5788 }
5789 }
5790}
5791
5792#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5796#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5797#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5798pub struct DropPolicy {
5799 pub if_exists: bool,
5801 pub name: Ident,
5803 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5805 pub table_name: ObjectName,
5806 pub drop_behavior: Option<DropBehavior>,
5808}
5809
5810impl fmt::Display for DropPolicy {
5811 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5812 write!(
5813 f,
5814 "DROP POLICY {if_exists}{name} ON {table_name}",
5815 if_exists = if self.if_exists { "IF EXISTS " } else { "" },
5816 name = self.name,
5817 table_name = self.table_name
5818 )?;
5819 if let Some(ref behavior) = self.drop_behavior {
5820 write!(f, " {behavior}")?;
5821 }
5822 Ok(())
5823 }
5824}
5825
5826impl From<CreatePolicy> for crate::ast::Statement {
5827 fn from(v: CreatePolicy) -> Self {
5828 crate::ast::Statement::CreatePolicy(v)
5829 }
5830}
5831
5832impl From<DropPolicy> for crate::ast::Statement {
5833 fn from(v: DropPolicy) -> Self {
5834 crate::ast::Statement::DropPolicy(v)
5835 }
5836}
5837
5838#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5845#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5846#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5847pub struct AlterPolicy {
5848 pub name: Ident,
5850 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5852 pub table_name: ObjectName,
5853 pub operation: AlterPolicyOperation,
5855}
5856
5857impl fmt::Display for AlterPolicy {
5858 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5859 write!(
5860 f,
5861 "ALTER POLICY {name} ON {table_name}{operation}",
5862 name = self.name,
5863 table_name = self.table_name,
5864 operation = self.operation
5865 )
5866 }
5867}
5868
5869impl From<AlterPolicy> for crate::ast::Statement {
5870 fn from(v: AlterPolicy) -> Self {
5871 crate::ast::Statement::AlterPolicy(v)
5872 }
5873}