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 SetDataType {
1283 data_type: DataType,
1285 using: Option<Expr>,
1287 had_set: bool,
1289 },
1290
1291 AddGenerated {
1295 generated_as: Option<GeneratedAs>,
1297 sequence_options: Option<Vec<SequenceOptions>>,
1299 },
1300}
1301
1302impl fmt::Display for AlterColumnOperation {
1303 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1304 match self {
1305 AlterColumnOperation::SetNotNull => write!(f, "SET NOT NULL",),
1306 AlterColumnOperation::DropNotNull => write!(f, "DROP NOT NULL",),
1307 AlterColumnOperation::SetDefault { value } => {
1308 write!(f, "SET DEFAULT {value}")
1309 }
1310 AlterColumnOperation::DropDefault => {
1311 write!(f, "DROP DEFAULT")
1312 }
1313 AlterColumnOperation::SetDataType {
1314 data_type,
1315 using,
1316 had_set,
1317 } => {
1318 if *had_set {
1319 write!(f, "SET DATA ")?;
1320 }
1321 write!(f, "TYPE {data_type}")?;
1322 if let Some(expr) = using {
1323 write!(f, " USING {expr}")?;
1324 }
1325 Ok(())
1326 }
1327 AlterColumnOperation::AddGenerated {
1328 generated_as,
1329 sequence_options,
1330 } => {
1331 let generated_as = match generated_as {
1332 Some(GeneratedAs::Always) => " ALWAYS",
1333 Some(GeneratedAs::ByDefault) => " BY DEFAULT",
1334 _ => "",
1335 };
1336
1337 write!(f, "ADD GENERATED{generated_as} AS IDENTITY",)?;
1338 if let Some(options) = sequence_options {
1339 write!(f, " (")?;
1340
1341 for sequence_option in options {
1342 write!(f, "{sequence_option}")?;
1343 }
1344
1345 write!(f, " )")?;
1346 }
1347 Ok(())
1348 }
1349 }
1350 }
1351}
1352
1353#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1361#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1362#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1363pub enum KeyOrIndexDisplay {
1364 None,
1366 Key,
1368 Index,
1370}
1371
1372impl KeyOrIndexDisplay {
1373 pub fn is_none(self) -> bool {
1375 matches!(self, Self::None)
1376 }
1377}
1378
1379impl fmt::Display for KeyOrIndexDisplay {
1380 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1381 let left_space = matches!(f.align(), Some(fmt::Alignment::Right));
1382
1383 if left_space && !self.is_none() {
1384 f.write_char(' ')?
1385 }
1386
1387 match self {
1388 KeyOrIndexDisplay::None => {
1389 write!(f, "")
1390 }
1391 KeyOrIndexDisplay::Key => {
1392 write!(f, "KEY")
1393 }
1394 KeyOrIndexDisplay::Index => {
1395 write!(f, "INDEX")
1396 }
1397 }
1398 }
1399}
1400
1401#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1410#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1411#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1412pub enum IndexType {
1413 BTree,
1415 Hash,
1417 GIN,
1419 GiST,
1421 SPGiST,
1423 BRIN,
1425 Bloom,
1427 Custom(Ident),
1430}
1431
1432impl fmt::Display for IndexType {
1433 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1434 match self {
1435 Self::BTree => write!(f, "BTREE"),
1436 Self::Hash => write!(f, "HASH"),
1437 Self::GIN => write!(f, "GIN"),
1438 Self::GiST => write!(f, "GIST"),
1439 Self::SPGiST => write!(f, "SPGIST"),
1440 Self::BRIN => write!(f, "BRIN"),
1441 Self::Bloom => write!(f, "BLOOM"),
1442 Self::Custom(name) => write!(f, "{name}"),
1443 }
1444 }
1445}
1446
1447#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1453#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1454#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1455pub enum IndexOption {
1456 Using(IndexType),
1460 Comment(String),
1462}
1463
1464impl fmt::Display for IndexOption {
1465 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1466 match self {
1467 Self::Using(index_type) => write!(f, "USING {index_type}"),
1468 Self::Comment(s) => write!(f, "COMMENT '{s}'"),
1469 }
1470 }
1471}
1472
1473#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1477#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1478#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1479pub enum NullsDistinctOption {
1480 None,
1482 Distinct,
1484 NotDistinct,
1486}
1487
1488impl fmt::Display for NullsDistinctOption {
1489 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1490 match self {
1491 Self::None => Ok(()),
1492 Self::Distinct => write!(f, " NULLS DISTINCT"),
1493 Self::NotDistinct => write!(f, " NULLS NOT DISTINCT"),
1494 }
1495 }
1496}
1497
1498#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1499#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1500#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1501pub struct ProcedureParam {
1503 pub name: Ident,
1505 pub data_type: DataType,
1507 pub mode: Option<ArgMode>,
1509 pub default: Option<Expr>,
1511}
1512
1513impl fmt::Display for ProcedureParam {
1514 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1515 if let Some(mode) = &self.mode {
1516 if let Some(default) = &self.default {
1517 write!(f, "{mode} {} {} = {}", self.name, self.data_type, default)
1518 } else {
1519 write!(f, "{mode} {} {}", self.name, self.data_type)
1520 }
1521 } else if let Some(default) = &self.default {
1522 write!(f, "{} {} = {}", self.name, self.data_type, default)
1523 } else {
1524 write!(f, "{} {}", self.name, self.data_type)
1525 }
1526 }
1527}
1528
1529#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1531#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1532#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1533pub struct ColumnDef {
1534 pub name: Ident,
1536 pub data_type: DataType,
1538 pub options: Vec<ColumnOptionDef>,
1540}
1541
1542impl fmt::Display for ColumnDef {
1543 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1544 if self.data_type == DataType::Unspecified {
1545 write!(f, "{}", self.name)?;
1546 } else {
1547 write!(f, "{} {}", self.name, self.data_type)?;
1548 }
1549 for option in &self.options {
1550 write!(f, " {option}")?;
1551 }
1552 Ok(())
1553 }
1554}
1555
1556#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1573#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1574#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1575pub struct ViewColumnDef {
1576 pub name: Ident,
1578 pub data_type: Option<DataType>,
1580 pub options: Option<ColumnOptions>,
1582}
1583
1584#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1585#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1586#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1587pub enum ColumnOptions {
1589 CommaSeparated(Vec<ColumnOption>),
1591 SpaceSeparated(Vec<ColumnOption>),
1593}
1594
1595impl ColumnOptions {
1596 pub fn as_slice(&self) -> &[ColumnOption] {
1598 match self {
1599 ColumnOptions::CommaSeparated(options) => options.as_slice(),
1600 ColumnOptions::SpaceSeparated(options) => options.as_slice(),
1601 }
1602 }
1603}
1604
1605impl fmt::Display for ViewColumnDef {
1606 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1607 write!(f, "{}", self.name)?;
1608 if let Some(data_type) = self.data_type.as_ref() {
1609 write!(f, " {data_type}")?;
1610 }
1611 if let Some(options) = self.options.as_ref() {
1612 match options {
1613 ColumnOptions::CommaSeparated(column_options) => {
1614 write!(f, " {}", display_comma_separated(column_options.as_slice()))?;
1615 }
1616 ColumnOptions::SpaceSeparated(column_options) => {
1617 write!(f, " {}", display_separated(column_options.as_slice(), " "))?
1618 }
1619 }
1620 }
1621 Ok(())
1622 }
1623}
1624
1625#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1642#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1643#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1644pub struct ColumnOptionDef {
1645 pub name: Option<Ident>,
1647 pub option: ColumnOption,
1649}
1650
1651impl fmt::Display for ColumnOptionDef {
1652 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1653 write!(f, "{}{}", display_constraint_name(&self.name), self.option)
1654 }
1655}
1656
1657#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1665#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1666#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1667pub enum IdentityPropertyKind {
1668 Autoincrement(IdentityProperty),
1676 Identity(IdentityProperty),
1689}
1690
1691impl fmt::Display for IdentityPropertyKind {
1692 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1693 let (command, property) = match self {
1694 IdentityPropertyKind::Identity(property) => ("IDENTITY", property),
1695 IdentityPropertyKind::Autoincrement(property) => ("AUTOINCREMENT", property),
1696 };
1697 write!(f, "{command}")?;
1698 if let Some(parameters) = &property.parameters {
1699 write!(f, "{parameters}")?;
1700 }
1701 if let Some(order) = &property.order {
1702 write!(f, "{order}")?;
1703 }
1704 Ok(())
1705 }
1706}
1707
1708#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1710#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1711#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1712pub struct IdentityProperty {
1713 pub parameters: Option<IdentityPropertyFormatKind>,
1715 pub order: Option<IdentityPropertyOrder>,
1717}
1718
1719#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1734#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1735#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1736pub enum IdentityPropertyFormatKind {
1737 FunctionCall(IdentityParameters),
1745 StartAndIncrement(IdentityParameters),
1752}
1753
1754impl fmt::Display for IdentityPropertyFormatKind {
1755 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1756 match self {
1757 IdentityPropertyFormatKind::FunctionCall(parameters) => {
1758 write!(f, "({}, {})", parameters.seed, parameters.increment)
1759 }
1760 IdentityPropertyFormatKind::StartAndIncrement(parameters) => {
1761 write!(
1762 f,
1763 " START {} INCREMENT {}",
1764 parameters.seed, parameters.increment
1765 )
1766 }
1767 }
1768 }
1769}
1770#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1772#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1773#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1774pub struct IdentityParameters {
1775 pub seed: Expr,
1777 pub increment: Expr,
1779}
1780
1781#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1788#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1789#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1790pub enum IdentityPropertyOrder {
1791 Order,
1793 NoOrder,
1795}
1796
1797impl fmt::Display for IdentityPropertyOrder {
1798 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1799 match self {
1800 IdentityPropertyOrder::Order => write!(f, " ORDER"),
1801 IdentityPropertyOrder::NoOrder => write!(f, " NOORDER"),
1802 }
1803 }
1804}
1805
1806#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1814#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1815#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1816pub enum ColumnPolicy {
1817 MaskingPolicy(ColumnPolicyProperty),
1819 ProjectionPolicy(ColumnPolicyProperty),
1821}
1822
1823impl fmt::Display for ColumnPolicy {
1824 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1825 let (command, property) = match self {
1826 ColumnPolicy::MaskingPolicy(property) => ("MASKING POLICY", property),
1827 ColumnPolicy::ProjectionPolicy(property) => ("PROJECTION POLICY", property),
1828 };
1829 if property.with {
1830 write!(f, "WITH ")?;
1831 }
1832 write!(f, "{command} {}", property.policy_name)?;
1833 if let Some(using_columns) = &property.using_columns {
1834 write!(f, " USING ({})", display_comma_separated(using_columns))?;
1835 }
1836 Ok(())
1837 }
1838}
1839
1840#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1841#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1842#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1843pub struct ColumnPolicyProperty {
1845 pub with: bool,
1852 pub policy_name: ObjectName,
1854 pub using_columns: Option<Vec<Ident>>,
1856}
1857
1858#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1865#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1866#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1867pub struct TagsColumnOption {
1868 pub with: bool,
1875 pub tags: Vec<Tag>,
1877}
1878
1879impl fmt::Display for TagsColumnOption {
1880 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1881 if self.with {
1882 write!(f, "WITH ")?;
1883 }
1884 write!(f, "TAG ({})", display_comma_separated(&self.tags))?;
1885 Ok(())
1886 }
1887}
1888
1889#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1892#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1893#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1894pub enum ColumnOption {
1895 Null,
1897 NotNull,
1899 Default(Expr),
1901
1902 Materialized(Expr),
1907 Ephemeral(Option<Expr>),
1911 Alias(Expr),
1915
1916 PrimaryKey(PrimaryKeyConstraint),
1918 Unique(UniqueConstraint),
1920 ForeignKey(ForeignKeyConstraint),
1928 Check(CheckConstraint),
1930 DialectSpecific(Vec<Token>),
1934 CharacterSet(ObjectName),
1936 Collation(ObjectName),
1938 Comment(String),
1940 OnUpdate(Expr),
1942 Generated {
1945 generated_as: GeneratedAs,
1947 sequence_options: Option<Vec<SequenceOptions>>,
1949 generation_expr: Option<Expr>,
1951 generation_expr_mode: Option<GeneratedExpressionMode>,
1953 generated_keyword: bool,
1955 },
1956 Options(Vec<SqlOption>),
1964 Identity(IdentityPropertyKind),
1972 OnConflict(Keyword),
1975 Policy(ColumnPolicy),
1983 Tags(TagsColumnOption),
1990 Srid(Box<Expr>),
1997 Invisible,
2004}
2005
2006impl From<UniqueConstraint> for ColumnOption {
2007 fn from(c: UniqueConstraint) -> Self {
2008 ColumnOption::Unique(c)
2009 }
2010}
2011
2012impl From<PrimaryKeyConstraint> for ColumnOption {
2013 fn from(c: PrimaryKeyConstraint) -> Self {
2014 ColumnOption::PrimaryKey(c)
2015 }
2016}
2017
2018impl From<CheckConstraint> for ColumnOption {
2019 fn from(c: CheckConstraint) -> Self {
2020 ColumnOption::Check(c)
2021 }
2022}
2023impl From<ForeignKeyConstraint> for ColumnOption {
2024 fn from(fk: ForeignKeyConstraint) -> Self {
2025 ColumnOption::ForeignKey(fk)
2026 }
2027}
2028
2029impl fmt::Display for ColumnOption {
2030 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2031 use ColumnOption::*;
2032 match self {
2033 Null => write!(f, "NULL"),
2034 NotNull => write!(f, "NOT NULL"),
2035 Default(expr) => write!(f, "DEFAULT {expr}"),
2036 Materialized(expr) => write!(f, "MATERIALIZED {expr}"),
2037 Ephemeral(expr) => {
2038 if let Some(e) = expr {
2039 write!(f, "EPHEMERAL {e}")
2040 } else {
2041 write!(f, "EPHEMERAL")
2042 }
2043 }
2044 Alias(expr) => write!(f, "ALIAS {expr}"),
2045 PrimaryKey(constraint) => {
2046 write!(f, "PRIMARY KEY")?;
2047 if let Some(characteristics) = &constraint.characteristics {
2048 write!(f, " {characteristics}")?;
2049 }
2050 Ok(())
2051 }
2052 Unique(constraint) => {
2053 write!(f, "UNIQUE{:>}", constraint.index_type_display)?;
2054 if let Some(characteristics) = &constraint.characteristics {
2055 write!(f, " {characteristics}")?;
2056 }
2057 Ok(())
2058 }
2059 ForeignKey(constraint) => {
2060 write!(f, "REFERENCES {}", constraint.foreign_table)?;
2061 if !constraint.referred_columns.is_empty() {
2062 write!(
2063 f,
2064 " ({})",
2065 display_comma_separated(&constraint.referred_columns)
2066 )?;
2067 }
2068 if let Some(match_kind) = &constraint.match_kind {
2069 write!(f, " {match_kind}")?;
2070 }
2071 if let Some(action) = &constraint.on_delete {
2072 write!(f, " ON DELETE {action}")?;
2073 }
2074 if let Some(action) = &constraint.on_update {
2075 write!(f, " ON UPDATE {action}")?;
2076 }
2077 if let Some(characteristics) = &constraint.characteristics {
2078 write!(f, " {characteristics}")?;
2079 }
2080 Ok(())
2081 }
2082 Check(constraint) => write!(f, "{constraint}"),
2083 DialectSpecific(val) => write!(f, "{}", display_separated(val, " ")),
2084 CharacterSet(n) => write!(f, "CHARACTER SET {n}"),
2085 Collation(n) => write!(f, "COLLATE {n}"),
2086 Comment(v) => write!(f, "COMMENT '{}'", escape_single_quote_string(v)),
2087 OnUpdate(expr) => write!(f, "ON UPDATE {expr}"),
2088 Generated {
2089 generated_as,
2090 sequence_options,
2091 generation_expr,
2092 generation_expr_mode,
2093 generated_keyword,
2094 } => {
2095 if let Some(expr) = generation_expr {
2096 let modifier = match generation_expr_mode {
2097 None => "",
2098 Some(GeneratedExpressionMode::Virtual) => " VIRTUAL",
2099 Some(GeneratedExpressionMode::Stored) => " STORED",
2100 };
2101 if *generated_keyword {
2102 write!(f, "GENERATED ALWAYS AS ({expr}){modifier}")?;
2103 } else {
2104 write!(f, "AS ({expr}){modifier}")?;
2105 }
2106 Ok(())
2107 } else {
2108 let when = match generated_as {
2110 GeneratedAs::Always => "ALWAYS",
2111 GeneratedAs::ByDefault => "BY DEFAULT",
2112 GeneratedAs::ExpStored => "",
2114 };
2115 write!(f, "GENERATED {when} AS IDENTITY")?;
2116 if let Some(so) = sequence_options {
2117 if !so.is_empty() {
2118 write!(f, " (")?;
2119 }
2120 for sequence_option in so {
2121 write!(f, "{sequence_option}")?;
2122 }
2123 if !so.is_empty() {
2124 write!(f, " )")?;
2125 }
2126 }
2127 Ok(())
2128 }
2129 }
2130 Options(options) => {
2131 write!(f, "OPTIONS({})", display_comma_separated(options))
2132 }
2133 Identity(parameters) => {
2134 write!(f, "{parameters}")
2135 }
2136 OnConflict(keyword) => {
2137 write!(f, "ON CONFLICT {keyword:?}")?;
2138 Ok(())
2139 }
2140 Policy(parameters) => {
2141 write!(f, "{parameters}")
2142 }
2143 Tags(tags) => {
2144 write!(f, "{tags}")
2145 }
2146 Srid(srid) => {
2147 write!(f, "SRID {srid}")
2148 }
2149 Invisible => {
2150 write!(f, "INVISIBLE")
2151 }
2152 }
2153 }
2154}
2155
2156#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2159#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2160#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2161pub enum GeneratedAs {
2162 Always,
2164 ByDefault,
2166 ExpStored,
2168}
2169
2170#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2173#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2174#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2175pub enum GeneratedExpressionMode {
2176 Virtual,
2178 Stored,
2180}
2181
2182#[must_use]
2183pub(crate) fn display_constraint_name(name: &'_ Option<Ident>) -> impl fmt::Display + '_ {
2184 struct ConstraintName<'a>(&'a Option<Ident>);
2185 impl fmt::Display for ConstraintName<'_> {
2186 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2187 if let Some(name) = self.0 {
2188 write!(f, "CONSTRAINT {name} ")?;
2189 }
2190 Ok(())
2191 }
2192 }
2193 ConstraintName(name)
2194}
2195
2196#[must_use]
2200pub(crate) fn display_option<'a, T: fmt::Display>(
2201 prefix: &'a str,
2202 postfix: &'a str,
2203 option: &'a Option<T>,
2204) -> impl fmt::Display + 'a {
2205 struct OptionDisplay<'a, T>(&'a str, &'a str, &'a Option<T>);
2206 impl<T: fmt::Display> fmt::Display for OptionDisplay<'_, T> {
2207 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2208 if let Some(inner) = self.2 {
2209 let (prefix, postfix) = (self.0, self.1);
2210 write!(f, "{prefix}{inner}{postfix}")?;
2211 }
2212 Ok(())
2213 }
2214 }
2215 OptionDisplay(prefix, postfix, option)
2216}
2217
2218#[must_use]
2222pub(crate) fn display_option_spaced<T: fmt::Display>(option: &Option<T>) -> impl fmt::Display + '_ {
2223 display_option(" ", "", option)
2224}
2225
2226#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Default, Eq, Ord, Hash)]
2230#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2231#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2232pub struct ConstraintCharacteristics {
2233 pub deferrable: Option<bool>,
2235 pub initially: Option<DeferrableInitial>,
2237 pub enforced: Option<bool>,
2239}
2240
2241#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2243#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2244#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2245pub enum DeferrableInitial {
2246 Immediate,
2248 Deferred,
2250}
2251
2252impl ConstraintCharacteristics {
2253 fn deferrable_text(&self) -> Option<&'static str> {
2254 self.deferrable.map(|deferrable| {
2255 if deferrable {
2256 "DEFERRABLE"
2257 } else {
2258 "NOT DEFERRABLE"
2259 }
2260 })
2261 }
2262
2263 fn initially_immediate_text(&self) -> Option<&'static str> {
2264 self.initially
2265 .map(|initially_immediate| match initially_immediate {
2266 DeferrableInitial::Immediate => "INITIALLY IMMEDIATE",
2267 DeferrableInitial::Deferred => "INITIALLY DEFERRED",
2268 })
2269 }
2270
2271 fn enforced_text(&self) -> Option<&'static str> {
2272 self.enforced.map(
2273 |enforced| {
2274 if enforced {
2275 "ENFORCED"
2276 } else {
2277 "NOT ENFORCED"
2278 }
2279 },
2280 )
2281 }
2282}
2283
2284impl fmt::Display for ConstraintCharacteristics {
2285 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2286 let deferrable = self.deferrable_text();
2287 let initially_immediate = self.initially_immediate_text();
2288 let enforced = self.enforced_text();
2289
2290 match (deferrable, initially_immediate, enforced) {
2291 (None, None, None) => Ok(()),
2292 (None, None, Some(enforced)) => write!(f, "{enforced}"),
2293 (None, Some(initial), None) => write!(f, "{initial}"),
2294 (None, Some(initial), Some(enforced)) => write!(f, "{initial} {enforced}"),
2295 (Some(deferrable), None, None) => write!(f, "{deferrable}"),
2296 (Some(deferrable), None, Some(enforced)) => write!(f, "{deferrable} {enforced}"),
2297 (Some(deferrable), Some(initial), None) => write!(f, "{deferrable} {initial}"),
2298 (Some(deferrable), Some(initial), Some(enforced)) => {
2299 write!(f, "{deferrable} {initial} {enforced}")
2300 }
2301 }
2302 }
2303}
2304
2305#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2310#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2311#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2312pub enum ReferentialAction {
2313 Restrict,
2315 Cascade,
2317 SetNull,
2319 NoAction,
2321 SetDefault,
2323}
2324
2325impl fmt::Display for ReferentialAction {
2326 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2327 f.write_str(match self {
2328 ReferentialAction::Restrict => "RESTRICT",
2329 ReferentialAction::Cascade => "CASCADE",
2330 ReferentialAction::SetNull => "SET NULL",
2331 ReferentialAction::NoAction => "NO ACTION",
2332 ReferentialAction::SetDefault => "SET DEFAULT",
2333 })
2334 }
2335}
2336
2337#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2341#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2342#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2343pub enum DropBehavior {
2344 Restrict,
2346 Cascade,
2348}
2349
2350impl fmt::Display for DropBehavior {
2351 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2352 f.write_str(match self {
2353 DropBehavior::Restrict => "RESTRICT",
2354 DropBehavior::Cascade => "CASCADE",
2355 })
2356 }
2357}
2358
2359#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2361#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2362#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2363pub enum UserDefinedTypeRepresentation {
2364 Composite {
2366 attributes: Vec<UserDefinedTypeCompositeAttributeDef>,
2368 },
2369 Enum {
2374 labels: Vec<Ident>,
2376 },
2377 Range {
2381 options: Vec<UserDefinedTypeRangeOption>,
2383 },
2384 SqlDefinition {
2390 options: Vec<UserDefinedTypeSqlDefinitionOption>,
2392 },
2393}
2394
2395impl fmt::Display for UserDefinedTypeRepresentation {
2396 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2397 match self {
2398 Self::Composite { attributes } => {
2399 write!(f, "AS ({})", display_comma_separated(attributes))
2400 }
2401 Self::Enum { labels } => {
2402 write!(f, "AS ENUM ({})", display_comma_separated(labels))
2403 }
2404 Self::Range { options } => {
2405 write!(f, "AS RANGE ({})", display_comma_separated(options))
2406 }
2407 Self::SqlDefinition { options } => {
2408 write!(f, "({})", display_comma_separated(options))
2409 }
2410 }
2411 }
2412}
2413
2414#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2416#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2417#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2418pub struct UserDefinedTypeCompositeAttributeDef {
2419 pub name: Ident,
2421 pub data_type: DataType,
2423 pub collation: Option<ObjectName>,
2425}
2426
2427impl fmt::Display for UserDefinedTypeCompositeAttributeDef {
2428 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2429 write!(f, "{} {}", self.name, self.data_type)?;
2430 if let Some(collation) = &self.collation {
2431 write!(f, " COLLATE {collation}")?;
2432 }
2433 Ok(())
2434 }
2435}
2436
2437#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2460#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2461#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2462pub enum UserDefinedTypeInternalLength {
2463 Fixed(u64),
2465 Variable,
2467}
2468
2469impl fmt::Display for UserDefinedTypeInternalLength {
2470 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2471 match self {
2472 UserDefinedTypeInternalLength::Fixed(n) => write!(f, "{}", n),
2473 UserDefinedTypeInternalLength::Variable => write!(f, "VARIABLE"),
2474 }
2475 }
2476}
2477
2478#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2497#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2498#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2499pub enum Alignment {
2500 Char,
2502 Int2,
2504 Int4,
2506 Double,
2508}
2509
2510impl fmt::Display for Alignment {
2511 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2512 match self {
2513 Alignment::Char => write!(f, "char"),
2514 Alignment::Int2 => write!(f, "int2"),
2515 Alignment::Int4 => write!(f, "int4"),
2516 Alignment::Double => write!(f, "double"),
2517 }
2518 }
2519}
2520
2521#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2541#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2542#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2543pub enum UserDefinedTypeStorage {
2544 Plain,
2546 External,
2548 Extended,
2550 Main,
2552}
2553
2554impl fmt::Display for UserDefinedTypeStorage {
2555 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2556 match self {
2557 UserDefinedTypeStorage::Plain => write!(f, "plain"),
2558 UserDefinedTypeStorage::External => write!(f, "external"),
2559 UserDefinedTypeStorage::Extended => write!(f, "extended"),
2560 UserDefinedTypeStorage::Main => write!(f, "main"),
2561 }
2562 }
2563}
2564
2565#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2583#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2584#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2585pub enum UserDefinedTypeRangeOption {
2586 Subtype(DataType),
2588 SubtypeOpClass(ObjectName),
2590 Collation(ObjectName),
2592 Canonical(ObjectName),
2594 SubtypeDiff(ObjectName),
2596 MultirangeTypeName(ObjectName),
2598}
2599
2600impl fmt::Display for UserDefinedTypeRangeOption {
2601 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2602 match self {
2603 UserDefinedTypeRangeOption::Subtype(dt) => write!(f, "SUBTYPE = {}", dt),
2604 UserDefinedTypeRangeOption::SubtypeOpClass(name) => {
2605 write!(f, "SUBTYPE_OPCLASS = {}", name)
2606 }
2607 UserDefinedTypeRangeOption::Collation(name) => write!(f, "COLLATION = {}", name),
2608 UserDefinedTypeRangeOption::Canonical(name) => write!(f, "CANONICAL = {}", name),
2609 UserDefinedTypeRangeOption::SubtypeDiff(name) => write!(f, "SUBTYPE_DIFF = {}", name),
2610 UserDefinedTypeRangeOption::MultirangeTypeName(name) => {
2611 write!(f, "MULTIRANGE_TYPE_NAME = {}", name)
2612 }
2613 }
2614 }
2615}
2616
2617#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2638#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2639#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2640pub enum UserDefinedTypeSqlDefinitionOption {
2641 Input(ObjectName),
2643 Output(ObjectName),
2645 Receive(ObjectName),
2647 Send(ObjectName),
2649 TypmodIn(ObjectName),
2651 TypmodOut(ObjectName),
2653 Analyze(ObjectName),
2655 Subscript(ObjectName),
2657 InternalLength(UserDefinedTypeInternalLength),
2659 PassedByValue,
2661 Alignment(Alignment),
2663 Storage(UserDefinedTypeStorage),
2665 Like(ObjectName),
2667 Category(char),
2669 Preferred(bool),
2671 Default(Expr),
2673 Element(DataType),
2675 Delimiter(String),
2677 Collatable(bool),
2679}
2680
2681impl fmt::Display for UserDefinedTypeSqlDefinitionOption {
2682 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2683 match self {
2684 UserDefinedTypeSqlDefinitionOption::Input(name) => write!(f, "INPUT = {}", name),
2685 UserDefinedTypeSqlDefinitionOption::Output(name) => write!(f, "OUTPUT = {}", name),
2686 UserDefinedTypeSqlDefinitionOption::Receive(name) => write!(f, "RECEIVE = {}", name),
2687 UserDefinedTypeSqlDefinitionOption::Send(name) => write!(f, "SEND = {}", name),
2688 UserDefinedTypeSqlDefinitionOption::TypmodIn(name) => write!(f, "TYPMOD_IN = {}", name),
2689 UserDefinedTypeSqlDefinitionOption::TypmodOut(name) => {
2690 write!(f, "TYPMOD_OUT = {}", name)
2691 }
2692 UserDefinedTypeSqlDefinitionOption::Analyze(name) => write!(f, "ANALYZE = {}", name),
2693 UserDefinedTypeSqlDefinitionOption::Subscript(name) => {
2694 write!(f, "SUBSCRIPT = {}", name)
2695 }
2696 UserDefinedTypeSqlDefinitionOption::InternalLength(len) => {
2697 write!(f, "INTERNALLENGTH = {}", len)
2698 }
2699 UserDefinedTypeSqlDefinitionOption::PassedByValue => write!(f, "PASSEDBYVALUE"),
2700 UserDefinedTypeSqlDefinitionOption::Alignment(align) => {
2701 write!(f, "ALIGNMENT = {}", align)
2702 }
2703 UserDefinedTypeSqlDefinitionOption::Storage(storage) => {
2704 write!(f, "STORAGE = {}", storage)
2705 }
2706 UserDefinedTypeSqlDefinitionOption::Like(name) => write!(f, "LIKE = {}", name),
2707 UserDefinedTypeSqlDefinitionOption::Category(c) => write!(f, "CATEGORY = '{}'", c),
2708 UserDefinedTypeSqlDefinitionOption::Preferred(b) => write!(f, "PREFERRED = {}", b),
2709 UserDefinedTypeSqlDefinitionOption::Default(expr) => write!(f, "DEFAULT = {}", expr),
2710 UserDefinedTypeSqlDefinitionOption::Element(dt) => write!(f, "ELEMENT = {}", dt),
2711 UserDefinedTypeSqlDefinitionOption::Delimiter(s) => {
2712 write!(f, "DELIMITER = '{}'", escape_single_quote_string(s))
2713 }
2714 UserDefinedTypeSqlDefinitionOption::Collatable(b) => write!(f, "COLLATABLE = {}", b),
2715 }
2716 }
2717}
2718
2719#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2723#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2724#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2725pub enum Partition {
2726 Identifier(Ident),
2728 Expr(Expr),
2730 Part(Expr),
2733 Partitions(Vec<Expr>),
2735}
2736
2737impl fmt::Display for Partition {
2738 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2739 match self {
2740 Partition::Identifier(id) => write!(f, "PARTITION ID {id}"),
2741 Partition::Expr(expr) => write!(f, "PARTITION {expr}"),
2742 Partition::Part(expr) => write!(f, "PART {expr}"),
2743 Partition::Partitions(partitions) => {
2744 write!(f, "PARTITION ({})", display_comma_separated(partitions))
2745 }
2746 }
2747 }
2748}
2749
2750#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2753#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2754#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2755pub enum Deduplicate {
2756 All,
2758 ByExpression(Expr),
2760}
2761
2762impl fmt::Display for Deduplicate {
2763 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2764 match self {
2765 Deduplicate::All => write!(f, "DEDUPLICATE"),
2766 Deduplicate::ByExpression(expr) => write!(f, "DEDUPLICATE BY {expr}"),
2767 }
2768 }
2769}
2770
2771#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2776#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2777#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2778pub struct ClusteredBy {
2779 pub columns: Vec<Ident>,
2781 pub sorted_by: Option<Vec<OrderByExpr>>,
2783 pub num_buckets: Value,
2785}
2786
2787impl fmt::Display for ClusteredBy {
2788 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2789 write!(
2790 f,
2791 "CLUSTERED BY ({})",
2792 display_comma_separated(&self.columns)
2793 )?;
2794 if let Some(ref sorted_by) = self.sorted_by {
2795 write!(f, " SORTED BY ({})", display_comma_separated(sorted_by))?;
2796 }
2797 write!(f, " INTO {} BUCKETS", self.num_buckets)
2798 }
2799}
2800
2801#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2803#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2804#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2805pub struct CreateIndex {
2806 pub name: Option<ObjectName>,
2808 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2809 pub table_name: ObjectName,
2811 pub using: Option<IndexType>,
2814 pub columns: Vec<IndexColumn>,
2816 pub unique: bool,
2818 pub concurrently: bool,
2820 pub r#async: bool,
2824 pub if_not_exists: bool,
2826 pub include: Vec<Ident>,
2828 pub nulls_distinct: Option<bool>,
2830 pub with: Vec<Expr>,
2832 pub predicate: Option<Expr>,
2834 pub index_options: Vec<IndexOption>,
2836 pub alter_options: Vec<AlterTableOperation>,
2843}
2844
2845impl fmt::Display for CreateIndex {
2846 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2847 write!(
2848 f,
2849 "CREATE {unique}INDEX {concurrently}{async_}{if_not_exists}",
2850 unique = if self.unique { "UNIQUE " } else { "" },
2851 concurrently = if self.concurrently {
2852 "CONCURRENTLY "
2853 } else {
2854 ""
2855 },
2856 async_ = if self.r#async { "ASYNC " } else { "" },
2857 if_not_exists = if self.if_not_exists {
2858 "IF NOT EXISTS "
2859 } else {
2860 ""
2861 },
2862 )?;
2863 if let Some(value) = &self.name {
2864 write!(f, "{value} ")?;
2865 }
2866 write!(f, "ON {}", self.table_name)?;
2867 if let Some(value) = &self.using {
2868 write!(f, " USING {value} ")?;
2869 }
2870 write!(f, "({})", display_comma_separated(&self.columns))?;
2871 if !self.include.is_empty() {
2872 write!(f, " INCLUDE ({})", display_comma_separated(&self.include))?;
2873 }
2874 if let Some(value) = self.nulls_distinct {
2875 if value {
2876 write!(f, " NULLS DISTINCT")?;
2877 } else {
2878 write!(f, " NULLS NOT DISTINCT")?;
2879 }
2880 }
2881 if !self.with.is_empty() {
2882 write!(f, " WITH ({})", display_comma_separated(&self.with))?;
2883 }
2884 if let Some(predicate) = &self.predicate {
2885 write!(f, " WHERE {predicate}")?;
2886 }
2887 if !self.index_options.is_empty() {
2888 write!(f, " {}", display_separated(&self.index_options, " "))?;
2889 }
2890 if !self.alter_options.is_empty() {
2891 write!(f, " {}", display_separated(&self.alter_options, " "))?;
2892 }
2893 Ok(())
2894 }
2895}
2896
2897#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2899#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2900#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2901pub struct CreateTable {
2902 pub or_replace: bool,
2904 pub temporary: bool,
2906 pub external: bool,
2908 pub dynamic: bool,
2910 pub global: Option<bool>,
2912 pub if_not_exists: bool,
2914 pub transient: bool,
2916 pub volatile: bool,
2918 pub iceberg: bool,
2920 pub snapshot: bool,
2923 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2925 pub name: ObjectName,
2926 pub columns: Vec<ColumnDef>,
2928 pub constraints: Vec<TableConstraint>,
2930 pub hive_distribution: HiveDistributionStyle,
2932 pub hive_formats: Option<HiveFormat>,
2934 pub table_options: CreateTableOptions,
2936 pub file_format: Option<FileFormat>,
2938 pub location: Option<String>,
2940 pub query: Option<Box<Query>>,
2942 pub without_rowid: bool,
2944 pub like: Option<CreateTableLikeKind>,
2946 pub clone: Option<ObjectName>,
2948 pub version: Option<TableVersion>,
2950 pub comment: Option<CommentDef>,
2954 pub on_commit: Option<OnCommit>,
2957 pub on_cluster: Option<Ident>,
2960 pub primary_key: Option<Box<Expr>>,
2963 pub order_by: Option<OneOrManyWithParens<Expr>>,
2967 pub partition_by: Option<Box<Expr>>,
2970 pub cluster_by: Option<WrappedCollection<Vec<Expr>>>,
2975 pub clustered_by: Option<ClusteredBy>,
2978 pub inherits: Option<Vec<ObjectName>>,
2983 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2987 pub partition_of: Option<ObjectName>,
2988 pub for_values: Option<ForValues>,
2991 pub strict: bool,
2995 pub copy_grants: bool,
2998 pub enable_schema_evolution: Option<bool>,
3001 pub change_tracking: Option<bool>,
3004 pub data_retention_time_in_days: Option<u64>,
3007 pub max_data_extension_time_in_days: Option<u64>,
3010 pub default_ddl_collation: Option<String>,
3013 pub with_aggregation_policy: Option<ObjectName>,
3016 pub with_row_access_policy: Option<RowAccessPolicy>,
3019 pub with_storage_lifecycle_policy: Option<StorageLifecyclePolicy>,
3022 pub with_tags: Option<Vec<Tag>>,
3025 pub external_volume: Option<String>,
3028 pub with_connection: Option<ObjectName>,
3031 pub base_location: Option<String>,
3034 pub catalog: Option<String>,
3037 pub catalog_sync: Option<String>,
3040 pub storage_serialization_policy: Option<StorageSerializationPolicy>,
3043 pub target_lag: Option<String>,
3046 pub warehouse: Option<Ident>,
3049 pub refresh_mode: Option<RefreshModeKind>,
3052 pub initialize: Option<InitializeKind>,
3055 pub require_user: bool,
3058 pub diststyle: Option<DistStyle>,
3061 pub distkey: Option<Expr>,
3064 pub sortkey: Option<Vec<Expr>>,
3067 pub backup: Option<bool>,
3070 pub multiset: Option<bool>,
3075 pub fallback: Option<bool>,
3080 pub with_data: Option<WithData>,
3084}
3085
3086impl fmt::Display for CreateTable {
3087 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3088 write!(
3096 f,
3097 "CREATE {or_replace}{external}{global}{multiset}{temporary}{transient}{volatile}{dynamic}{iceberg}{snapshot}TABLE {if_not_exists}{name}",
3098 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3099 external = if self.external { "EXTERNAL " } else { "" },
3100 snapshot = if self.snapshot { "SNAPSHOT " } else { "" },
3101 global = self.global
3102 .map(|global| {
3103 if global {
3104 "GLOBAL "
3105 } else {
3106 "LOCAL "
3107 }
3108 })
3109 .unwrap_or(""),
3110 if_not_exists = if self.if_not_exists { "IF NOT EXISTS " } else { "" },
3111 multiset = self
3112 .multiset
3113 .map(|m| if m { "MULTISET " } else { "SET " })
3114 .unwrap_or(""),
3115 temporary = if self.temporary { "TEMPORARY " } else { "" },
3116 transient = if self.transient { "TRANSIENT " } else { "" },
3117 volatile = if self.volatile { "VOLATILE " } else { "" },
3118 iceberg = if self.iceberg { "ICEBERG " } else { "" },
3119 dynamic = if self.dynamic { "DYNAMIC " } else { "" },
3120 name = self.name,
3121 )?;
3122 if let Some(fallback) = self.fallback {
3123 write!(f, ", {}", if fallback { "FALLBACK" } else { "NO FALLBACK" })?;
3124 }
3125 if let Some(partition_of) = &self.partition_of {
3126 write!(f, " PARTITION OF {partition_of}")?;
3127 }
3128 if let Some(on_cluster) = &self.on_cluster {
3129 write!(f, " ON CLUSTER {on_cluster}")?;
3130 }
3131 if !self.columns.is_empty() || !self.constraints.is_empty() {
3132 f.write_str(" (")?;
3133 NewLine.fmt(f)?;
3134 Indent(DisplayCommaSeparated(&self.columns)).fmt(f)?;
3135 if !self.columns.is_empty() && !self.constraints.is_empty() {
3136 f.write_str(",")?;
3137 SpaceOrNewline.fmt(f)?;
3138 }
3139 Indent(DisplayCommaSeparated(&self.constraints)).fmt(f)?;
3140 NewLine.fmt(f)?;
3141 f.write_str(")")?;
3142 } else if self.query.is_none()
3143 && self.like.is_none()
3144 && self.clone.is_none()
3145 && self.partition_of.is_none()
3146 {
3147 f.write_str(" ()")?;
3149 } else if let Some(CreateTableLikeKind::Parenthesized(like_in_columns_list)) = &self.like {
3150 write!(f, " ({like_in_columns_list})")?;
3151 }
3152 if let Some(for_values) = &self.for_values {
3153 write!(f, " {for_values}")?;
3154 }
3155
3156 if let Some(comment) = &self.comment {
3159 write!(f, " COMMENT '{comment}'")?;
3160 }
3161
3162 if self.without_rowid {
3164 write!(f, " WITHOUT ROWID")?;
3165 }
3166
3167 if let Some(CreateTableLikeKind::Plain(like)) = &self.like {
3168 write!(f, " {like}")?;
3169 }
3170
3171 if let Some(c) = &self.clone {
3172 write!(f, " CLONE {c}")?;
3173 }
3174
3175 if let Some(version) = &self.version {
3176 write!(f, " {version}")?;
3177 }
3178
3179 match &self.hive_distribution {
3180 HiveDistributionStyle::PARTITIONED { columns } => {
3181 write!(f, " PARTITIONED BY ({})", display_comma_separated(columns))?;
3182 }
3183 HiveDistributionStyle::SKEWED {
3184 columns,
3185 on,
3186 stored_as_directories,
3187 } => {
3188 write!(
3189 f,
3190 " SKEWED BY ({})) ON ({})",
3191 display_comma_separated(columns),
3192 display_comma_separated(on)
3193 )?;
3194 if *stored_as_directories {
3195 write!(f, " STORED AS DIRECTORIES")?;
3196 }
3197 }
3198 _ => (),
3199 }
3200
3201 if let Some(clustered_by) = &self.clustered_by {
3202 write!(f, " {clustered_by}")?;
3203 }
3204
3205 if let Some(HiveFormat {
3206 row_format,
3207 serde_properties,
3208 storage,
3209 location,
3210 }) = &self.hive_formats
3211 {
3212 match row_format {
3213 Some(HiveRowFormat::SERDE { class }) => write!(f, " ROW FORMAT SERDE '{class}'")?,
3214 Some(HiveRowFormat::DELIMITED { delimiters }) => {
3215 write!(f, " ROW FORMAT DELIMITED")?;
3216 if !delimiters.is_empty() {
3217 write!(f, " {}", display_separated(delimiters, " "))?;
3218 }
3219 }
3220 None => (),
3221 }
3222 match storage {
3223 Some(HiveIOFormat::IOF {
3224 input_format,
3225 output_format,
3226 }) => write!(
3227 f,
3228 " STORED AS INPUTFORMAT {input_format} OUTPUTFORMAT {output_format}"
3229 )?,
3230 Some(HiveIOFormat::FileFormat { format }) if !self.external => {
3231 write!(f, " STORED AS {format}")?
3232 }
3233 Some(HiveIOFormat::Using { format }) => write!(f, " USING {format}")?,
3234 _ => (),
3235 }
3236 if let Some(serde_properties) = serde_properties.as_ref() {
3237 write!(
3238 f,
3239 " WITH SERDEPROPERTIES ({})",
3240 display_comma_separated(serde_properties)
3241 )?;
3242 }
3243 if !self.external {
3244 if let Some(loc) = location {
3245 write!(f, " LOCATION '{loc}'")?;
3246 }
3247 }
3248 }
3249 if self.external {
3250 if let Some(file_format) = self.file_format {
3251 write!(f, " STORED AS {file_format}")?;
3252 }
3253 if let Some(location) = &self.location {
3254 write!(f, " LOCATION '{location}'")?;
3255 }
3256 }
3257
3258 match &self.table_options {
3259 options @ CreateTableOptions::With(_)
3260 | options @ CreateTableOptions::Plain(_)
3261 | options @ CreateTableOptions::TableProperties(_) => write!(f, " {options}")?,
3262 _ => (),
3263 }
3264
3265 if let Some(primary_key) = &self.primary_key {
3266 write!(f, " PRIMARY KEY {primary_key}")?;
3267 }
3268 if let Some(order_by) = &self.order_by {
3269 write!(f, " ORDER BY {order_by}")?;
3270 }
3271 if let Some(inherits) = &self.inherits {
3272 write!(f, " INHERITS ({})", display_comma_separated(inherits))?;
3273 }
3274 if let Some(partition_by) = self.partition_by.as_ref() {
3275 write!(f, " PARTITION BY {partition_by}")?;
3276 }
3277 if let Some(cluster_by) = self.cluster_by.as_ref() {
3278 write!(f, " CLUSTER BY {cluster_by}")?;
3279 }
3280 if let Some(with_connection) = &self.with_connection {
3281 write!(f, " WITH CONNECTION {with_connection}")?;
3282 }
3283 if let options @ CreateTableOptions::Options(_) = &self.table_options {
3284 write!(f, " {options}")?;
3285 }
3286 if let Some(external_volume) = self.external_volume.as_ref() {
3287 write!(f, " EXTERNAL_VOLUME='{external_volume}'")?;
3288 }
3289
3290 if let Some(catalog) = self.catalog.as_ref() {
3291 write!(f, " CATALOG='{catalog}'")?;
3292 }
3293
3294 if self.iceberg {
3295 if let Some(base_location) = self.base_location.as_ref() {
3296 write!(f, " BASE_LOCATION='{base_location}'")?;
3297 }
3298 }
3299
3300 if let Some(catalog_sync) = self.catalog_sync.as_ref() {
3301 write!(f, " CATALOG_SYNC='{catalog_sync}'")?;
3302 }
3303
3304 if let Some(storage_serialization_policy) = self.storage_serialization_policy.as_ref() {
3305 write!(
3306 f,
3307 " STORAGE_SERIALIZATION_POLICY={storage_serialization_policy}"
3308 )?;
3309 }
3310
3311 if self.copy_grants {
3312 write!(f, " COPY GRANTS")?;
3313 }
3314
3315 if let Some(is_enabled) = self.enable_schema_evolution {
3316 write!(
3317 f,
3318 " ENABLE_SCHEMA_EVOLUTION={}",
3319 if is_enabled { "TRUE" } else { "FALSE" }
3320 )?;
3321 }
3322
3323 if let Some(is_enabled) = self.change_tracking {
3324 write!(
3325 f,
3326 " CHANGE_TRACKING={}",
3327 if is_enabled { "TRUE" } else { "FALSE" }
3328 )?;
3329 }
3330
3331 if let Some(data_retention_time_in_days) = self.data_retention_time_in_days {
3332 write!(
3333 f,
3334 " DATA_RETENTION_TIME_IN_DAYS={data_retention_time_in_days}",
3335 )?;
3336 }
3337
3338 if let Some(max_data_extension_time_in_days) = self.max_data_extension_time_in_days {
3339 write!(
3340 f,
3341 " MAX_DATA_EXTENSION_TIME_IN_DAYS={max_data_extension_time_in_days}",
3342 )?;
3343 }
3344
3345 if let Some(default_ddl_collation) = &self.default_ddl_collation {
3346 write!(f, " DEFAULT_DDL_COLLATION='{default_ddl_collation}'",)?;
3347 }
3348
3349 if let Some(with_aggregation_policy) = &self.with_aggregation_policy {
3350 write!(f, " WITH AGGREGATION POLICY {with_aggregation_policy}",)?;
3351 }
3352
3353 if let Some(row_access_policy) = &self.with_row_access_policy {
3354 write!(f, " {row_access_policy}",)?;
3355 }
3356
3357 if let Some(storage_lifecycle_policy) = &self.with_storage_lifecycle_policy {
3358 write!(f, " {storage_lifecycle_policy}",)?;
3359 }
3360
3361 if let Some(tag) = &self.with_tags {
3362 write!(f, " WITH TAG ({})", display_comma_separated(tag.as_slice()))?;
3363 }
3364
3365 if let Some(target_lag) = &self.target_lag {
3366 write!(f, " TARGET_LAG='{target_lag}'")?;
3367 }
3368
3369 if let Some(warehouse) = &self.warehouse {
3370 write!(f, " WAREHOUSE={warehouse}")?;
3371 }
3372
3373 if let Some(refresh_mode) = &self.refresh_mode {
3374 write!(f, " REFRESH_MODE={refresh_mode}")?;
3375 }
3376
3377 if let Some(initialize) = &self.initialize {
3378 write!(f, " INITIALIZE={initialize}")?;
3379 }
3380
3381 if self.require_user {
3382 write!(f, " REQUIRE USER")?;
3383 }
3384
3385 if self.on_commit.is_some() {
3386 let on_commit = match self.on_commit {
3387 Some(OnCommit::DeleteRows) => "ON COMMIT DELETE ROWS",
3388 Some(OnCommit::PreserveRows) => "ON COMMIT PRESERVE ROWS",
3389 Some(OnCommit::Drop) => "ON COMMIT DROP",
3390 None => "",
3391 };
3392 write!(f, " {on_commit}")?;
3393 }
3394 if self.strict {
3395 write!(f, " STRICT")?;
3396 }
3397 if let Some(backup) = self.backup {
3398 write!(f, " BACKUP {}", if backup { "YES" } else { "NO" })?;
3399 }
3400 if let Some(diststyle) = &self.diststyle {
3401 write!(f, " DISTSTYLE {diststyle}")?;
3402 }
3403 if let Some(distkey) = &self.distkey {
3404 write!(f, " DISTKEY({distkey})")?;
3405 }
3406 if let Some(sortkey) = &self.sortkey {
3407 write!(f, " SORTKEY({})", display_comma_separated(sortkey))?;
3408 }
3409 if let Some(query) = &self.query {
3410 write!(f, " AS {query}")?;
3411 }
3412 if let Some(with_data) = &self.with_data {
3413 write!(f, " {with_data}")?;
3414 }
3415 Ok(())
3416 }
3417}
3418
3419#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
3423#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3424#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3425pub struct WithData {
3426 pub data: bool,
3428 pub statistics: Option<bool>,
3431}
3432
3433impl fmt::Display for WithData {
3434 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3435 f.write_str("WITH ")?;
3436 if !self.data {
3437 f.write_str("NO ")?;
3438 }
3439 f.write_str("DATA")?;
3440 if let Some(stats) = self.statistics {
3441 f.write_str(" AND ")?;
3442 if !stats {
3443 f.write_str("NO ")?;
3444 }
3445 f.write_str("STATISTICS")?;
3446 }
3447 Ok(())
3448 }
3449}
3450
3451#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3457#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3458#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3459pub enum ForValues {
3460 In(Vec<Expr>),
3462 From {
3464 from: Vec<PartitionBoundValue>,
3466 to: Vec<PartitionBoundValue>,
3468 },
3469 With {
3471 modulus: u64,
3473 remainder: u64,
3475 },
3476 Default,
3478}
3479
3480impl fmt::Display for ForValues {
3481 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3482 match self {
3483 ForValues::In(values) => {
3484 write!(f, "FOR VALUES IN ({})", display_comma_separated(values))
3485 }
3486 ForValues::From { from, to } => {
3487 write!(
3488 f,
3489 "FOR VALUES FROM ({}) TO ({})",
3490 display_comma_separated(from),
3491 display_comma_separated(to)
3492 )
3493 }
3494 ForValues::With { modulus, remainder } => {
3495 write!(
3496 f,
3497 "FOR VALUES WITH (MODULUS {modulus}, REMAINDER {remainder})"
3498 )
3499 }
3500 ForValues::Default => write!(f, "DEFAULT"),
3501 }
3502 }
3503}
3504
3505#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3510#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3511#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3512pub enum PartitionBoundValue {
3513 Expr(Expr),
3515 MinValue,
3517 MaxValue,
3519}
3520
3521impl fmt::Display for PartitionBoundValue {
3522 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3523 match self {
3524 PartitionBoundValue::Expr(expr) => write!(f, "{expr}"),
3525 PartitionBoundValue::MinValue => write!(f, "MINVALUE"),
3526 PartitionBoundValue::MaxValue => write!(f, "MAXVALUE"),
3527 }
3528 }
3529}
3530
3531#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3535#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3536#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3537pub enum DistStyle {
3538 Auto,
3540 Even,
3542 Key,
3544 All,
3546}
3547
3548impl fmt::Display for DistStyle {
3549 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3550 match self {
3551 DistStyle::Auto => write!(f, "AUTO"),
3552 DistStyle::Even => write!(f, "EVEN"),
3553 DistStyle::Key => write!(f, "KEY"),
3554 DistStyle::All => write!(f, "ALL"),
3555 }
3556 }
3557}
3558
3559#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3560#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3561#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3562pub struct CreateDomain {
3575 pub name: ObjectName,
3577 pub data_type: DataType,
3579 pub collation: Option<Ident>,
3581 pub default: Option<Expr>,
3583 pub constraints: Vec<TableConstraint>,
3585}
3586
3587impl fmt::Display for CreateDomain {
3588 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3589 write!(
3590 f,
3591 "CREATE DOMAIN {name} AS {data_type}",
3592 name = self.name,
3593 data_type = self.data_type
3594 )?;
3595 if let Some(collation) = &self.collation {
3596 write!(f, " COLLATE {collation}")?;
3597 }
3598 if let Some(default) = &self.default {
3599 write!(f, " DEFAULT {default}")?;
3600 }
3601 if !self.constraints.is_empty() {
3602 write!(f, " {}", display_separated(&self.constraints, " "))?;
3603 }
3604 Ok(())
3605 }
3606}
3607
3608#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3610#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3611#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3612pub enum FunctionReturnType {
3613 DataType(DataType),
3615 SetOf(DataType),
3619}
3620
3621impl fmt::Display for FunctionReturnType {
3622 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3623 match self {
3624 FunctionReturnType::DataType(data_type) => write!(f, "{data_type}"),
3625 FunctionReturnType::SetOf(data_type) => write!(f, "SETOF {data_type}"),
3626 }
3627 }
3628}
3629
3630#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3631#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3632#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3633pub struct CreateFunction {
3635 pub or_alter: bool,
3639 pub or_replace: bool,
3641 pub temporary: bool,
3643 pub if_not_exists: bool,
3645 pub name: ObjectName,
3647 pub args: Option<Vec<OperateFunctionArg>>,
3649 pub return_type: Option<FunctionReturnType>,
3651 pub function_body: Option<CreateFunctionBody>,
3659 pub behavior: Option<FunctionBehavior>,
3665 pub called_on_null: Option<FunctionCalledOnNull>,
3669 pub parallel: Option<FunctionParallel>,
3673 pub security: Option<FunctionSecurity>,
3677 pub set_params: Vec<FunctionDefinitionSetParam>,
3681 pub using: Option<CreateFunctionUsing>,
3683 pub language: Option<Ident>,
3691 pub determinism_specifier: Option<FunctionDeterminismSpecifier>,
3695 pub options: Option<Vec<SqlOption>>,
3699 pub remote_connection: Option<ObjectName>,
3709}
3710
3711impl fmt::Display for CreateFunction {
3712 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3713 write!(
3714 f,
3715 "CREATE {or_alter}{or_replace}{temp}FUNCTION {if_not_exists}{name}",
3716 name = self.name,
3717 temp = if self.temporary { "TEMPORARY " } else { "" },
3718 or_alter = if self.or_alter { "OR ALTER " } else { "" },
3719 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3720 if_not_exists = if self.if_not_exists {
3721 "IF NOT EXISTS "
3722 } else {
3723 ""
3724 },
3725 )?;
3726 if let Some(args) = &self.args {
3727 write!(f, "({})", display_comma_separated(args))?;
3728 }
3729 if let Some(return_type) = &self.return_type {
3730 write!(f, " RETURNS {return_type}")?;
3731 }
3732 if let Some(determinism_specifier) = &self.determinism_specifier {
3733 write!(f, " {determinism_specifier}")?;
3734 }
3735 if let Some(language) = &self.language {
3736 write!(f, " LANGUAGE {language}")?;
3737 }
3738 if let Some(behavior) = &self.behavior {
3739 write!(f, " {behavior}")?;
3740 }
3741 if let Some(called_on_null) = &self.called_on_null {
3742 write!(f, " {called_on_null}")?;
3743 }
3744 if let Some(parallel) = &self.parallel {
3745 write!(f, " {parallel}")?;
3746 }
3747 if let Some(security) = &self.security {
3748 write!(f, " {security}")?;
3749 }
3750 for set_param in &self.set_params {
3751 write!(f, " {set_param}")?;
3752 }
3753 if let Some(remote_connection) = &self.remote_connection {
3754 write!(f, " REMOTE WITH CONNECTION {remote_connection}")?;
3755 }
3756 if let Some(CreateFunctionBody::AsBeforeOptions { body, link_symbol }) = &self.function_body
3757 {
3758 write!(f, " AS {body}")?;
3759 if let Some(link_symbol) = link_symbol {
3760 write!(f, ", {link_symbol}")?;
3761 }
3762 }
3763 if let Some(CreateFunctionBody::Return(function_body)) = &self.function_body {
3764 write!(f, " RETURN {function_body}")?;
3765 }
3766 if let Some(CreateFunctionBody::AsReturnExpr(function_body)) = &self.function_body {
3767 write!(f, " AS RETURN {function_body}")?;
3768 }
3769 if let Some(CreateFunctionBody::AsReturnSelect(function_body)) = &self.function_body {
3770 write!(f, " AS RETURN {function_body}")?;
3771 }
3772 if let Some(using) = &self.using {
3773 write!(f, " {using}")?;
3774 }
3775 if let Some(options) = &self.options {
3776 write!(
3777 f,
3778 " OPTIONS({})",
3779 display_comma_separated(options.as_slice())
3780 )?;
3781 }
3782 if let Some(CreateFunctionBody::AsAfterOptions(function_body)) = &self.function_body {
3783 write!(f, " AS {function_body}")?;
3784 }
3785 if let Some(CreateFunctionBody::AsBeginEnd(bes)) = &self.function_body {
3786 write!(f, " AS {bes}")?;
3787 }
3788 Ok(())
3789 }
3790}
3791
3792#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3802#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3803#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3804pub struct CreateConnector {
3805 pub name: Ident,
3807 pub if_not_exists: bool,
3809 pub connector_type: Option<String>,
3811 pub url: Option<String>,
3813 pub comment: Option<CommentDef>,
3815 pub with_dcproperties: Option<Vec<SqlOption>>,
3817}
3818
3819impl fmt::Display for CreateConnector {
3820 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3821 write!(
3822 f,
3823 "CREATE CONNECTOR {if_not_exists}{name}",
3824 if_not_exists = if self.if_not_exists {
3825 "IF NOT EXISTS "
3826 } else {
3827 ""
3828 },
3829 name = self.name,
3830 )?;
3831
3832 if let Some(connector_type) = &self.connector_type {
3833 write!(f, " TYPE '{connector_type}'")?;
3834 }
3835
3836 if let Some(url) = &self.url {
3837 write!(f, " URL '{url}'")?;
3838 }
3839
3840 if let Some(comment) = &self.comment {
3841 write!(f, " COMMENT = '{comment}'")?;
3842 }
3843
3844 if let Some(with_dcproperties) = &self.with_dcproperties {
3845 write!(
3846 f,
3847 " WITH DCPROPERTIES({})",
3848 display_comma_separated(with_dcproperties)
3849 )?;
3850 }
3851
3852 Ok(())
3853 }
3854}
3855
3856#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3861#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3862#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3863pub enum AlterSchemaOperation {
3864 SetDefaultCollate {
3866 collate: Expr,
3868 },
3869 AddReplica {
3871 replica: Ident,
3873 options: Option<Vec<SqlOption>>,
3875 },
3876 DropReplica {
3878 replica: Ident,
3880 },
3881 SetOptionsParens {
3883 options: Vec<SqlOption>,
3885 },
3886 Rename {
3888 name: ObjectName,
3890 },
3891 OwnerTo {
3893 owner: Owner,
3895 },
3896}
3897
3898impl fmt::Display for AlterSchemaOperation {
3899 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3900 match self {
3901 AlterSchemaOperation::SetDefaultCollate { collate } => {
3902 write!(f, "SET DEFAULT COLLATE {collate}")
3903 }
3904 AlterSchemaOperation::AddReplica { replica, options } => {
3905 write!(f, "ADD REPLICA {replica}")?;
3906 if let Some(options) = options {
3907 write!(f, " OPTIONS ({})", display_comma_separated(options))?;
3908 }
3909 Ok(())
3910 }
3911 AlterSchemaOperation::DropReplica { replica } => write!(f, "DROP REPLICA {replica}"),
3912 AlterSchemaOperation::SetOptionsParens { options } => {
3913 write!(f, "SET OPTIONS ({})", display_comma_separated(options))
3914 }
3915 AlterSchemaOperation::Rename { name } => write!(f, "RENAME TO {name}"),
3916 AlterSchemaOperation::OwnerTo { owner } => write!(f, "OWNER TO {owner}"),
3917 }
3918 }
3919}
3920#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3926#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3927#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3928pub enum RenameTableNameKind {
3929 As(ObjectName),
3931 To(ObjectName),
3933}
3934
3935impl fmt::Display for RenameTableNameKind {
3936 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3937 match self {
3938 RenameTableNameKind::As(name) => write!(f, "AS {name}"),
3939 RenameTableNameKind::To(name) => write!(f, "TO {name}"),
3940 }
3941 }
3942}
3943
3944#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3945#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3946#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3947pub struct AlterSchema {
3949 pub name: ObjectName,
3951 pub if_exists: bool,
3953 pub operations: Vec<AlterSchemaOperation>,
3955}
3956
3957impl fmt::Display for AlterSchema {
3958 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3959 write!(f, "ALTER SCHEMA ")?;
3960 if self.if_exists {
3961 write!(f, "IF EXISTS ")?;
3962 }
3963 write!(f, "{}", self.name)?;
3964 for operation in &self.operations {
3965 write!(f, " {operation}")?;
3966 }
3967
3968 Ok(())
3969 }
3970}
3971
3972impl Spanned for RenameTableNameKind {
3973 fn span(&self) -> Span {
3974 match self {
3975 RenameTableNameKind::As(name) => name.span(),
3976 RenameTableNameKind::To(name) => name.span(),
3977 }
3978 }
3979}
3980
3981#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
3982#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3983#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3984pub enum TriggerObjectKind {
3986 For(TriggerObject),
3988 ForEach(TriggerObject),
3990}
3991
3992impl Display for TriggerObjectKind {
3993 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3994 match self {
3995 TriggerObjectKind::For(obj) => write!(f, "FOR {obj}"),
3996 TriggerObjectKind::ForEach(obj) => write!(f, "FOR EACH {obj}"),
3997 }
3998 }
3999}
4000
4001#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4002#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4003#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4004pub struct CreateTrigger {
4018 pub or_alter: bool,
4022 pub temporary: bool,
4039 pub or_replace: bool,
4049 pub is_constraint: bool,
4051 pub name: ObjectName,
4053 pub period: Option<TriggerPeriod>,
4082 pub period_before_table: bool,
4093 pub events: Vec<TriggerEvent>,
4095 pub table_name: ObjectName,
4097 pub referenced_table_name: Option<ObjectName>,
4100 pub referencing: Vec<TriggerReferencing>,
4102 pub trigger_object: Option<TriggerObjectKind>,
4107 pub condition: Option<Expr>,
4109 pub exec_body: Option<TriggerExecBody>,
4111 pub statements_as: bool,
4113 pub statements: Option<ConditionalStatements>,
4115 pub characteristics: Option<ConstraintCharacteristics>,
4117}
4118
4119impl Display for CreateTrigger {
4120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4121 let CreateTrigger {
4122 or_alter,
4123 temporary,
4124 or_replace,
4125 is_constraint,
4126 name,
4127 period_before_table,
4128 period,
4129 events,
4130 table_name,
4131 referenced_table_name,
4132 referencing,
4133 trigger_object,
4134 condition,
4135 exec_body,
4136 statements_as,
4137 statements,
4138 characteristics,
4139 } = self;
4140 write!(
4141 f,
4142 "CREATE {temporary}{or_alter}{or_replace}{is_constraint}TRIGGER {name} ",
4143 temporary = if *temporary { "TEMPORARY " } else { "" },
4144 or_alter = if *or_alter { "OR ALTER " } else { "" },
4145 or_replace = if *or_replace { "OR REPLACE " } else { "" },
4146 is_constraint = if *is_constraint { "CONSTRAINT " } else { "" },
4147 )?;
4148
4149 if *period_before_table {
4150 if let Some(p) = period {
4151 write!(f, "{p} ")?;
4152 }
4153 if !events.is_empty() {
4154 write!(f, "{} ", display_separated(events, " OR "))?;
4155 }
4156 write!(f, "ON {table_name}")?;
4157 } else {
4158 write!(f, "ON {table_name} ")?;
4159 if let Some(p) = period {
4160 write!(f, "{p}")?;
4161 }
4162 if !events.is_empty() {
4163 write!(f, " {}", display_separated(events, ", "))?;
4164 }
4165 }
4166
4167 if let Some(referenced_table_name) = referenced_table_name {
4168 write!(f, " FROM {referenced_table_name}")?;
4169 }
4170
4171 if let Some(characteristics) = characteristics {
4172 write!(f, " {characteristics}")?;
4173 }
4174
4175 if !referencing.is_empty() {
4176 write!(f, " REFERENCING {}", display_separated(referencing, " "))?;
4177 }
4178
4179 if let Some(trigger_object) = trigger_object {
4180 write!(f, " {trigger_object}")?;
4181 }
4182 if let Some(condition) = condition {
4183 write!(f, " WHEN {condition}")?;
4184 }
4185 if let Some(exec_body) = exec_body {
4186 write!(f, " EXECUTE {exec_body}")?;
4187 }
4188 if let Some(statements) = statements {
4189 if *statements_as {
4190 write!(f, " AS")?;
4191 }
4192 write!(f, " {statements}")?;
4193 }
4194 Ok(())
4195 }
4196}
4197
4198#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4199#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4200#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4201pub struct DropTrigger {
4208 pub if_exists: bool,
4210 pub trigger_name: ObjectName,
4212 pub table_name: Option<ObjectName>,
4214 pub option: Option<ReferentialAction>,
4216}
4217
4218impl fmt::Display for DropTrigger {
4219 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4220 let DropTrigger {
4221 if_exists,
4222 trigger_name,
4223 table_name,
4224 option,
4225 } = self;
4226 write!(f, "DROP TRIGGER")?;
4227 if *if_exists {
4228 write!(f, " IF EXISTS")?;
4229 }
4230 match &table_name {
4231 Some(table_name) => write!(f, " {trigger_name} ON {table_name}")?,
4232 None => write!(f, " {trigger_name}")?,
4233 };
4234 if let Some(option) = option {
4235 write!(f, " {option}")?;
4236 }
4237 Ok(())
4238 }
4239}
4240
4241#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4247#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4248#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4249pub struct Truncate {
4250 pub table_names: Vec<super::TruncateTableTarget>,
4252 pub partitions: Option<Vec<Expr>>,
4254 pub table: bool,
4256 pub if_exists: bool,
4258 pub identity: Option<super::TruncateIdentityOption>,
4260 pub cascade: Option<super::CascadeOption>,
4262 pub on_cluster: Option<Ident>,
4265}
4266
4267impl fmt::Display for Truncate {
4268 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4269 let table = if self.table { "TABLE " } else { "" };
4270 let if_exists = if self.if_exists { "IF EXISTS " } else { "" };
4271
4272 write!(
4273 f,
4274 "TRUNCATE {table}{if_exists}{table_names}",
4275 table_names = display_comma_separated(&self.table_names)
4276 )?;
4277
4278 if let Some(identity) = &self.identity {
4279 match identity {
4280 super::TruncateIdentityOption::Restart => write!(f, " RESTART IDENTITY")?,
4281 super::TruncateIdentityOption::Continue => write!(f, " CONTINUE IDENTITY")?,
4282 }
4283 }
4284 if let Some(cascade) = &self.cascade {
4285 match cascade {
4286 super::CascadeOption::Cascade => write!(f, " CASCADE")?,
4287 super::CascadeOption::Restrict => write!(f, " RESTRICT")?,
4288 }
4289 }
4290
4291 if let Some(ref parts) = &self.partitions {
4292 if !parts.is_empty() {
4293 write!(f, " PARTITION ({})", display_comma_separated(parts))?;
4294 }
4295 }
4296 if let Some(on_cluster) = &self.on_cluster {
4297 write!(f, " ON CLUSTER {on_cluster}")?;
4298 }
4299 Ok(())
4300 }
4301}
4302
4303impl Spanned for Truncate {
4304 fn span(&self) -> Span {
4305 Span::union_iter(
4306 self.table_names.iter().map(|i| i.name.span()).chain(
4307 self.partitions
4308 .iter()
4309 .flat_map(|i| i.iter().map(|k| k.span())),
4310 ),
4311 )
4312 }
4313}
4314
4315#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4322#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4323#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4324pub struct Msck {
4325 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4327 pub table_name: ObjectName,
4328 pub repair: bool,
4330 pub partition_action: Option<super::AddDropSync>,
4332}
4333
4334impl fmt::Display for Msck {
4335 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4336 write!(
4337 f,
4338 "MSCK {repair}TABLE {table}",
4339 repair = if self.repair { "REPAIR " } else { "" },
4340 table = self.table_name
4341 )?;
4342 if let Some(pa) = &self.partition_action {
4343 write!(f, " {pa}")?;
4344 }
4345 Ok(())
4346 }
4347}
4348
4349impl Spanned for Msck {
4350 fn span(&self) -> Span {
4351 self.table_name.span()
4352 }
4353}
4354
4355#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4357#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4358#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4359pub struct CreateView {
4360 pub or_alter: bool,
4364 pub or_replace: bool,
4366 pub materialized: bool,
4368 pub secure: bool,
4371 pub name: ObjectName,
4373 pub name_before_not_exists: bool,
4384 pub columns: Vec<ViewColumnDef>,
4386 pub query: Box<Query>,
4388 pub options: CreateTableOptions,
4390 pub cluster_by: Vec<Ident>,
4392 pub comment: Option<String>,
4395 pub with_no_schema_binding: bool,
4397 pub if_not_exists: bool,
4399 pub temporary: bool,
4401 pub copy_grants: bool,
4404 pub to: Option<ObjectName>,
4407 pub params: Option<CreateViewParams>,
4409}
4410
4411impl fmt::Display for CreateView {
4412 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4413 write!(
4414 f,
4415 "CREATE {or_alter}{or_replace}",
4416 or_alter = if self.or_alter { "OR ALTER " } else { "" },
4417 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
4418 )?;
4419 if let Some(ref params) = self.params {
4420 params.fmt(f)?;
4421 }
4422 write!(
4423 f,
4424 "{secure}{materialized}{temporary}VIEW {if_not_and_name}{to}",
4425 if_not_and_name = if self.if_not_exists {
4426 if self.name_before_not_exists {
4427 format!("{} IF NOT EXISTS", self.name)
4428 } else {
4429 format!("IF NOT EXISTS {}", self.name)
4430 }
4431 } else {
4432 format!("{}", self.name)
4433 },
4434 secure = if self.secure { "SECURE " } else { "" },
4435 materialized = if self.materialized {
4436 "MATERIALIZED "
4437 } else {
4438 ""
4439 },
4440 temporary = if self.temporary { "TEMPORARY " } else { "" },
4441 to = self
4442 .to
4443 .as_ref()
4444 .map(|to| format!(" TO {to}"))
4445 .unwrap_or_default()
4446 )?;
4447 if self.copy_grants {
4448 write!(f, " COPY GRANTS")?;
4449 }
4450 if !self.columns.is_empty() {
4451 write!(f, " ({})", display_comma_separated(&self.columns))?;
4452 }
4453 if matches!(self.options, CreateTableOptions::With(_)) {
4454 write!(f, " {}", self.options)?;
4455 }
4456 if let Some(ref comment) = self.comment {
4457 write!(f, " COMMENT = '{}'", escape_single_quote_string(comment))?;
4458 }
4459 if !self.cluster_by.is_empty() {
4460 write!(
4461 f,
4462 " CLUSTER BY ({})",
4463 display_comma_separated(&self.cluster_by)
4464 )?;
4465 }
4466 if matches!(self.options, CreateTableOptions::Options(_)) {
4467 write!(f, " {}", self.options)?;
4468 }
4469 f.write_str(" AS")?;
4470 SpaceOrNewline.fmt(f)?;
4471 self.query.fmt(f)?;
4472 if self.with_no_schema_binding {
4473 write!(f, " WITH NO SCHEMA BINDING")?;
4474 }
4475 Ok(())
4476 }
4477}
4478
4479#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4482#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4483#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4484pub struct CreateExtension {
4485 pub name: Ident,
4487 pub if_not_exists: bool,
4489 pub cascade: bool,
4491 pub schema: Option<Ident>,
4493 pub version: Option<Ident>,
4495}
4496
4497impl fmt::Display for CreateExtension {
4498 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4499 write!(
4500 f,
4501 "CREATE EXTENSION {if_not_exists}{name}",
4502 if_not_exists = if self.if_not_exists {
4503 "IF NOT EXISTS "
4504 } else {
4505 ""
4506 },
4507 name = self.name
4508 )?;
4509 if self.cascade || self.schema.is_some() || self.version.is_some() {
4510 write!(f, " WITH")?;
4511
4512 if let Some(name) = &self.schema {
4513 write!(f, " SCHEMA {name}")?;
4514 }
4515 if let Some(version) = &self.version {
4516 write!(f, " VERSION {version}")?;
4517 }
4518 if self.cascade {
4519 write!(f, " CASCADE")?;
4520 }
4521 }
4522
4523 Ok(())
4524 }
4525}
4526
4527impl Spanned for CreateExtension {
4528 fn span(&self) -> Span {
4529 Span::empty()
4530 }
4531}
4532
4533#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4541#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4542#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4543pub struct DropExtension {
4544 pub names: Vec<Ident>,
4546 pub if_exists: bool,
4548 pub cascade_or_restrict: Option<ReferentialAction>,
4550}
4551
4552impl fmt::Display for DropExtension {
4553 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4554 write!(f, "DROP EXTENSION")?;
4555 if self.if_exists {
4556 write!(f, " IF EXISTS")?;
4557 }
4558 write!(f, " {}", display_comma_separated(&self.names))?;
4559 if let Some(cascade_or_restrict) = &self.cascade_or_restrict {
4560 write!(f, " {cascade_or_restrict}")?;
4561 }
4562 Ok(())
4563 }
4564}
4565
4566impl Spanned for DropExtension {
4567 fn span(&self) -> Span {
4568 Span::empty()
4569 }
4570}
4571
4572#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4575#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4576#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4577pub struct CreateCollation {
4578 pub if_not_exists: bool,
4580 pub name: ObjectName,
4582 pub definition: CreateCollationDefinition,
4584}
4585
4586#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4588#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4589#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4590pub enum CreateCollationDefinition {
4591 From(ObjectName),
4597 Options(Vec<SqlOption>),
4603}
4604
4605impl fmt::Display for CreateCollation {
4606 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4607 write!(
4608 f,
4609 "CREATE COLLATION {if_not_exists}{name}",
4610 if_not_exists = if self.if_not_exists {
4611 "IF NOT EXISTS "
4612 } else {
4613 ""
4614 },
4615 name = self.name
4616 )?;
4617 match &self.definition {
4618 CreateCollationDefinition::From(existing_collation) => {
4619 write!(f, " FROM {existing_collation}")
4620 }
4621 CreateCollationDefinition::Options(options) => {
4622 write!(f, " ({})", display_comma_separated(options))
4623 }
4624 }
4625 }
4626}
4627
4628impl Spanned for CreateCollation {
4629 fn span(&self) -> Span {
4630 Span::empty()
4631 }
4632}
4633
4634#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4637#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4638#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4639pub struct AlterCollation {
4640 pub name: ObjectName,
4642 pub operation: AlterCollationOperation,
4644}
4645
4646#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4648#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4649#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4650pub enum AlterCollationOperation {
4651 RenameTo {
4657 new_name: Ident,
4659 },
4660 OwnerTo(Owner),
4666 SetSchema {
4672 schema_name: ObjectName,
4674 },
4675 RefreshVersion,
4681}
4682
4683impl fmt::Display for AlterCollationOperation {
4684 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4685 match self {
4686 AlterCollationOperation::RenameTo { new_name } => write!(f, "RENAME TO {new_name}"),
4687 AlterCollationOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
4688 AlterCollationOperation::SetSchema { schema_name } => {
4689 write!(f, "SET SCHEMA {schema_name}")
4690 }
4691 AlterCollationOperation::RefreshVersion => write!(f, "REFRESH VERSION"),
4692 }
4693 }
4694}
4695
4696impl fmt::Display for AlterCollation {
4697 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4698 write!(f, "ALTER COLLATION {} {}", self.name, self.operation)
4699 }
4700}
4701
4702impl Spanned for AlterCollation {
4703 fn span(&self) -> Span {
4704 Span::empty()
4705 }
4706}
4707
4708#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4711#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4712#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4713pub enum AlterTableType {
4714 Iceberg,
4717 Dynamic,
4720 External,
4723}
4724
4725#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4727#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4728#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4729pub struct AlterTable {
4730 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4732 pub name: ObjectName,
4733 pub if_exists: bool,
4735 pub only: bool,
4737 pub operations: Vec<AlterTableOperation>,
4739 pub location: Option<HiveSetLocation>,
4741 pub on_cluster: Option<Ident>,
4745 pub table_type: Option<AlterTableType>,
4747 pub end_token: AttachedToken,
4749}
4750
4751impl fmt::Display for AlterTable {
4752 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4753 match &self.table_type {
4754 Some(AlterTableType::Iceberg) => write!(f, "ALTER ICEBERG TABLE ")?,
4755 Some(AlterTableType::Dynamic) => write!(f, "ALTER DYNAMIC TABLE ")?,
4756 Some(AlterTableType::External) => write!(f, "ALTER EXTERNAL TABLE ")?,
4757 None => write!(f, "ALTER TABLE ")?,
4758 }
4759
4760 if self.if_exists {
4761 write!(f, "IF EXISTS ")?;
4762 }
4763 if self.only {
4764 write!(f, "ONLY ")?;
4765 }
4766 write!(f, "{} ", &self.name)?;
4767 if let Some(cluster) = &self.on_cluster {
4768 write!(f, "ON CLUSTER {cluster} ")?;
4769 }
4770 write!(f, "{}", display_comma_separated(&self.operations))?;
4771 if let Some(loc) = &self.location {
4772 write!(f, " {loc}")?
4773 }
4774 Ok(())
4775 }
4776}
4777
4778#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4780#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4781#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4782pub struct DropFunction {
4783 pub if_exists: bool,
4785 pub func_desc: Vec<FunctionDesc>,
4787 pub drop_behavior: Option<DropBehavior>,
4789}
4790
4791impl fmt::Display for DropFunction {
4792 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4793 write!(
4794 f,
4795 "DROP FUNCTION{} {}",
4796 if self.if_exists { " IF EXISTS" } else { "" },
4797 display_comma_separated(&self.func_desc),
4798 )?;
4799 if let Some(op) = &self.drop_behavior {
4800 write!(f, " {op}")?;
4801 }
4802 Ok(())
4803 }
4804}
4805
4806impl Spanned for DropFunction {
4807 fn span(&self) -> Span {
4808 Span::empty()
4809 }
4810}
4811
4812#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4815#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4816#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4817pub struct CreateOperator {
4818 pub name: ObjectName,
4820 pub function: ObjectName,
4822 pub is_procedure: bool,
4824 pub left_arg: Option<DataType>,
4826 pub right_arg: Option<DataType>,
4828 pub options: Vec<OperatorOption>,
4830}
4831
4832#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4835#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4836#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4837pub struct CreateOperatorFamily {
4838 pub name: ObjectName,
4840 pub using: Ident,
4842}
4843
4844#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4847#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4848#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4849pub struct CreateOperatorClass {
4850 pub name: ObjectName,
4852 pub default: bool,
4854 pub for_type: DataType,
4856 pub using: Ident,
4858 pub family: Option<ObjectName>,
4860 pub items: Vec<OperatorClassItem>,
4862}
4863
4864impl fmt::Display for CreateOperator {
4865 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4866 write!(f, "CREATE OPERATOR {} (", self.name)?;
4867
4868 let function_keyword = if self.is_procedure {
4869 "PROCEDURE"
4870 } else {
4871 "FUNCTION"
4872 };
4873 let mut params = vec![format!("{} = {}", function_keyword, self.function)];
4874
4875 if let Some(left_arg) = &self.left_arg {
4876 params.push(format!("LEFTARG = {}", left_arg));
4877 }
4878 if let Some(right_arg) = &self.right_arg {
4879 params.push(format!("RIGHTARG = {}", right_arg));
4880 }
4881
4882 for option in &self.options {
4883 params.push(option.to_string());
4884 }
4885
4886 write!(f, "{}", params.join(", "))?;
4887 write!(f, ")")
4888 }
4889}
4890
4891impl fmt::Display for CreateOperatorFamily {
4892 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4893 write!(
4894 f,
4895 "CREATE OPERATOR FAMILY {} USING {}",
4896 self.name, self.using
4897 )
4898 }
4899}
4900
4901impl fmt::Display for CreateOperatorClass {
4902 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4903 write!(f, "CREATE OPERATOR CLASS {}", self.name)?;
4904 if self.default {
4905 write!(f, " DEFAULT")?;
4906 }
4907 write!(f, " FOR TYPE {} USING {}", self.for_type, self.using)?;
4908 if let Some(family) = &self.family {
4909 write!(f, " FAMILY {}", family)?;
4910 }
4911 write!(f, " AS {}", display_comma_separated(&self.items))
4912 }
4913}
4914
4915#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4917#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4918#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4919pub struct OperatorArgTypes {
4920 pub left: DataType,
4922 pub right: DataType,
4924}
4925
4926impl fmt::Display for OperatorArgTypes {
4927 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4928 write!(f, "{}, {}", self.left, self.right)
4929 }
4930}
4931
4932#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4934#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4935#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4936pub enum OperatorClassItem {
4937 Operator {
4939 strategy_number: u64,
4941 operator_name: ObjectName,
4943 op_types: Option<OperatorArgTypes>,
4945 purpose: Option<OperatorPurpose>,
4947 },
4948 Function {
4950 support_number: u64,
4952 op_types: Option<Vec<DataType>>,
4954 function_name: ObjectName,
4956 argument_types: Vec<DataType>,
4958 },
4959 Storage {
4961 storage_type: DataType,
4963 },
4964}
4965
4966#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4968#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4969#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4970pub enum OperatorPurpose {
4971 ForSearch,
4973 ForOrderBy {
4975 sort_family: ObjectName,
4977 },
4978}
4979
4980impl fmt::Display for OperatorClassItem {
4981 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4982 match self {
4983 OperatorClassItem::Operator {
4984 strategy_number,
4985 operator_name,
4986 op_types,
4987 purpose,
4988 } => {
4989 write!(f, "OPERATOR {strategy_number} {operator_name}")?;
4990 if let Some(types) = op_types {
4991 write!(f, " ({types})")?;
4992 }
4993 if let Some(purpose) = purpose {
4994 write!(f, " {purpose}")?;
4995 }
4996 Ok(())
4997 }
4998 OperatorClassItem::Function {
4999 support_number,
5000 op_types,
5001 function_name,
5002 argument_types,
5003 } => {
5004 write!(f, "FUNCTION {support_number}")?;
5005 if let Some(types) = op_types {
5006 write!(f, " ({})", display_comma_separated(types))?;
5007 }
5008 write!(f, " {function_name}")?;
5009 if !argument_types.is_empty() {
5010 write!(f, "({})", display_comma_separated(argument_types))?;
5011 }
5012 Ok(())
5013 }
5014 OperatorClassItem::Storage { storage_type } => {
5015 write!(f, "STORAGE {storage_type}")
5016 }
5017 }
5018 }
5019}
5020
5021impl fmt::Display for OperatorPurpose {
5022 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5023 match self {
5024 OperatorPurpose::ForSearch => write!(f, "FOR SEARCH"),
5025 OperatorPurpose::ForOrderBy { sort_family } => {
5026 write!(f, "FOR ORDER BY {sort_family}")
5027 }
5028 }
5029 }
5030}
5031
5032#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5035#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5036#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5037pub struct DropOperator {
5038 pub if_exists: bool,
5040 pub operators: Vec<DropOperatorSignature>,
5042 pub drop_behavior: Option<DropBehavior>,
5044}
5045
5046#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5048#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5049#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5050pub struct DropOperatorSignature {
5051 pub name: ObjectName,
5053 pub left_type: Option<DataType>,
5055 pub right_type: DataType,
5057}
5058
5059impl fmt::Display for DropOperatorSignature {
5060 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5061 write!(f, "{} (", self.name)?;
5062 if let Some(left_type) = &self.left_type {
5063 write!(f, "{}", left_type)?;
5064 } else {
5065 write!(f, "NONE")?;
5066 }
5067 write!(f, ", {})", self.right_type)
5068 }
5069}
5070
5071impl fmt::Display for DropOperator {
5072 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5073 write!(f, "DROP OPERATOR")?;
5074 if self.if_exists {
5075 write!(f, " IF EXISTS")?;
5076 }
5077 write!(f, " {}", display_comma_separated(&self.operators))?;
5078 if let Some(drop_behavior) = &self.drop_behavior {
5079 write!(f, " {}", drop_behavior)?;
5080 }
5081 Ok(())
5082 }
5083}
5084
5085impl Spanned for DropOperator {
5086 fn span(&self) -> Span {
5087 Span::empty()
5088 }
5089}
5090
5091#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5094#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5095#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5096pub struct DropOperatorFamily {
5097 pub if_exists: bool,
5099 pub names: Vec<ObjectName>,
5101 pub using: Ident,
5103 pub drop_behavior: Option<DropBehavior>,
5105}
5106
5107impl fmt::Display for DropOperatorFamily {
5108 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5109 write!(f, "DROP OPERATOR FAMILY")?;
5110 if self.if_exists {
5111 write!(f, " IF EXISTS")?;
5112 }
5113 write!(f, " {}", display_comma_separated(&self.names))?;
5114 write!(f, " USING {}", self.using)?;
5115 if let Some(drop_behavior) = &self.drop_behavior {
5116 write!(f, " {}", drop_behavior)?;
5117 }
5118 Ok(())
5119 }
5120}
5121
5122impl Spanned for DropOperatorFamily {
5123 fn span(&self) -> Span {
5124 Span::empty()
5125 }
5126}
5127
5128#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5131#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5132#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5133pub struct DropOperatorClass {
5134 pub if_exists: bool,
5136 pub names: Vec<ObjectName>,
5138 pub using: Ident,
5140 pub drop_behavior: Option<DropBehavior>,
5142}
5143
5144impl fmt::Display for DropOperatorClass {
5145 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5146 write!(f, "DROP OPERATOR CLASS")?;
5147 if self.if_exists {
5148 write!(f, " IF EXISTS")?;
5149 }
5150 write!(f, " {}", display_comma_separated(&self.names))?;
5151 write!(f, " USING {}", self.using)?;
5152 if let Some(drop_behavior) = &self.drop_behavior {
5153 write!(f, " {}", drop_behavior)?;
5154 }
5155 Ok(())
5156 }
5157}
5158
5159impl Spanned for DropOperatorClass {
5160 fn span(&self) -> Span {
5161 Span::empty()
5162 }
5163}
5164
5165#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5167#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5168#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5169pub enum OperatorFamilyItem {
5170 Operator {
5172 strategy_number: u64,
5174 operator_name: ObjectName,
5176 op_types: Vec<DataType>,
5178 purpose: Option<OperatorPurpose>,
5180 },
5181 Function {
5183 support_number: u64,
5185 op_types: Option<Vec<DataType>>,
5187 function_name: ObjectName,
5189 argument_types: Vec<DataType>,
5191 },
5192}
5193
5194#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5196#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5197#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5198pub enum OperatorFamilyDropItem {
5199 Operator {
5201 strategy_number: u64,
5203 op_types: Vec<DataType>,
5205 },
5206 Function {
5208 support_number: u64,
5210 op_types: Vec<DataType>,
5212 },
5213}
5214
5215impl fmt::Display for OperatorFamilyItem {
5216 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5217 match self {
5218 OperatorFamilyItem::Operator {
5219 strategy_number,
5220 operator_name,
5221 op_types,
5222 purpose,
5223 } => {
5224 write!(
5225 f,
5226 "OPERATOR {strategy_number} {operator_name} ({})",
5227 display_comma_separated(op_types)
5228 )?;
5229 if let Some(purpose) = purpose {
5230 write!(f, " {purpose}")?;
5231 }
5232 Ok(())
5233 }
5234 OperatorFamilyItem::Function {
5235 support_number,
5236 op_types,
5237 function_name,
5238 argument_types,
5239 } => {
5240 write!(f, "FUNCTION {support_number}")?;
5241 if let Some(types) = op_types {
5242 write!(f, " ({})", display_comma_separated(types))?;
5243 }
5244 write!(f, " {function_name}")?;
5245 if !argument_types.is_empty() {
5246 write!(f, "({})", display_comma_separated(argument_types))?;
5247 }
5248 Ok(())
5249 }
5250 }
5251 }
5252}
5253
5254impl fmt::Display for OperatorFamilyDropItem {
5255 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5256 match self {
5257 OperatorFamilyDropItem::Operator {
5258 strategy_number,
5259 op_types,
5260 } => {
5261 write!(
5262 f,
5263 "OPERATOR {strategy_number} ({})",
5264 display_comma_separated(op_types)
5265 )
5266 }
5267 OperatorFamilyDropItem::Function {
5268 support_number,
5269 op_types,
5270 } => {
5271 write!(
5272 f,
5273 "FUNCTION {support_number} ({})",
5274 display_comma_separated(op_types)
5275 )
5276 }
5277 }
5278 }
5279}
5280
5281#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5284#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5285#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5286pub struct AlterOperatorFamily {
5287 pub name: ObjectName,
5289 pub using: Ident,
5291 pub operation: AlterOperatorFamilyOperation,
5293}
5294
5295#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5297#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5298#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5299pub enum AlterOperatorFamilyOperation {
5300 Add {
5302 items: Vec<OperatorFamilyItem>,
5304 },
5305 Drop {
5307 items: Vec<OperatorFamilyDropItem>,
5309 },
5310 RenameTo {
5312 new_name: ObjectName,
5314 },
5315 OwnerTo(Owner),
5317 SetSchema {
5319 schema_name: ObjectName,
5321 },
5322}
5323
5324impl fmt::Display for AlterOperatorFamily {
5325 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5326 write!(
5327 f,
5328 "ALTER OPERATOR FAMILY {} USING {}",
5329 self.name, self.using
5330 )?;
5331 write!(f, " {}", self.operation)
5332 }
5333}
5334
5335impl fmt::Display for AlterOperatorFamilyOperation {
5336 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5337 match self {
5338 AlterOperatorFamilyOperation::Add { items } => {
5339 write!(f, "ADD {}", display_comma_separated(items))
5340 }
5341 AlterOperatorFamilyOperation::Drop { items } => {
5342 write!(f, "DROP {}", display_comma_separated(items))
5343 }
5344 AlterOperatorFamilyOperation::RenameTo { new_name } => {
5345 write!(f, "RENAME TO {new_name}")
5346 }
5347 AlterOperatorFamilyOperation::OwnerTo(owner) => {
5348 write!(f, "OWNER TO {owner}")
5349 }
5350 AlterOperatorFamilyOperation::SetSchema { schema_name } => {
5351 write!(f, "SET SCHEMA {schema_name}")
5352 }
5353 }
5354 }
5355}
5356
5357impl Spanned for AlterOperatorFamily {
5358 fn span(&self) -> Span {
5359 Span::empty()
5360 }
5361}
5362
5363#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5366#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5367#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5368pub struct AlterOperatorClass {
5369 pub name: ObjectName,
5371 pub using: Ident,
5373 pub operation: AlterOperatorClassOperation,
5375}
5376
5377#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5379#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5380#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5381pub enum AlterOperatorClassOperation {
5382 RenameTo {
5385 new_name: ObjectName,
5387 },
5388 OwnerTo(Owner),
5390 SetSchema {
5393 schema_name: ObjectName,
5395 },
5396}
5397
5398impl fmt::Display for AlterOperatorClass {
5399 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5400 write!(f, "ALTER OPERATOR CLASS {} USING {}", self.name, self.using)?;
5401 write!(f, " {}", self.operation)
5402 }
5403}
5404
5405impl fmt::Display for AlterOperatorClassOperation {
5406 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5407 match self {
5408 AlterOperatorClassOperation::RenameTo { new_name } => {
5409 write!(f, "RENAME TO {new_name}")
5410 }
5411 AlterOperatorClassOperation::OwnerTo(owner) => {
5412 write!(f, "OWNER TO {owner}")
5413 }
5414 AlterOperatorClassOperation::SetSchema { schema_name } => {
5415 write!(f, "SET SCHEMA {schema_name}")
5416 }
5417 }
5418 }
5419}
5420
5421impl Spanned for AlterOperatorClass {
5422 fn span(&self) -> Span {
5423 Span::empty()
5424 }
5425}
5426
5427#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5429#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5430#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5431pub struct AlterFunction {
5432 pub kind: AlterFunctionKind,
5434 pub function: FunctionDesc,
5436 pub aggregate_order_by: Option<Vec<OperateFunctionArg>>,
5440 pub aggregate_star: bool,
5444 pub operation: AlterFunctionOperation,
5446}
5447
5448#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5450#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5451#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5452pub enum AlterFunctionKind {
5453 Function,
5455 Aggregate,
5457}
5458
5459impl fmt::Display for AlterFunctionKind {
5460 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5461 match self {
5462 Self::Function => write!(f, "FUNCTION"),
5463 Self::Aggregate => write!(f, "AGGREGATE"),
5464 }
5465 }
5466}
5467
5468#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5470#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5471#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5472pub enum AlterFunctionOperation {
5473 RenameTo {
5475 new_name: Ident,
5477 },
5478 OwnerTo(Owner),
5480 SetSchema {
5482 schema_name: ObjectName,
5484 },
5485 DependsOnExtension {
5487 no: bool,
5489 extension_name: ObjectName,
5491 },
5492 Actions {
5494 actions: Vec<AlterFunctionAction>,
5496 restrict: bool,
5498 },
5499}
5500
5501#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5503#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5504#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5505pub enum AlterFunctionAction {
5506 CalledOnNull(FunctionCalledOnNull),
5508 Behavior(FunctionBehavior),
5510 Leakproof(bool),
5512 Security {
5514 external: bool,
5516 security: FunctionSecurity,
5518 },
5519 Parallel(FunctionParallel),
5521 Cost(Expr),
5523 Rows(Expr),
5525 Support(ObjectName),
5527 Set(FunctionDefinitionSetParam),
5530 Reset(ResetConfig),
5532}
5533
5534impl fmt::Display for AlterFunction {
5535 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5536 write!(f, "ALTER {} ", self.kind)?;
5537 match self.kind {
5538 AlterFunctionKind::Function => {
5539 write!(f, "{} ", self.function)?;
5540 }
5541 AlterFunctionKind::Aggregate => {
5542 write!(f, "{}(", self.function.name)?;
5543 if self.aggregate_star {
5544 write!(f, "*")?;
5545 } else {
5546 if let Some(args) = &self.function.args {
5547 write!(f, "{}", display_comma_separated(args))?;
5548 }
5549 if let Some(order_by_args) = &self.aggregate_order_by {
5550 if self
5551 .function
5552 .args
5553 .as_ref()
5554 .is_some_and(|args| !args.is_empty())
5555 {
5556 write!(f, " ")?;
5557 }
5558 write!(f, "ORDER BY {}", display_comma_separated(order_by_args))?;
5559 }
5560 }
5561 write!(f, ") ")?;
5562 }
5563 }
5564 write!(f, "{}", self.operation)
5565 }
5566}
5567
5568impl fmt::Display for AlterFunctionOperation {
5569 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5570 match self {
5571 AlterFunctionOperation::RenameTo { new_name } => {
5572 write!(f, "RENAME TO {new_name}")
5573 }
5574 AlterFunctionOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
5575 AlterFunctionOperation::SetSchema { schema_name } => {
5576 write!(f, "SET SCHEMA {schema_name}")
5577 }
5578 AlterFunctionOperation::DependsOnExtension { no, extension_name } => {
5579 if *no {
5580 write!(f, "NO DEPENDS ON EXTENSION {extension_name}")
5581 } else {
5582 write!(f, "DEPENDS ON EXTENSION {extension_name}")
5583 }
5584 }
5585 AlterFunctionOperation::Actions { actions, restrict } => {
5586 write!(f, "{}", display_separated(actions, " "))?;
5587 if *restrict {
5588 write!(f, " RESTRICT")?;
5589 }
5590 Ok(())
5591 }
5592 }
5593 }
5594}
5595
5596impl fmt::Display for AlterFunctionAction {
5597 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5598 match self {
5599 AlterFunctionAction::CalledOnNull(called_on_null) => write!(f, "{called_on_null}"),
5600 AlterFunctionAction::Behavior(behavior) => write!(f, "{behavior}"),
5601 AlterFunctionAction::Leakproof(leakproof) => {
5602 if *leakproof {
5603 write!(f, "LEAKPROOF")
5604 } else {
5605 write!(f, "NOT LEAKPROOF")
5606 }
5607 }
5608 AlterFunctionAction::Security { external, security } => {
5609 if *external {
5610 write!(f, "EXTERNAL ")?;
5611 }
5612 write!(f, "{security}")
5613 }
5614 AlterFunctionAction::Parallel(parallel) => write!(f, "{parallel}"),
5615 AlterFunctionAction::Cost(execution_cost) => write!(f, "COST {execution_cost}"),
5616 AlterFunctionAction::Rows(result_rows) => write!(f, "ROWS {result_rows}"),
5617 AlterFunctionAction::Support(support_function) => {
5618 write!(f, "SUPPORT {support_function}")
5619 }
5620 AlterFunctionAction::Set(set_param) => write!(f, "{set_param}"),
5621 AlterFunctionAction::Reset(reset_config) => match reset_config {
5622 ResetConfig::ALL => write!(f, "RESET ALL"),
5623 ResetConfig::ConfigName(name) => write!(f, "RESET {name}"),
5624 },
5625 }
5626 }
5627}
5628
5629impl Spanned for AlterFunction {
5630 fn span(&self) -> Span {
5631 Span::empty()
5632 }
5633}
5634
5635#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5639#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5640#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5641pub struct CreatePolicy {
5642 pub name: Ident,
5644 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5646 pub table_name: ObjectName,
5647 pub policy_type: Option<CreatePolicyType>,
5649 pub command: Option<CreatePolicyCommand>,
5651 pub to: Option<Vec<Owner>>,
5653 pub using: Option<Expr>,
5655 pub with_check: Option<Expr>,
5657}
5658
5659impl fmt::Display for CreatePolicy {
5660 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5661 write!(
5662 f,
5663 "CREATE POLICY {name} ON {table_name}",
5664 name = self.name,
5665 table_name = self.table_name,
5666 )?;
5667 if let Some(ref policy_type) = self.policy_type {
5668 write!(f, " AS {policy_type}")?;
5669 }
5670 if let Some(ref command) = self.command {
5671 write!(f, " FOR {command}")?;
5672 }
5673 if let Some(ref to) = self.to {
5674 write!(f, " TO {}", display_comma_separated(to))?;
5675 }
5676 if let Some(ref using) = self.using {
5677 write!(f, " USING ({using})")?;
5678 }
5679 if let Some(ref with_check) = self.with_check {
5680 write!(f, " WITH CHECK ({with_check})")?;
5681 }
5682 Ok(())
5683 }
5684}
5685
5686#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5692#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5693#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5694pub enum CreatePolicyType {
5695 Permissive,
5697 Restrictive,
5699}
5700
5701impl fmt::Display for CreatePolicyType {
5702 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5703 match self {
5704 CreatePolicyType::Permissive => write!(f, "PERMISSIVE"),
5705 CreatePolicyType::Restrictive => write!(f, "RESTRICTIVE"),
5706 }
5707 }
5708}
5709
5710#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5716#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5717#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5718pub enum CreatePolicyCommand {
5719 All,
5721 Select,
5723 Insert,
5725 Update,
5727 Delete,
5729}
5730
5731impl fmt::Display for CreatePolicyCommand {
5732 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5733 match self {
5734 CreatePolicyCommand::All => write!(f, "ALL"),
5735 CreatePolicyCommand::Select => write!(f, "SELECT"),
5736 CreatePolicyCommand::Insert => write!(f, "INSERT"),
5737 CreatePolicyCommand::Update => write!(f, "UPDATE"),
5738 CreatePolicyCommand::Delete => write!(f, "DELETE"),
5739 }
5740 }
5741}
5742
5743#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5747#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5748#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5749pub struct DropPolicy {
5750 pub if_exists: bool,
5752 pub name: Ident,
5754 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5756 pub table_name: ObjectName,
5757 pub drop_behavior: Option<DropBehavior>,
5759}
5760
5761impl fmt::Display for DropPolicy {
5762 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5763 write!(
5764 f,
5765 "DROP POLICY {if_exists}{name} ON {table_name}",
5766 if_exists = if self.if_exists { "IF EXISTS " } else { "" },
5767 name = self.name,
5768 table_name = self.table_name
5769 )?;
5770 if let Some(ref behavior) = self.drop_behavior {
5771 write!(f, " {behavior}")?;
5772 }
5773 Ok(())
5774 }
5775}
5776
5777impl From<CreatePolicy> for crate::ast::Statement {
5778 fn from(v: CreatePolicy) -> Self {
5779 crate::ast::Statement::CreatePolicy(v)
5780 }
5781}
5782
5783impl From<DropPolicy> for crate::ast::Statement {
5784 fn from(v: DropPolicy) -> Self {
5785 crate::ast::Statement::DropPolicy(v)
5786 }
5787}
5788
5789#[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 AlterPolicy {
5799 pub name: Ident,
5801 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5803 pub table_name: ObjectName,
5804 pub operation: AlterPolicyOperation,
5806}
5807
5808impl fmt::Display for AlterPolicy {
5809 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5810 write!(
5811 f,
5812 "ALTER POLICY {name} ON {table_name}{operation}",
5813 name = self.name,
5814 table_name = self.table_name,
5815 operation = self.operation
5816 )
5817 }
5818}
5819
5820impl From<AlterPolicy> for crate::ast::Statement {
5821 fn from(v: AlterPolicy) -> Self {
5822 crate::ast::Statement::AlterPolicy(v)
5823 }
5824}