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 sequence_options.is_some() {
2117 let so = sequence_options.as_ref().unwrap();
2118 if !so.is_empty() {
2119 write!(f, " (")?;
2120 }
2121 for sequence_option in so {
2122 write!(f, "{sequence_option}")?;
2123 }
2124 if !so.is_empty() {
2125 write!(f, " )")?;
2126 }
2127 }
2128 Ok(())
2129 }
2130 }
2131 Options(options) => {
2132 write!(f, "OPTIONS({})", display_comma_separated(options))
2133 }
2134 Identity(parameters) => {
2135 write!(f, "{parameters}")
2136 }
2137 OnConflict(keyword) => {
2138 write!(f, "ON CONFLICT {keyword:?}")?;
2139 Ok(())
2140 }
2141 Policy(parameters) => {
2142 write!(f, "{parameters}")
2143 }
2144 Tags(tags) => {
2145 write!(f, "{tags}")
2146 }
2147 Srid(srid) => {
2148 write!(f, "SRID {srid}")
2149 }
2150 Invisible => {
2151 write!(f, "INVISIBLE")
2152 }
2153 }
2154 }
2155}
2156
2157#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2160#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2161#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2162pub enum GeneratedAs {
2163 Always,
2165 ByDefault,
2167 ExpStored,
2169}
2170
2171#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2174#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2175#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2176pub enum GeneratedExpressionMode {
2177 Virtual,
2179 Stored,
2181}
2182
2183#[must_use]
2184pub(crate) fn display_constraint_name(name: &'_ Option<Ident>) -> impl fmt::Display + '_ {
2185 struct ConstraintName<'a>(&'a Option<Ident>);
2186 impl fmt::Display for ConstraintName<'_> {
2187 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2188 if let Some(name) = self.0 {
2189 write!(f, "CONSTRAINT {name} ")?;
2190 }
2191 Ok(())
2192 }
2193 }
2194 ConstraintName(name)
2195}
2196
2197#[must_use]
2201pub(crate) fn display_option<'a, T: fmt::Display>(
2202 prefix: &'a str,
2203 postfix: &'a str,
2204 option: &'a Option<T>,
2205) -> impl fmt::Display + 'a {
2206 struct OptionDisplay<'a, T>(&'a str, &'a str, &'a Option<T>);
2207 impl<T: fmt::Display> fmt::Display for OptionDisplay<'_, T> {
2208 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2209 if let Some(inner) = self.2 {
2210 let (prefix, postfix) = (self.0, self.1);
2211 write!(f, "{prefix}{inner}{postfix}")?;
2212 }
2213 Ok(())
2214 }
2215 }
2216 OptionDisplay(prefix, postfix, option)
2217}
2218
2219#[must_use]
2223pub(crate) fn display_option_spaced<T: fmt::Display>(option: &Option<T>) -> impl fmt::Display + '_ {
2224 display_option(" ", "", option)
2225}
2226
2227#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Default, Eq, Ord, Hash)]
2231#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2232#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2233pub struct ConstraintCharacteristics {
2234 pub deferrable: Option<bool>,
2236 pub initially: Option<DeferrableInitial>,
2238 pub enforced: Option<bool>,
2240}
2241
2242#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2244#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2245#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2246pub enum DeferrableInitial {
2247 Immediate,
2249 Deferred,
2251}
2252
2253impl ConstraintCharacteristics {
2254 fn deferrable_text(&self) -> Option<&'static str> {
2255 self.deferrable.map(|deferrable| {
2256 if deferrable {
2257 "DEFERRABLE"
2258 } else {
2259 "NOT DEFERRABLE"
2260 }
2261 })
2262 }
2263
2264 fn initially_immediate_text(&self) -> Option<&'static str> {
2265 self.initially
2266 .map(|initially_immediate| match initially_immediate {
2267 DeferrableInitial::Immediate => "INITIALLY IMMEDIATE",
2268 DeferrableInitial::Deferred => "INITIALLY DEFERRED",
2269 })
2270 }
2271
2272 fn enforced_text(&self) -> Option<&'static str> {
2273 self.enforced.map(
2274 |enforced| {
2275 if enforced {
2276 "ENFORCED"
2277 } else {
2278 "NOT ENFORCED"
2279 }
2280 },
2281 )
2282 }
2283}
2284
2285impl fmt::Display for ConstraintCharacteristics {
2286 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2287 let deferrable = self.deferrable_text();
2288 let initially_immediate = self.initially_immediate_text();
2289 let enforced = self.enforced_text();
2290
2291 match (deferrable, initially_immediate, enforced) {
2292 (None, None, None) => Ok(()),
2293 (None, None, Some(enforced)) => write!(f, "{enforced}"),
2294 (None, Some(initial), None) => write!(f, "{initial}"),
2295 (None, Some(initial), Some(enforced)) => write!(f, "{initial} {enforced}"),
2296 (Some(deferrable), None, None) => write!(f, "{deferrable}"),
2297 (Some(deferrable), None, Some(enforced)) => write!(f, "{deferrable} {enforced}"),
2298 (Some(deferrable), Some(initial), None) => write!(f, "{deferrable} {initial}"),
2299 (Some(deferrable), Some(initial), Some(enforced)) => {
2300 write!(f, "{deferrable} {initial} {enforced}")
2301 }
2302 }
2303 }
2304}
2305
2306#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2311#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2312#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2313pub enum ReferentialAction {
2314 Restrict,
2316 Cascade,
2318 SetNull,
2320 NoAction,
2322 SetDefault,
2324}
2325
2326impl fmt::Display for ReferentialAction {
2327 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2328 f.write_str(match self {
2329 ReferentialAction::Restrict => "RESTRICT",
2330 ReferentialAction::Cascade => "CASCADE",
2331 ReferentialAction::SetNull => "SET NULL",
2332 ReferentialAction::NoAction => "NO ACTION",
2333 ReferentialAction::SetDefault => "SET DEFAULT",
2334 })
2335 }
2336}
2337
2338#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2342#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2343#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2344pub enum DropBehavior {
2345 Restrict,
2347 Cascade,
2349}
2350
2351impl fmt::Display for DropBehavior {
2352 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2353 f.write_str(match self {
2354 DropBehavior::Restrict => "RESTRICT",
2355 DropBehavior::Cascade => "CASCADE",
2356 })
2357 }
2358}
2359
2360#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2362#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2363#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2364pub enum UserDefinedTypeRepresentation {
2365 Composite {
2367 attributes: Vec<UserDefinedTypeCompositeAttributeDef>,
2369 },
2370 Enum {
2375 labels: Vec<Ident>,
2377 },
2378 Range {
2382 options: Vec<UserDefinedTypeRangeOption>,
2384 },
2385 SqlDefinition {
2391 options: Vec<UserDefinedTypeSqlDefinitionOption>,
2393 },
2394}
2395
2396impl fmt::Display for UserDefinedTypeRepresentation {
2397 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2398 match self {
2399 Self::Composite { attributes } => {
2400 write!(f, "AS ({})", display_comma_separated(attributes))
2401 }
2402 Self::Enum { labels } => {
2403 write!(f, "AS ENUM ({})", display_comma_separated(labels))
2404 }
2405 Self::Range { options } => {
2406 write!(f, "AS RANGE ({})", display_comma_separated(options))
2407 }
2408 Self::SqlDefinition { options } => {
2409 write!(f, "({})", display_comma_separated(options))
2410 }
2411 }
2412 }
2413}
2414
2415#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2417#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2418#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2419pub struct UserDefinedTypeCompositeAttributeDef {
2420 pub name: Ident,
2422 pub data_type: DataType,
2424 pub collation: Option<ObjectName>,
2426}
2427
2428impl fmt::Display for UserDefinedTypeCompositeAttributeDef {
2429 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2430 write!(f, "{} {}", self.name, self.data_type)?;
2431 if let Some(collation) = &self.collation {
2432 write!(f, " COLLATE {collation}")?;
2433 }
2434 Ok(())
2435 }
2436}
2437
2438#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2461#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2462#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2463pub enum UserDefinedTypeInternalLength {
2464 Fixed(u64),
2466 Variable,
2468}
2469
2470impl fmt::Display for UserDefinedTypeInternalLength {
2471 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2472 match self {
2473 UserDefinedTypeInternalLength::Fixed(n) => write!(f, "{}", n),
2474 UserDefinedTypeInternalLength::Variable => write!(f, "VARIABLE"),
2475 }
2476 }
2477}
2478
2479#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2498#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2499#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2500pub enum Alignment {
2501 Char,
2503 Int2,
2505 Int4,
2507 Double,
2509}
2510
2511impl fmt::Display for Alignment {
2512 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2513 match self {
2514 Alignment::Char => write!(f, "char"),
2515 Alignment::Int2 => write!(f, "int2"),
2516 Alignment::Int4 => write!(f, "int4"),
2517 Alignment::Double => write!(f, "double"),
2518 }
2519 }
2520}
2521
2522#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2542#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2543#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2544pub enum UserDefinedTypeStorage {
2545 Plain,
2547 External,
2549 Extended,
2551 Main,
2553}
2554
2555impl fmt::Display for UserDefinedTypeStorage {
2556 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2557 match self {
2558 UserDefinedTypeStorage::Plain => write!(f, "plain"),
2559 UserDefinedTypeStorage::External => write!(f, "external"),
2560 UserDefinedTypeStorage::Extended => write!(f, "extended"),
2561 UserDefinedTypeStorage::Main => write!(f, "main"),
2562 }
2563 }
2564}
2565
2566#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2584#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2585#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2586pub enum UserDefinedTypeRangeOption {
2587 Subtype(DataType),
2589 SubtypeOpClass(ObjectName),
2591 Collation(ObjectName),
2593 Canonical(ObjectName),
2595 SubtypeDiff(ObjectName),
2597 MultirangeTypeName(ObjectName),
2599}
2600
2601impl fmt::Display for UserDefinedTypeRangeOption {
2602 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2603 match self {
2604 UserDefinedTypeRangeOption::Subtype(dt) => write!(f, "SUBTYPE = {}", dt),
2605 UserDefinedTypeRangeOption::SubtypeOpClass(name) => {
2606 write!(f, "SUBTYPE_OPCLASS = {}", name)
2607 }
2608 UserDefinedTypeRangeOption::Collation(name) => write!(f, "COLLATION = {}", name),
2609 UserDefinedTypeRangeOption::Canonical(name) => write!(f, "CANONICAL = {}", name),
2610 UserDefinedTypeRangeOption::SubtypeDiff(name) => write!(f, "SUBTYPE_DIFF = {}", name),
2611 UserDefinedTypeRangeOption::MultirangeTypeName(name) => {
2612 write!(f, "MULTIRANGE_TYPE_NAME = {}", name)
2613 }
2614 }
2615 }
2616}
2617
2618#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2639#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2640#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2641pub enum UserDefinedTypeSqlDefinitionOption {
2642 Input(ObjectName),
2644 Output(ObjectName),
2646 Receive(ObjectName),
2648 Send(ObjectName),
2650 TypmodIn(ObjectName),
2652 TypmodOut(ObjectName),
2654 Analyze(ObjectName),
2656 Subscript(ObjectName),
2658 InternalLength(UserDefinedTypeInternalLength),
2660 PassedByValue,
2662 Alignment(Alignment),
2664 Storage(UserDefinedTypeStorage),
2666 Like(ObjectName),
2668 Category(char),
2670 Preferred(bool),
2672 Default(Expr),
2674 Element(DataType),
2676 Delimiter(String),
2678 Collatable(bool),
2680}
2681
2682impl fmt::Display for UserDefinedTypeSqlDefinitionOption {
2683 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2684 match self {
2685 UserDefinedTypeSqlDefinitionOption::Input(name) => write!(f, "INPUT = {}", name),
2686 UserDefinedTypeSqlDefinitionOption::Output(name) => write!(f, "OUTPUT = {}", name),
2687 UserDefinedTypeSqlDefinitionOption::Receive(name) => write!(f, "RECEIVE = {}", name),
2688 UserDefinedTypeSqlDefinitionOption::Send(name) => write!(f, "SEND = {}", name),
2689 UserDefinedTypeSqlDefinitionOption::TypmodIn(name) => write!(f, "TYPMOD_IN = {}", name),
2690 UserDefinedTypeSqlDefinitionOption::TypmodOut(name) => {
2691 write!(f, "TYPMOD_OUT = {}", name)
2692 }
2693 UserDefinedTypeSqlDefinitionOption::Analyze(name) => write!(f, "ANALYZE = {}", name),
2694 UserDefinedTypeSqlDefinitionOption::Subscript(name) => {
2695 write!(f, "SUBSCRIPT = {}", name)
2696 }
2697 UserDefinedTypeSqlDefinitionOption::InternalLength(len) => {
2698 write!(f, "INTERNALLENGTH = {}", len)
2699 }
2700 UserDefinedTypeSqlDefinitionOption::PassedByValue => write!(f, "PASSEDBYVALUE"),
2701 UserDefinedTypeSqlDefinitionOption::Alignment(align) => {
2702 write!(f, "ALIGNMENT = {}", align)
2703 }
2704 UserDefinedTypeSqlDefinitionOption::Storage(storage) => {
2705 write!(f, "STORAGE = {}", storage)
2706 }
2707 UserDefinedTypeSqlDefinitionOption::Like(name) => write!(f, "LIKE = {}", name),
2708 UserDefinedTypeSqlDefinitionOption::Category(c) => write!(f, "CATEGORY = '{}'", c),
2709 UserDefinedTypeSqlDefinitionOption::Preferred(b) => write!(f, "PREFERRED = {}", b),
2710 UserDefinedTypeSqlDefinitionOption::Default(expr) => write!(f, "DEFAULT = {}", expr),
2711 UserDefinedTypeSqlDefinitionOption::Element(dt) => write!(f, "ELEMENT = {}", dt),
2712 UserDefinedTypeSqlDefinitionOption::Delimiter(s) => {
2713 write!(f, "DELIMITER = '{}'", escape_single_quote_string(s))
2714 }
2715 UserDefinedTypeSqlDefinitionOption::Collatable(b) => write!(f, "COLLATABLE = {}", b),
2716 }
2717 }
2718}
2719
2720#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2724#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2725#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2726pub enum Partition {
2727 Identifier(Ident),
2729 Expr(Expr),
2731 Part(Expr),
2734 Partitions(Vec<Expr>),
2736}
2737
2738impl fmt::Display for Partition {
2739 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2740 match self {
2741 Partition::Identifier(id) => write!(f, "PARTITION ID {id}"),
2742 Partition::Expr(expr) => write!(f, "PARTITION {expr}"),
2743 Partition::Part(expr) => write!(f, "PART {expr}"),
2744 Partition::Partitions(partitions) => {
2745 write!(f, "PARTITION ({})", display_comma_separated(partitions))
2746 }
2747 }
2748 }
2749}
2750
2751#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2754#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2755#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2756pub enum Deduplicate {
2757 All,
2759 ByExpression(Expr),
2761}
2762
2763impl fmt::Display for Deduplicate {
2764 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2765 match self {
2766 Deduplicate::All => write!(f, "DEDUPLICATE"),
2767 Deduplicate::ByExpression(expr) => write!(f, "DEDUPLICATE BY {expr}"),
2768 }
2769 }
2770}
2771
2772#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2777#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2778#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2779pub struct ClusteredBy {
2780 pub columns: Vec<Ident>,
2782 pub sorted_by: Option<Vec<OrderByExpr>>,
2784 pub num_buckets: Value,
2786}
2787
2788impl fmt::Display for ClusteredBy {
2789 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2790 write!(
2791 f,
2792 "CLUSTERED BY ({})",
2793 display_comma_separated(&self.columns)
2794 )?;
2795 if let Some(ref sorted_by) = self.sorted_by {
2796 write!(f, " SORTED BY ({})", display_comma_separated(sorted_by))?;
2797 }
2798 write!(f, " INTO {} BUCKETS", self.num_buckets)
2799 }
2800}
2801
2802#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2804#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2805#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2806pub struct CreateIndex {
2807 pub name: Option<ObjectName>,
2809 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2810 pub table_name: ObjectName,
2812 pub using: Option<IndexType>,
2815 pub columns: Vec<IndexColumn>,
2817 pub unique: bool,
2819 pub concurrently: bool,
2821 pub r#async: bool,
2823 pub if_not_exists: bool,
2825 pub include: Vec<Ident>,
2827 pub nulls_distinct: Option<bool>,
2829 pub with: Vec<Expr>,
2831 pub predicate: Option<Expr>,
2833 pub index_options: Vec<IndexOption>,
2835 pub alter_options: Vec<AlterTableOperation>,
2842}
2843
2844impl fmt::Display for CreateIndex {
2845 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2846 write!(
2847 f,
2848 "CREATE {unique}INDEX {concurrently}{async_}{if_not_exists}",
2849 unique = if self.unique { "UNIQUE " } else { "" },
2850 concurrently = if self.concurrently {
2851 "CONCURRENTLY "
2852 } else {
2853 ""
2854 },
2855 async_ = if self.r#async { "ASYNC " } else { "" },
2856 if_not_exists = if self.if_not_exists {
2857 "IF NOT EXISTS "
2858 } else {
2859 ""
2860 },
2861 )?;
2862 if let Some(value) = &self.name {
2863 write!(f, "{value} ")?;
2864 }
2865 write!(f, "ON {}", self.table_name)?;
2866 if let Some(value) = &self.using {
2867 write!(f, " USING {value} ")?;
2868 }
2869 write!(f, "({})", display_comma_separated(&self.columns))?;
2870 if !self.include.is_empty() {
2871 write!(f, " INCLUDE ({})", display_comma_separated(&self.include))?;
2872 }
2873 if let Some(value) = self.nulls_distinct {
2874 if value {
2875 write!(f, " NULLS DISTINCT")?;
2876 } else {
2877 write!(f, " NULLS NOT DISTINCT")?;
2878 }
2879 }
2880 if !self.with.is_empty() {
2881 write!(f, " WITH ({})", display_comma_separated(&self.with))?;
2882 }
2883 if let Some(predicate) = &self.predicate {
2884 write!(f, " WHERE {predicate}")?;
2885 }
2886 if !self.index_options.is_empty() {
2887 write!(f, " {}", display_separated(&self.index_options, " "))?;
2888 }
2889 if !self.alter_options.is_empty() {
2890 write!(f, " {}", display_separated(&self.alter_options, " "))?;
2891 }
2892 Ok(())
2893 }
2894}
2895
2896#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2898#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2899#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2900pub struct CreateTable {
2901 pub or_replace: bool,
2903 pub temporary: bool,
2905 pub external: bool,
2907 pub dynamic: bool,
2909 pub global: Option<bool>,
2911 pub if_not_exists: bool,
2913 pub transient: bool,
2915 pub volatile: bool,
2917 pub iceberg: bool,
2919 pub snapshot: bool,
2922 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2924 pub name: ObjectName,
2925 pub columns: Vec<ColumnDef>,
2927 pub constraints: Vec<TableConstraint>,
2929 pub hive_distribution: HiveDistributionStyle,
2931 pub hive_formats: Option<HiveFormat>,
2933 pub table_options: CreateTableOptions,
2935 pub file_format: Option<FileFormat>,
2937 pub location: Option<String>,
2939 pub query: Option<Box<Query>>,
2941 pub without_rowid: bool,
2943 pub like: Option<CreateTableLikeKind>,
2945 pub clone: Option<ObjectName>,
2947 pub version: Option<TableVersion>,
2949 pub comment: Option<CommentDef>,
2953 pub on_commit: Option<OnCommit>,
2956 pub on_cluster: Option<Ident>,
2959 pub primary_key: Option<Box<Expr>>,
2962 pub order_by: Option<OneOrManyWithParens<Expr>>,
2966 pub partition_by: Option<Box<Expr>>,
2969 pub cluster_by: Option<WrappedCollection<Vec<Expr>>>,
2974 pub clustered_by: Option<ClusteredBy>,
2977 pub inherits: Option<Vec<ObjectName>>,
2982 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2986 pub partition_of: Option<ObjectName>,
2987 pub for_values: Option<ForValues>,
2990 pub strict: bool,
2994 pub copy_grants: bool,
2997 pub enable_schema_evolution: Option<bool>,
3000 pub change_tracking: Option<bool>,
3003 pub data_retention_time_in_days: Option<u64>,
3006 pub max_data_extension_time_in_days: Option<u64>,
3009 pub default_ddl_collation: Option<String>,
3012 pub with_aggregation_policy: Option<ObjectName>,
3015 pub with_row_access_policy: Option<RowAccessPolicy>,
3018 pub with_storage_lifecycle_policy: Option<StorageLifecyclePolicy>,
3021 pub with_tags: Option<Vec<Tag>>,
3024 pub external_volume: Option<String>,
3027 pub base_location: Option<String>,
3030 pub catalog: Option<String>,
3033 pub catalog_sync: Option<String>,
3036 pub storage_serialization_policy: Option<StorageSerializationPolicy>,
3039 pub target_lag: Option<String>,
3042 pub warehouse: Option<Ident>,
3045 pub refresh_mode: Option<RefreshModeKind>,
3048 pub initialize: Option<InitializeKind>,
3051 pub require_user: bool,
3054 pub diststyle: Option<DistStyle>,
3057 pub distkey: Option<Expr>,
3060 pub sortkey: Option<Vec<Expr>>,
3063 pub backup: Option<bool>,
3066}
3067
3068impl fmt::Display for CreateTable {
3069 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3070 write!(
3078 f,
3079 "CREATE {or_replace}{external}{global}{temporary}{transient}{volatile}{dynamic}{iceberg}{snapshot}TABLE {if_not_exists}{name}",
3080 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3081 external = if self.external { "EXTERNAL " } else { "" },
3082 snapshot = if self.snapshot { "SNAPSHOT " } else { "" },
3083 global = self.global
3084 .map(|global| {
3085 if global {
3086 "GLOBAL "
3087 } else {
3088 "LOCAL "
3089 }
3090 })
3091 .unwrap_or(""),
3092 if_not_exists = if self.if_not_exists { "IF NOT EXISTS " } else { "" },
3093 temporary = if self.temporary { "TEMPORARY " } else { "" },
3094 transient = if self.transient { "TRANSIENT " } else { "" },
3095 volatile = if self.volatile { "VOLATILE " } else { "" },
3096 iceberg = if self.iceberg { "ICEBERG " } else { "" },
3098 dynamic = if self.dynamic { "DYNAMIC " } else { "" },
3099 name = self.name,
3100 )?;
3101 if let Some(partition_of) = &self.partition_of {
3102 write!(f, " PARTITION OF {partition_of}")?;
3103 }
3104 if let Some(on_cluster) = &self.on_cluster {
3105 write!(f, " ON CLUSTER {on_cluster}")?;
3106 }
3107 if !self.columns.is_empty() || !self.constraints.is_empty() {
3108 f.write_str(" (")?;
3109 NewLine.fmt(f)?;
3110 Indent(DisplayCommaSeparated(&self.columns)).fmt(f)?;
3111 if !self.columns.is_empty() && !self.constraints.is_empty() {
3112 f.write_str(",")?;
3113 SpaceOrNewline.fmt(f)?;
3114 }
3115 Indent(DisplayCommaSeparated(&self.constraints)).fmt(f)?;
3116 NewLine.fmt(f)?;
3117 f.write_str(")")?;
3118 } else if self.query.is_none()
3119 && self.like.is_none()
3120 && self.clone.is_none()
3121 && self.partition_of.is_none()
3122 {
3123 f.write_str(" ()")?;
3125 } else if let Some(CreateTableLikeKind::Parenthesized(like_in_columns_list)) = &self.like {
3126 write!(f, " ({like_in_columns_list})")?;
3127 }
3128 if let Some(for_values) = &self.for_values {
3129 write!(f, " {for_values}")?;
3130 }
3131
3132 if let Some(comment) = &self.comment {
3135 write!(f, " COMMENT '{comment}'")?;
3136 }
3137
3138 if self.without_rowid {
3140 write!(f, " WITHOUT ROWID")?;
3141 }
3142
3143 if let Some(CreateTableLikeKind::Plain(like)) = &self.like {
3144 write!(f, " {like}")?;
3145 }
3146
3147 if let Some(c) = &self.clone {
3148 write!(f, " CLONE {c}")?;
3149 }
3150
3151 if let Some(version) = &self.version {
3152 write!(f, " {version}")?;
3153 }
3154
3155 match &self.hive_distribution {
3156 HiveDistributionStyle::PARTITIONED { columns } => {
3157 write!(f, " PARTITIONED BY ({})", display_comma_separated(columns))?;
3158 }
3159 HiveDistributionStyle::SKEWED {
3160 columns,
3161 on,
3162 stored_as_directories,
3163 } => {
3164 write!(
3165 f,
3166 " SKEWED BY ({})) ON ({})",
3167 display_comma_separated(columns),
3168 display_comma_separated(on)
3169 )?;
3170 if *stored_as_directories {
3171 write!(f, " STORED AS DIRECTORIES")?;
3172 }
3173 }
3174 _ => (),
3175 }
3176
3177 if let Some(clustered_by) = &self.clustered_by {
3178 write!(f, " {clustered_by}")?;
3179 }
3180
3181 if let Some(HiveFormat {
3182 row_format,
3183 serde_properties,
3184 storage,
3185 location,
3186 }) = &self.hive_formats
3187 {
3188 match row_format {
3189 Some(HiveRowFormat::SERDE { class }) => write!(f, " ROW FORMAT SERDE '{class}'")?,
3190 Some(HiveRowFormat::DELIMITED { delimiters }) => {
3191 write!(f, " ROW FORMAT DELIMITED")?;
3192 if !delimiters.is_empty() {
3193 write!(f, " {}", display_separated(delimiters, " "))?;
3194 }
3195 }
3196 None => (),
3197 }
3198 match storage {
3199 Some(HiveIOFormat::IOF {
3200 input_format,
3201 output_format,
3202 }) => write!(
3203 f,
3204 " STORED AS INPUTFORMAT {input_format} OUTPUTFORMAT {output_format}"
3205 )?,
3206 Some(HiveIOFormat::FileFormat { format }) if !self.external => {
3207 write!(f, " STORED AS {format}")?
3208 }
3209 _ => (),
3210 }
3211 if let Some(serde_properties) = serde_properties.as_ref() {
3212 write!(
3213 f,
3214 " WITH SERDEPROPERTIES ({})",
3215 display_comma_separated(serde_properties)
3216 )?;
3217 }
3218 if !self.external {
3219 if let Some(loc) = location {
3220 write!(f, " LOCATION '{loc}'")?;
3221 }
3222 }
3223 }
3224 if self.external {
3225 if let Some(file_format) = self.file_format {
3226 write!(f, " STORED AS {file_format}")?;
3227 }
3228 if let Some(location) = &self.location {
3229 write!(f, " LOCATION '{location}'")?;
3230 }
3231 }
3232
3233 match &self.table_options {
3234 options @ CreateTableOptions::With(_)
3235 | options @ CreateTableOptions::Plain(_)
3236 | options @ CreateTableOptions::TableProperties(_) => write!(f, " {options}")?,
3237 _ => (),
3238 }
3239
3240 if let Some(primary_key) = &self.primary_key {
3241 write!(f, " PRIMARY KEY {primary_key}")?;
3242 }
3243 if let Some(order_by) = &self.order_by {
3244 write!(f, " ORDER BY {order_by}")?;
3245 }
3246 if let Some(inherits) = &self.inherits {
3247 write!(f, " INHERITS ({})", display_comma_separated(inherits))?;
3248 }
3249 if let Some(partition_by) = self.partition_by.as_ref() {
3250 write!(f, " PARTITION BY {partition_by}")?;
3251 }
3252 if let Some(cluster_by) = self.cluster_by.as_ref() {
3253 write!(f, " CLUSTER BY {cluster_by}")?;
3254 }
3255 if let options @ CreateTableOptions::Options(_) = &self.table_options {
3256 write!(f, " {options}")?;
3257 }
3258 if let Some(external_volume) = self.external_volume.as_ref() {
3259 write!(f, " EXTERNAL_VOLUME='{external_volume}'")?;
3260 }
3261
3262 if let Some(catalog) = self.catalog.as_ref() {
3263 write!(f, " CATALOG='{catalog}'")?;
3264 }
3265
3266 if self.iceberg {
3267 if let Some(base_location) = self.base_location.as_ref() {
3268 write!(f, " BASE_LOCATION='{base_location}'")?;
3269 }
3270 }
3271
3272 if let Some(catalog_sync) = self.catalog_sync.as_ref() {
3273 write!(f, " CATALOG_SYNC='{catalog_sync}'")?;
3274 }
3275
3276 if let Some(storage_serialization_policy) = self.storage_serialization_policy.as_ref() {
3277 write!(
3278 f,
3279 " STORAGE_SERIALIZATION_POLICY={storage_serialization_policy}"
3280 )?;
3281 }
3282
3283 if self.copy_grants {
3284 write!(f, " COPY GRANTS")?;
3285 }
3286
3287 if let Some(is_enabled) = self.enable_schema_evolution {
3288 write!(
3289 f,
3290 " ENABLE_SCHEMA_EVOLUTION={}",
3291 if is_enabled { "TRUE" } else { "FALSE" }
3292 )?;
3293 }
3294
3295 if let Some(is_enabled) = self.change_tracking {
3296 write!(
3297 f,
3298 " CHANGE_TRACKING={}",
3299 if is_enabled { "TRUE" } else { "FALSE" }
3300 )?;
3301 }
3302
3303 if let Some(data_retention_time_in_days) = self.data_retention_time_in_days {
3304 write!(
3305 f,
3306 " DATA_RETENTION_TIME_IN_DAYS={data_retention_time_in_days}",
3307 )?;
3308 }
3309
3310 if let Some(max_data_extension_time_in_days) = self.max_data_extension_time_in_days {
3311 write!(
3312 f,
3313 " MAX_DATA_EXTENSION_TIME_IN_DAYS={max_data_extension_time_in_days}",
3314 )?;
3315 }
3316
3317 if let Some(default_ddl_collation) = &self.default_ddl_collation {
3318 write!(f, " DEFAULT_DDL_COLLATION='{default_ddl_collation}'",)?;
3319 }
3320
3321 if let Some(with_aggregation_policy) = &self.with_aggregation_policy {
3322 write!(f, " WITH AGGREGATION POLICY {with_aggregation_policy}",)?;
3323 }
3324
3325 if let Some(row_access_policy) = &self.with_row_access_policy {
3326 write!(f, " {row_access_policy}",)?;
3327 }
3328
3329 if let Some(storage_lifecycle_policy) = &self.with_storage_lifecycle_policy {
3330 write!(f, " {storage_lifecycle_policy}",)?;
3331 }
3332
3333 if let Some(tag) = &self.with_tags {
3334 write!(f, " WITH TAG ({})", display_comma_separated(tag.as_slice()))?;
3335 }
3336
3337 if let Some(target_lag) = &self.target_lag {
3338 write!(f, " TARGET_LAG='{target_lag}'")?;
3339 }
3340
3341 if let Some(warehouse) = &self.warehouse {
3342 write!(f, " WAREHOUSE={warehouse}")?;
3343 }
3344
3345 if let Some(refresh_mode) = &self.refresh_mode {
3346 write!(f, " REFRESH_MODE={refresh_mode}")?;
3347 }
3348
3349 if let Some(initialize) = &self.initialize {
3350 write!(f, " INITIALIZE={initialize}")?;
3351 }
3352
3353 if self.require_user {
3354 write!(f, " REQUIRE USER")?;
3355 }
3356
3357 if self.on_commit.is_some() {
3358 let on_commit = match self.on_commit {
3359 Some(OnCommit::DeleteRows) => "ON COMMIT DELETE ROWS",
3360 Some(OnCommit::PreserveRows) => "ON COMMIT PRESERVE ROWS",
3361 Some(OnCommit::Drop) => "ON COMMIT DROP",
3362 None => "",
3363 };
3364 write!(f, " {on_commit}")?;
3365 }
3366 if self.strict {
3367 write!(f, " STRICT")?;
3368 }
3369 if let Some(backup) = self.backup {
3370 write!(f, " BACKUP {}", if backup { "YES" } else { "NO" })?;
3371 }
3372 if let Some(diststyle) = &self.diststyle {
3373 write!(f, " DISTSTYLE {diststyle}")?;
3374 }
3375 if let Some(distkey) = &self.distkey {
3376 write!(f, " DISTKEY({distkey})")?;
3377 }
3378 if let Some(sortkey) = &self.sortkey {
3379 write!(f, " SORTKEY({})", display_comma_separated(sortkey))?;
3380 }
3381 if let Some(query) = &self.query {
3382 write!(f, " AS {query}")?;
3383 }
3384 Ok(())
3385 }
3386}
3387
3388#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3394#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3395#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3396pub enum ForValues {
3397 In(Vec<Expr>),
3399 From {
3401 from: Vec<PartitionBoundValue>,
3403 to: Vec<PartitionBoundValue>,
3405 },
3406 With {
3408 modulus: u64,
3410 remainder: u64,
3412 },
3413 Default,
3415}
3416
3417impl fmt::Display for ForValues {
3418 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3419 match self {
3420 ForValues::In(values) => {
3421 write!(f, "FOR VALUES IN ({})", display_comma_separated(values))
3422 }
3423 ForValues::From { from, to } => {
3424 write!(
3425 f,
3426 "FOR VALUES FROM ({}) TO ({})",
3427 display_comma_separated(from),
3428 display_comma_separated(to)
3429 )
3430 }
3431 ForValues::With { modulus, remainder } => {
3432 write!(
3433 f,
3434 "FOR VALUES WITH (MODULUS {modulus}, REMAINDER {remainder})"
3435 )
3436 }
3437 ForValues::Default => write!(f, "DEFAULT"),
3438 }
3439 }
3440}
3441
3442#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3447#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3448#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3449pub enum PartitionBoundValue {
3450 Expr(Expr),
3452 MinValue,
3454 MaxValue,
3456}
3457
3458impl fmt::Display for PartitionBoundValue {
3459 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3460 match self {
3461 PartitionBoundValue::Expr(expr) => write!(f, "{expr}"),
3462 PartitionBoundValue::MinValue => write!(f, "MINVALUE"),
3463 PartitionBoundValue::MaxValue => write!(f, "MAXVALUE"),
3464 }
3465 }
3466}
3467
3468#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3472#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3473#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3474pub enum DistStyle {
3475 Auto,
3477 Even,
3479 Key,
3481 All,
3483}
3484
3485impl fmt::Display for DistStyle {
3486 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3487 match self {
3488 DistStyle::Auto => write!(f, "AUTO"),
3489 DistStyle::Even => write!(f, "EVEN"),
3490 DistStyle::Key => write!(f, "KEY"),
3491 DistStyle::All => write!(f, "ALL"),
3492 }
3493 }
3494}
3495
3496#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3497#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3498#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3499pub struct CreateDomain {
3512 pub name: ObjectName,
3514 pub data_type: DataType,
3516 pub collation: Option<Ident>,
3518 pub default: Option<Expr>,
3520 pub constraints: Vec<TableConstraint>,
3522}
3523
3524impl fmt::Display for CreateDomain {
3525 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3526 write!(
3527 f,
3528 "CREATE DOMAIN {name} AS {data_type}",
3529 name = self.name,
3530 data_type = self.data_type
3531 )?;
3532 if let Some(collation) = &self.collation {
3533 write!(f, " COLLATE {collation}")?;
3534 }
3535 if let Some(default) = &self.default {
3536 write!(f, " DEFAULT {default}")?;
3537 }
3538 if !self.constraints.is_empty() {
3539 write!(f, " {}", display_separated(&self.constraints, " "))?;
3540 }
3541 Ok(())
3542 }
3543}
3544
3545#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3547#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3548#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3549pub enum FunctionReturnType {
3550 DataType(DataType),
3552 SetOf(DataType),
3556}
3557
3558impl fmt::Display for FunctionReturnType {
3559 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3560 match self {
3561 FunctionReturnType::DataType(data_type) => write!(f, "{data_type}"),
3562 FunctionReturnType::SetOf(data_type) => write!(f, "SETOF {data_type}"),
3563 }
3564 }
3565}
3566
3567#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3568#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3569#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3570pub struct CreateFunction {
3572 pub or_alter: bool,
3576 pub or_replace: bool,
3578 pub temporary: bool,
3580 pub if_not_exists: bool,
3582 pub name: ObjectName,
3584 pub args: Option<Vec<OperateFunctionArg>>,
3586 pub return_type: Option<FunctionReturnType>,
3588 pub function_body: Option<CreateFunctionBody>,
3596 pub behavior: Option<FunctionBehavior>,
3602 pub called_on_null: Option<FunctionCalledOnNull>,
3606 pub parallel: Option<FunctionParallel>,
3610 pub security: Option<FunctionSecurity>,
3614 pub set_params: Vec<FunctionDefinitionSetParam>,
3618 pub using: Option<CreateFunctionUsing>,
3620 pub language: Option<Ident>,
3628 pub determinism_specifier: Option<FunctionDeterminismSpecifier>,
3632 pub options: Option<Vec<SqlOption>>,
3636 pub remote_connection: Option<ObjectName>,
3646}
3647
3648impl fmt::Display for CreateFunction {
3649 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3650 write!(
3651 f,
3652 "CREATE {or_alter}{or_replace}{temp}FUNCTION {if_not_exists}{name}",
3653 name = self.name,
3654 temp = if self.temporary { "TEMPORARY " } else { "" },
3655 or_alter = if self.or_alter { "OR ALTER " } else { "" },
3656 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3657 if_not_exists = if self.if_not_exists {
3658 "IF NOT EXISTS "
3659 } else {
3660 ""
3661 },
3662 )?;
3663 if let Some(args) = &self.args {
3664 write!(f, "({})", display_comma_separated(args))?;
3665 }
3666 if let Some(return_type) = &self.return_type {
3667 write!(f, " RETURNS {return_type}")?;
3668 }
3669 if let Some(determinism_specifier) = &self.determinism_specifier {
3670 write!(f, " {determinism_specifier}")?;
3671 }
3672 if let Some(language) = &self.language {
3673 write!(f, " LANGUAGE {language}")?;
3674 }
3675 if let Some(behavior) = &self.behavior {
3676 write!(f, " {behavior}")?;
3677 }
3678 if let Some(called_on_null) = &self.called_on_null {
3679 write!(f, " {called_on_null}")?;
3680 }
3681 if let Some(parallel) = &self.parallel {
3682 write!(f, " {parallel}")?;
3683 }
3684 if let Some(security) = &self.security {
3685 write!(f, " {security}")?;
3686 }
3687 for set_param in &self.set_params {
3688 write!(f, " {set_param}")?;
3689 }
3690 if let Some(remote_connection) = &self.remote_connection {
3691 write!(f, " REMOTE WITH CONNECTION {remote_connection}")?;
3692 }
3693 if let Some(CreateFunctionBody::AsBeforeOptions { body, link_symbol }) = &self.function_body
3694 {
3695 write!(f, " AS {body}")?;
3696 if let Some(link_symbol) = link_symbol {
3697 write!(f, ", {link_symbol}")?;
3698 }
3699 }
3700 if let Some(CreateFunctionBody::Return(function_body)) = &self.function_body {
3701 write!(f, " RETURN {function_body}")?;
3702 }
3703 if let Some(CreateFunctionBody::AsReturnExpr(function_body)) = &self.function_body {
3704 write!(f, " AS RETURN {function_body}")?;
3705 }
3706 if let Some(CreateFunctionBody::AsReturnSelect(function_body)) = &self.function_body {
3707 write!(f, " AS RETURN {function_body}")?;
3708 }
3709 if let Some(using) = &self.using {
3710 write!(f, " {using}")?;
3711 }
3712 if let Some(options) = &self.options {
3713 write!(
3714 f,
3715 " OPTIONS({})",
3716 display_comma_separated(options.as_slice())
3717 )?;
3718 }
3719 if let Some(CreateFunctionBody::AsAfterOptions(function_body)) = &self.function_body {
3720 write!(f, " AS {function_body}")?;
3721 }
3722 if let Some(CreateFunctionBody::AsBeginEnd(bes)) = &self.function_body {
3723 write!(f, " AS {bes}")?;
3724 }
3725 Ok(())
3726 }
3727}
3728
3729#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3739#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3740#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3741pub struct CreateConnector {
3742 pub name: Ident,
3744 pub if_not_exists: bool,
3746 pub connector_type: Option<String>,
3748 pub url: Option<String>,
3750 pub comment: Option<CommentDef>,
3752 pub with_dcproperties: Option<Vec<SqlOption>>,
3754}
3755
3756impl fmt::Display for CreateConnector {
3757 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3758 write!(
3759 f,
3760 "CREATE CONNECTOR {if_not_exists}{name}",
3761 if_not_exists = if self.if_not_exists {
3762 "IF NOT EXISTS "
3763 } else {
3764 ""
3765 },
3766 name = self.name,
3767 )?;
3768
3769 if let Some(connector_type) = &self.connector_type {
3770 write!(f, " TYPE '{connector_type}'")?;
3771 }
3772
3773 if let Some(url) = &self.url {
3774 write!(f, " URL '{url}'")?;
3775 }
3776
3777 if let Some(comment) = &self.comment {
3778 write!(f, " COMMENT = '{comment}'")?;
3779 }
3780
3781 if let Some(with_dcproperties) = &self.with_dcproperties {
3782 write!(
3783 f,
3784 " WITH DCPROPERTIES({})",
3785 display_comma_separated(with_dcproperties)
3786 )?;
3787 }
3788
3789 Ok(())
3790 }
3791}
3792
3793#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3798#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3799#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3800pub enum AlterSchemaOperation {
3801 SetDefaultCollate {
3803 collate: Expr,
3805 },
3806 AddReplica {
3808 replica: Ident,
3810 options: Option<Vec<SqlOption>>,
3812 },
3813 DropReplica {
3815 replica: Ident,
3817 },
3818 SetOptionsParens {
3820 options: Vec<SqlOption>,
3822 },
3823 Rename {
3825 name: ObjectName,
3827 },
3828 OwnerTo {
3830 owner: Owner,
3832 },
3833}
3834
3835impl fmt::Display for AlterSchemaOperation {
3836 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3837 match self {
3838 AlterSchemaOperation::SetDefaultCollate { collate } => {
3839 write!(f, "SET DEFAULT COLLATE {collate}")
3840 }
3841 AlterSchemaOperation::AddReplica { replica, options } => {
3842 write!(f, "ADD REPLICA {replica}")?;
3843 if let Some(options) = options {
3844 write!(f, " OPTIONS ({})", display_comma_separated(options))?;
3845 }
3846 Ok(())
3847 }
3848 AlterSchemaOperation::DropReplica { replica } => write!(f, "DROP REPLICA {replica}"),
3849 AlterSchemaOperation::SetOptionsParens { options } => {
3850 write!(f, "SET OPTIONS ({})", display_comma_separated(options))
3851 }
3852 AlterSchemaOperation::Rename { name } => write!(f, "RENAME TO {name}"),
3853 AlterSchemaOperation::OwnerTo { owner } => write!(f, "OWNER TO {owner}"),
3854 }
3855 }
3856}
3857#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3863#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3864#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3865pub enum RenameTableNameKind {
3866 As(ObjectName),
3868 To(ObjectName),
3870}
3871
3872impl fmt::Display for RenameTableNameKind {
3873 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3874 match self {
3875 RenameTableNameKind::As(name) => write!(f, "AS {name}"),
3876 RenameTableNameKind::To(name) => write!(f, "TO {name}"),
3877 }
3878 }
3879}
3880
3881#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3882#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3883#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3884pub struct AlterSchema {
3886 pub name: ObjectName,
3888 pub if_exists: bool,
3890 pub operations: Vec<AlterSchemaOperation>,
3892}
3893
3894impl fmt::Display for AlterSchema {
3895 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3896 write!(f, "ALTER SCHEMA ")?;
3897 if self.if_exists {
3898 write!(f, "IF EXISTS ")?;
3899 }
3900 write!(f, "{}", self.name)?;
3901 for operation in &self.operations {
3902 write!(f, " {operation}")?;
3903 }
3904
3905 Ok(())
3906 }
3907}
3908
3909impl Spanned for RenameTableNameKind {
3910 fn span(&self) -> Span {
3911 match self {
3912 RenameTableNameKind::As(name) => name.span(),
3913 RenameTableNameKind::To(name) => name.span(),
3914 }
3915 }
3916}
3917
3918#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
3919#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3920#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3921pub enum TriggerObjectKind {
3923 For(TriggerObject),
3925 ForEach(TriggerObject),
3927}
3928
3929impl Display for TriggerObjectKind {
3930 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3931 match self {
3932 TriggerObjectKind::For(obj) => write!(f, "FOR {obj}"),
3933 TriggerObjectKind::ForEach(obj) => write!(f, "FOR EACH {obj}"),
3934 }
3935 }
3936}
3937
3938#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3939#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3940#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3941pub struct CreateTrigger {
3955 pub or_alter: bool,
3959 pub temporary: bool,
3976 pub or_replace: bool,
3986 pub is_constraint: bool,
3988 pub name: ObjectName,
3990 pub period: Option<TriggerPeriod>,
4019 pub period_before_table: bool,
4030 pub events: Vec<TriggerEvent>,
4032 pub table_name: ObjectName,
4034 pub referenced_table_name: Option<ObjectName>,
4037 pub referencing: Vec<TriggerReferencing>,
4039 pub trigger_object: Option<TriggerObjectKind>,
4044 pub condition: Option<Expr>,
4046 pub exec_body: Option<TriggerExecBody>,
4048 pub statements_as: bool,
4050 pub statements: Option<ConditionalStatements>,
4052 pub characteristics: Option<ConstraintCharacteristics>,
4054}
4055
4056impl Display for CreateTrigger {
4057 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4058 let CreateTrigger {
4059 or_alter,
4060 temporary,
4061 or_replace,
4062 is_constraint,
4063 name,
4064 period_before_table,
4065 period,
4066 events,
4067 table_name,
4068 referenced_table_name,
4069 referencing,
4070 trigger_object,
4071 condition,
4072 exec_body,
4073 statements_as,
4074 statements,
4075 characteristics,
4076 } = self;
4077 write!(
4078 f,
4079 "CREATE {temporary}{or_alter}{or_replace}{is_constraint}TRIGGER {name} ",
4080 temporary = if *temporary { "TEMPORARY " } else { "" },
4081 or_alter = if *or_alter { "OR ALTER " } else { "" },
4082 or_replace = if *or_replace { "OR REPLACE " } else { "" },
4083 is_constraint = if *is_constraint { "CONSTRAINT " } else { "" },
4084 )?;
4085
4086 if *period_before_table {
4087 if let Some(p) = period {
4088 write!(f, "{p} ")?;
4089 }
4090 if !events.is_empty() {
4091 write!(f, "{} ", display_separated(events, " OR "))?;
4092 }
4093 write!(f, "ON {table_name}")?;
4094 } else {
4095 write!(f, "ON {table_name} ")?;
4096 if let Some(p) = period {
4097 write!(f, "{p}")?;
4098 }
4099 if !events.is_empty() {
4100 write!(f, " {}", display_separated(events, ", "))?;
4101 }
4102 }
4103
4104 if let Some(referenced_table_name) = referenced_table_name {
4105 write!(f, " FROM {referenced_table_name}")?;
4106 }
4107
4108 if let Some(characteristics) = characteristics {
4109 write!(f, " {characteristics}")?;
4110 }
4111
4112 if !referencing.is_empty() {
4113 write!(f, " REFERENCING {}", display_separated(referencing, " "))?;
4114 }
4115
4116 if let Some(trigger_object) = trigger_object {
4117 write!(f, " {trigger_object}")?;
4118 }
4119 if let Some(condition) = condition {
4120 write!(f, " WHEN {condition}")?;
4121 }
4122 if let Some(exec_body) = exec_body {
4123 write!(f, " EXECUTE {exec_body}")?;
4124 }
4125 if let Some(statements) = statements {
4126 if *statements_as {
4127 write!(f, " AS")?;
4128 }
4129 write!(f, " {statements}")?;
4130 }
4131 Ok(())
4132 }
4133}
4134
4135#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4136#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4137#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4138pub struct DropTrigger {
4145 pub if_exists: bool,
4147 pub trigger_name: ObjectName,
4149 pub table_name: Option<ObjectName>,
4151 pub option: Option<ReferentialAction>,
4153}
4154
4155impl fmt::Display for DropTrigger {
4156 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4157 let DropTrigger {
4158 if_exists,
4159 trigger_name,
4160 table_name,
4161 option,
4162 } = self;
4163 write!(f, "DROP TRIGGER")?;
4164 if *if_exists {
4165 write!(f, " IF EXISTS")?;
4166 }
4167 match &table_name {
4168 Some(table_name) => write!(f, " {trigger_name} ON {table_name}")?,
4169 None => write!(f, " {trigger_name}")?,
4170 };
4171 if let Some(option) = option {
4172 write!(f, " {option}")?;
4173 }
4174 Ok(())
4175 }
4176}
4177
4178#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4184#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4185#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4186pub struct Truncate {
4187 pub table_names: Vec<super::TruncateTableTarget>,
4189 pub partitions: Option<Vec<Expr>>,
4191 pub table: bool,
4193 pub if_exists: bool,
4195 pub identity: Option<super::TruncateIdentityOption>,
4197 pub cascade: Option<super::CascadeOption>,
4199 pub on_cluster: Option<Ident>,
4202}
4203
4204impl fmt::Display for Truncate {
4205 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4206 let table = if self.table { "TABLE " } else { "" };
4207 let if_exists = if self.if_exists { "IF EXISTS " } else { "" };
4208
4209 write!(
4210 f,
4211 "TRUNCATE {table}{if_exists}{table_names}",
4212 table_names = display_comma_separated(&self.table_names)
4213 )?;
4214
4215 if let Some(identity) = &self.identity {
4216 match identity {
4217 super::TruncateIdentityOption::Restart => write!(f, " RESTART IDENTITY")?,
4218 super::TruncateIdentityOption::Continue => write!(f, " CONTINUE IDENTITY")?,
4219 }
4220 }
4221 if let Some(cascade) = &self.cascade {
4222 match cascade {
4223 super::CascadeOption::Cascade => write!(f, " CASCADE")?,
4224 super::CascadeOption::Restrict => write!(f, " RESTRICT")?,
4225 }
4226 }
4227
4228 if let Some(ref parts) = &self.partitions {
4229 if !parts.is_empty() {
4230 write!(f, " PARTITION ({})", display_comma_separated(parts))?;
4231 }
4232 }
4233 if let Some(on_cluster) = &self.on_cluster {
4234 write!(f, " ON CLUSTER {on_cluster}")?;
4235 }
4236 Ok(())
4237 }
4238}
4239
4240impl Spanned for Truncate {
4241 fn span(&self) -> Span {
4242 Span::union_iter(
4243 self.table_names.iter().map(|i| i.name.span()).chain(
4244 self.partitions
4245 .iter()
4246 .flat_map(|i| i.iter().map(|k| k.span())),
4247 ),
4248 )
4249 }
4250}
4251
4252#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4259#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4260#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4261pub struct Msck {
4262 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4264 pub table_name: ObjectName,
4265 pub repair: bool,
4267 pub partition_action: Option<super::AddDropSync>,
4269}
4270
4271impl fmt::Display for Msck {
4272 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4273 write!(
4274 f,
4275 "MSCK {repair}TABLE {table}",
4276 repair = if self.repair { "REPAIR " } else { "" },
4277 table = self.table_name
4278 )?;
4279 if let Some(pa) = &self.partition_action {
4280 write!(f, " {pa}")?;
4281 }
4282 Ok(())
4283 }
4284}
4285
4286impl Spanned for Msck {
4287 fn span(&self) -> Span {
4288 self.table_name.span()
4289 }
4290}
4291
4292#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4294#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4295#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4296pub struct CreateView {
4297 pub or_alter: bool,
4301 pub or_replace: bool,
4303 pub materialized: bool,
4305 pub secure: bool,
4308 pub name: ObjectName,
4310 pub name_before_not_exists: bool,
4321 pub columns: Vec<ViewColumnDef>,
4323 pub query: Box<Query>,
4325 pub options: CreateTableOptions,
4327 pub cluster_by: Vec<Ident>,
4329 pub comment: Option<String>,
4332 pub with_no_schema_binding: bool,
4334 pub if_not_exists: bool,
4336 pub temporary: bool,
4338 pub copy_grants: bool,
4341 pub to: Option<ObjectName>,
4344 pub params: Option<CreateViewParams>,
4346}
4347
4348impl fmt::Display for CreateView {
4349 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4350 write!(
4351 f,
4352 "CREATE {or_alter}{or_replace}",
4353 or_alter = if self.or_alter { "OR ALTER " } else { "" },
4354 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
4355 )?;
4356 if let Some(ref params) = self.params {
4357 params.fmt(f)?;
4358 }
4359 write!(
4360 f,
4361 "{secure}{materialized}{temporary}VIEW {if_not_and_name}{to}",
4362 if_not_and_name = if self.if_not_exists {
4363 if self.name_before_not_exists {
4364 format!("{} IF NOT EXISTS", self.name)
4365 } else {
4366 format!("IF NOT EXISTS {}", self.name)
4367 }
4368 } else {
4369 format!("{}", self.name)
4370 },
4371 secure = if self.secure { "SECURE " } else { "" },
4372 materialized = if self.materialized {
4373 "MATERIALIZED "
4374 } else {
4375 ""
4376 },
4377 temporary = if self.temporary { "TEMPORARY " } else { "" },
4378 to = self
4379 .to
4380 .as_ref()
4381 .map(|to| format!(" TO {to}"))
4382 .unwrap_or_default()
4383 )?;
4384 if self.copy_grants {
4385 write!(f, " COPY GRANTS")?;
4386 }
4387 if !self.columns.is_empty() {
4388 write!(f, " ({})", display_comma_separated(&self.columns))?;
4389 }
4390 if matches!(self.options, CreateTableOptions::With(_)) {
4391 write!(f, " {}", self.options)?;
4392 }
4393 if let Some(ref comment) = self.comment {
4394 write!(f, " COMMENT = '{}'", escape_single_quote_string(comment))?;
4395 }
4396 if !self.cluster_by.is_empty() {
4397 write!(
4398 f,
4399 " CLUSTER BY ({})",
4400 display_comma_separated(&self.cluster_by)
4401 )?;
4402 }
4403 if matches!(self.options, CreateTableOptions::Options(_)) {
4404 write!(f, " {}", self.options)?;
4405 }
4406 f.write_str(" AS")?;
4407 SpaceOrNewline.fmt(f)?;
4408 self.query.fmt(f)?;
4409 if self.with_no_schema_binding {
4410 write!(f, " WITH NO SCHEMA BINDING")?;
4411 }
4412 Ok(())
4413 }
4414}
4415
4416#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4419#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4420#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4421pub struct CreateExtension {
4422 pub name: Ident,
4424 pub if_not_exists: bool,
4426 pub cascade: bool,
4428 pub schema: Option<Ident>,
4430 pub version: Option<Ident>,
4432}
4433
4434impl fmt::Display for CreateExtension {
4435 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4436 write!(
4437 f,
4438 "CREATE EXTENSION {if_not_exists}{name}",
4439 if_not_exists = if self.if_not_exists {
4440 "IF NOT EXISTS "
4441 } else {
4442 ""
4443 },
4444 name = self.name
4445 )?;
4446 if self.cascade || self.schema.is_some() || self.version.is_some() {
4447 write!(f, " WITH")?;
4448
4449 if let Some(name) = &self.schema {
4450 write!(f, " SCHEMA {name}")?;
4451 }
4452 if let Some(version) = &self.version {
4453 write!(f, " VERSION {version}")?;
4454 }
4455 if self.cascade {
4456 write!(f, " CASCADE")?;
4457 }
4458 }
4459
4460 Ok(())
4461 }
4462}
4463
4464impl Spanned for CreateExtension {
4465 fn span(&self) -> Span {
4466 Span::empty()
4467 }
4468}
4469
4470#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4478#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4479#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4480pub struct DropExtension {
4481 pub names: Vec<Ident>,
4483 pub if_exists: bool,
4485 pub cascade_or_restrict: Option<ReferentialAction>,
4487}
4488
4489impl fmt::Display for DropExtension {
4490 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4491 write!(f, "DROP EXTENSION")?;
4492 if self.if_exists {
4493 write!(f, " IF EXISTS")?;
4494 }
4495 write!(f, " {}", display_comma_separated(&self.names))?;
4496 if let Some(cascade_or_restrict) = &self.cascade_or_restrict {
4497 write!(f, " {cascade_or_restrict}")?;
4498 }
4499 Ok(())
4500 }
4501}
4502
4503impl Spanned for DropExtension {
4504 fn span(&self) -> Span {
4505 Span::empty()
4506 }
4507}
4508
4509#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4512#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4513#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4514pub struct CreateCollation {
4515 pub if_not_exists: bool,
4517 pub name: ObjectName,
4519 pub definition: CreateCollationDefinition,
4521}
4522
4523#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4525#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4526#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4527pub enum CreateCollationDefinition {
4528 From(ObjectName),
4534 Options(Vec<SqlOption>),
4540}
4541
4542impl fmt::Display for CreateCollation {
4543 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4544 write!(
4545 f,
4546 "CREATE COLLATION {if_not_exists}{name}",
4547 if_not_exists = if self.if_not_exists {
4548 "IF NOT EXISTS "
4549 } else {
4550 ""
4551 },
4552 name = self.name
4553 )?;
4554 match &self.definition {
4555 CreateCollationDefinition::From(existing_collation) => {
4556 write!(f, " FROM {existing_collation}")
4557 }
4558 CreateCollationDefinition::Options(options) => {
4559 write!(f, " ({})", display_comma_separated(options))
4560 }
4561 }
4562 }
4563}
4564
4565impl Spanned for CreateCollation {
4566 fn span(&self) -> Span {
4567 Span::empty()
4568 }
4569}
4570
4571#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4574#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4575#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4576pub struct AlterCollation {
4577 pub name: ObjectName,
4579 pub operation: AlterCollationOperation,
4581}
4582
4583#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4585#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4586#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4587pub enum AlterCollationOperation {
4588 RenameTo {
4594 new_name: Ident,
4596 },
4597 OwnerTo(Owner),
4603 SetSchema {
4609 schema_name: ObjectName,
4611 },
4612 RefreshVersion,
4618}
4619
4620impl fmt::Display for AlterCollationOperation {
4621 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4622 match self {
4623 AlterCollationOperation::RenameTo { new_name } => write!(f, "RENAME TO {new_name}"),
4624 AlterCollationOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
4625 AlterCollationOperation::SetSchema { schema_name } => {
4626 write!(f, "SET SCHEMA {schema_name}")
4627 }
4628 AlterCollationOperation::RefreshVersion => write!(f, "REFRESH VERSION"),
4629 }
4630 }
4631}
4632
4633impl fmt::Display for AlterCollation {
4634 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4635 write!(f, "ALTER COLLATION {} {}", self.name, self.operation)
4636 }
4637}
4638
4639impl Spanned for AlterCollation {
4640 fn span(&self) -> Span {
4641 Span::empty()
4642 }
4643}
4644
4645#[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 AlterTableType {
4651 Iceberg,
4654 Dynamic,
4657 External,
4660}
4661
4662#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4664#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4665#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4666pub struct AlterTable {
4667 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4669 pub name: ObjectName,
4670 pub if_exists: bool,
4672 pub only: bool,
4674 pub operations: Vec<AlterTableOperation>,
4676 pub location: Option<HiveSetLocation>,
4678 pub on_cluster: Option<Ident>,
4682 pub table_type: Option<AlterTableType>,
4684 pub end_token: AttachedToken,
4686}
4687
4688impl fmt::Display for AlterTable {
4689 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4690 match &self.table_type {
4691 Some(AlterTableType::Iceberg) => write!(f, "ALTER ICEBERG TABLE ")?,
4692 Some(AlterTableType::Dynamic) => write!(f, "ALTER DYNAMIC TABLE ")?,
4693 Some(AlterTableType::External) => write!(f, "ALTER EXTERNAL TABLE ")?,
4694 None => write!(f, "ALTER TABLE ")?,
4695 }
4696
4697 if self.if_exists {
4698 write!(f, "IF EXISTS ")?;
4699 }
4700 if self.only {
4701 write!(f, "ONLY ")?;
4702 }
4703 write!(f, "{} ", &self.name)?;
4704 if let Some(cluster) = &self.on_cluster {
4705 write!(f, "ON CLUSTER {cluster} ")?;
4706 }
4707 write!(f, "{}", display_comma_separated(&self.operations))?;
4708 if let Some(loc) = &self.location {
4709 write!(f, " {loc}")?
4710 }
4711 Ok(())
4712 }
4713}
4714
4715#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4717#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4718#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4719pub struct DropFunction {
4720 pub if_exists: bool,
4722 pub func_desc: Vec<FunctionDesc>,
4724 pub drop_behavior: Option<DropBehavior>,
4726}
4727
4728impl fmt::Display for DropFunction {
4729 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4730 write!(
4731 f,
4732 "DROP FUNCTION{} {}",
4733 if self.if_exists { " IF EXISTS" } else { "" },
4734 display_comma_separated(&self.func_desc),
4735 )?;
4736 if let Some(op) = &self.drop_behavior {
4737 write!(f, " {op}")?;
4738 }
4739 Ok(())
4740 }
4741}
4742
4743impl Spanned for DropFunction {
4744 fn span(&self) -> Span {
4745 Span::empty()
4746 }
4747}
4748
4749#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4752#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4753#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4754pub struct CreateOperator {
4755 pub name: ObjectName,
4757 pub function: ObjectName,
4759 pub is_procedure: bool,
4761 pub left_arg: Option<DataType>,
4763 pub right_arg: Option<DataType>,
4765 pub options: Vec<OperatorOption>,
4767}
4768
4769#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4772#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4773#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4774pub struct CreateOperatorFamily {
4775 pub name: ObjectName,
4777 pub using: Ident,
4779}
4780
4781#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4784#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4785#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4786pub struct CreateOperatorClass {
4787 pub name: ObjectName,
4789 pub default: bool,
4791 pub for_type: DataType,
4793 pub using: Ident,
4795 pub family: Option<ObjectName>,
4797 pub items: Vec<OperatorClassItem>,
4799}
4800
4801impl fmt::Display for CreateOperator {
4802 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4803 write!(f, "CREATE OPERATOR {} (", self.name)?;
4804
4805 let function_keyword = if self.is_procedure {
4806 "PROCEDURE"
4807 } else {
4808 "FUNCTION"
4809 };
4810 let mut params = vec![format!("{} = {}", function_keyword, self.function)];
4811
4812 if let Some(left_arg) = &self.left_arg {
4813 params.push(format!("LEFTARG = {}", left_arg));
4814 }
4815 if let Some(right_arg) = &self.right_arg {
4816 params.push(format!("RIGHTARG = {}", right_arg));
4817 }
4818
4819 for option in &self.options {
4820 params.push(option.to_string());
4821 }
4822
4823 write!(f, "{}", params.join(", "))?;
4824 write!(f, ")")
4825 }
4826}
4827
4828impl fmt::Display for CreateOperatorFamily {
4829 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4830 write!(
4831 f,
4832 "CREATE OPERATOR FAMILY {} USING {}",
4833 self.name, self.using
4834 )
4835 }
4836}
4837
4838impl fmt::Display for CreateOperatorClass {
4839 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4840 write!(f, "CREATE OPERATOR CLASS {}", self.name)?;
4841 if self.default {
4842 write!(f, " DEFAULT")?;
4843 }
4844 write!(f, " FOR TYPE {} USING {}", self.for_type, self.using)?;
4845 if let Some(family) = &self.family {
4846 write!(f, " FAMILY {}", family)?;
4847 }
4848 write!(f, " AS {}", display_comma_separated(&self.items))
4849 }
4850}
4851
4852#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4854#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4855#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4856pub struct OperatorArgTypes {
4857 pub left: DataType,
4859 pub right: DataType,
4861}
4862
4863impl fmt::Display for OperatorArgTypes {
4864 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4865 write!(f, "{}, {}", self.left, self.right)
4866 }
4867}
4868
4869#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4871#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4872#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4873pub enum OperatorClassItem {
4874 Operator {
4876 strategy_number: u64,
4878 operator_name: ObjectName,
4880 op_types: Option<OperatorArgTypes>,
4882 purpose: Option<OperatorPurpose>,
4884 },
4885 Function {
4887 support_number: u64,
4889 op_types: Option<Vec<DataType>>,
4891 function_name: ObjectName,
4893 argument_types: Vec<DataType>,
4895 },
4896 Storage {
4898 storage_type: DataType,
4900 },
4901}
4902
4903#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4905#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4906#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4907pub enum OperatorPurpose {
4908 ForSearch,
4910 ForOrderBy {
4912 sort_family: ObjectName,
4914 },
4915}
4916
4917impl fmt::Display for OperatorClassItem {
4918 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4919 match self {
4920 OperatorClassItem::Operator {
4921 strategy_number,
4922 operator_name,
4923 op_types,
4924 purpose,
4925 } => {
4926 write!(f, "OPERATOR {strategy_number} {operator_name}")?;
4927 if let Some(types) = op_types {
4928 write!(f, " ({types})")?;
4929 }
4930 if let Some(purpose) = purpose {
4931 write!(f, " {purpose}")?;
4932 }
4933 Ok(())
4934 }
4935 OperatorClassItem::Function {
4936 support_number,
4937 op_types,
4938 function_name,
4939 argument_types,
4940 } => {
4941 write!(f, "FUNCTION {support_number}")?;
4942 if let Some(types) = op_types {
4943 write!(f, " ({})", display_comma_separated(types))?;
4944 }
4945 write!(f, " {function_name}")?;
4946 if !argument_types.is_empty() {
4947 write!(f, "({})", display_comma_separated(argument_types))?;
4948 }
4949 Ok(())
4950 }
4951 OperatorClassItem::Storage { storage_type } => {
4952 write!(f, "STORAGE {storage_type}")
4953 }
4954 }
4955 }
4956}
4957
4958impl fmt::Display for OperatorPurpose {
4959 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4960 match self {
4961 OperatorPurpose::ForSearch => write!(f, "FOR SEARCH"),
4962 OperatorPurpose::ForOrderBy { sort_family } => {
4963 write!(f, "FOR ORDER BY {sort_family}")
4964 }
4965 }
4966 }
4967}
4968
4969#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4972#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4973#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4974pub struct DropOperator {
4975 pub if_exists: bool,
4977 pub operators: Vec<DropOperatorSignature>,
4979 pub drop_behavior: Option<DropBehavior>,
4981}
4982
4983#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4985#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4986#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4987pub struct DropOperatorSignature {
4988 pub name: ObjectName,
4990 pub left_type: Option<DataType>,
4992 pub right_type: DataType,
4994}
4995
4996impl fmt::Display for DropOperatorSignature {
4997 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4998 write!(f, "{} (", self.name)?;
4999 if let Some(left_type) = &self.left_type {
5000 write!(f, "{}", left_type)?;
5001 } else {
5002 write!(f, "NONE")?;
5003 }
5004 write!(f, ", {})", self.right_type)
5005 }
5006}
5007
5008impl fmt::Display for DropOperator {
5009 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5010 write!(f, "DROP OPERATOR")?;
5011 if self.if_exists {
5012 write!(f, " IF EXISTS")?;
5013 }
5014 write!(f, " {}", display_comma_separated(&self.operators))?;
5015 if let Some(drop_behavior) = &self.drop_behavior {
5016 write!(f, " {}", drop_behavior)?;
5017 }
5018 Ok(())
5019 }
5020}
5021
5022impl Spanned for DropOperator {
5023 fn span(&self) -> Span {
5024 Span::empty()
5025 }
5026}
5027
5028#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5031#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5032#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5033pub struct DropOperatorFamily {
5034 pub if_exists: bool,
5036 pub names: Vec<ObjectName>,
5038 pub using: Ident,
5040 pub drop_behavior: Option<DropBehavior>,
5042}
5043
5044impl fmt::Display for DropOperatorFamily {
5045 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5046 write!(f, "DROP OPERATOR FAMILY")?;
5047 if self.if_exists {
5048 write!(f, " IF EXISTS")?;
5049 }
5050 write!(f, " {}", display_comma_separated(&self.names))?;
5051 write!(f, " USING {}", self.using)?;
5052 if let Some(drop_behavior) = &self.drop_behavior {
5053 write!(f, " {}", drop_behavior)?;
5054 }
5055 Ok(())
5056 }
5057}
5058
5059impl Spanned for DropOperatorFamily {
5060 fn span(&self) -> Span {
5061 Span::empty()
5062 }
5063}
5064
5065#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5068#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5069#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5070pub struct DropOperatorClass {
5071 pub if_exists: bool,
5073 pub names: Vec<ObjectName>,
5075 pub using: Ident,
5077 pub drop_behavior: Option<DropBehavior>,
5079}
5080
5081impl fmt::Display for DropOperatorClass {
5082 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5083 write!(f, "DROP OPERATOR CLASS")?;
5084 if self.if_exists {
5085 write!(f, " IF EXISTS")?;
5086 }
5087 write!(f, " {}", display_comma_separated(&self.names))?;
5088 write!(f, " USING {}", self.using)?;
5089 if let Some(drop_behavior) = &self.drop_behavior {
5090 write!(f, " {}", drop_behavior)?;
5091 }
5092 Ok(())
5093 }
5094}
5095
5096impl Spanned for DropOperatorClass {
5097 fn span(&self) -> Span {
5098 Span::empty()
5099 }
5100}
5101
5102#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5104#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5105#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5106pub enum OperatorFamilyItem {
5107 Operator {
5109 strategy_number: u64,
5111 operator_name: ObjectName,
5113 op_types: Vec<DataType>,
5115 purpose: Option<OperatorPurpose>,
5117 },
5118 Function {
5120 support_number: u64,
5122 op_types: Option<Vec<DataType>>,
5124 function_name: ObjectName,
5126 argument_types: Vec<DataType>,
5128 },
5129}
5130
5131#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5133#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5134#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5135pub enum OperatorFamilyDropItem {
5136 Operator {
5138 strategy_number: u64,
5140 op_types: Vec<DataType>,
5142 },
5143 Function {
5145 support_number: u64,
5147 op_types: Vec<DataType>,
5149 },
5150}
5151
5152impl fmt::Display for OperatorFamilyItem {
5153 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5154 match self {
5155 OperatorFamilyItem::Operator {
5156 strategy_number,
5157 operator_name,
5158 op_types,
5159 purpose,
5160 } => {
5161 write!(
5162 f,
5163 "OPERATOR {strategy_number} {operator_name} ({})",
5164 display_comma_separated(op_types)
5165 )?;
5166 if let Some(purpose) = purpose {
5167 write!(f, " {purpose}")?;
5168 }
5169 Ok(())
5170 }
5171 OperatorFamilyItem::Function {
5172 support_number,
5173 op_types,
5174 function_name,
5175 argument_types,
5176 } => {
5177 write!(f, "FUNCTION {support_number}")?;
5178 if let Some(types) = op_types {
5179 write!(f, " ({})", display_comma_separated(types))?;
5180 }
5181 write!(f, " {function_name}")?;
5182 if !argument_types.is_empty() {
5183 write!(f, "({})", display_comma_separated(argument_types))?;
5184 }
5185 Ok(())
5186 }
5187 }
5188 }
5189}
5190
5191impl fmt::Display for OperatorFamilyDropItem {
5192 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5193 match self {
5194 OperatorFamilyDropItem::Operator {
5195 strategy_number,
5196 op_types,
5197 } => {
5198 write!(
5199 f,
5200 "OPERATOR {strategy_number} ({})",
5201 display_comma_separated(op_types)
5202 )
5203 }
5204 OperatorFamilyDropItem::Function {
5205 support_number,
5206 op_types,
5207 } => {
5208 write!(
5209 f,
5210 "FUNCTION {support_number} ({})",
5211 display_comma_separated(op_types)
5212 )
5213 }
5214 }
5215 }
5216}
5217
5218#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5221#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5222#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5223pub struct AlterOperatorFamily {
5224 pub name: ObjectName,
5226 pub using: Ident,
5228 pub operation: AlterOperatorFamilyOperation,
5230}
5231
5232#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5234#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5235#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5236pub enum AlterOperatorFamilyOperation {
5237 Add {
5239 items: Vec<OperatorFamilyItem>,
5241 },
5242 Drop {
5244 items: Vec<OperatorFamilyDropItem>,
5246 },
5247 RenameTo {
5249 new_name: ObjectName,
5251 },
5252 OwnerTo(Owner),
5254 SetSchema {
5256 schema_name: ObjectName,
5258 },
5259}
5260
5261impl fmt::Display for AlterOperatorFamily {
5262 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5263 write!(
5264 f,
5265 "ALTER OPERATOR FAMILY {} USING {}",
5266 self.name, self.using
5267 )?;
5268 write!(f, " {}", self.operation)
5269 }
5270}
5271
5272impl fmt::Display for AlterOperatorFamilyOperation {
5273 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5274 match self {
5275 AlterOperatorFamilyOperation::Add { items } => {
5276 write!(f, "ADD {}", display_comma_separated(items))
5277 }
5278 AlterOperatorFamilyOperation::Drop { items } => {
5279 write!(f, "DROP {}", display_comma_separated(items))
5280 }
5281 AlterOperatorFamilyOperation::RenameTo { new_name } => {
5282 write!(f, "RENAME TO {new_name}")
5283 }
5284 AlterOperatorFamilyOperation::OwnerTo(owner) => {
5285 write!(f, "OWNER TO {owner}")
5286 }
5287 AlterOperatorFamilyOperation::SetSchema { schema_name } => {
5288 write!(f, "SET SCHEMA {schema_name}")
5289 }
5290 }
5291 }
5292}
5293
5294impl Spanned for AlterOperatorFamily {
5295 fn span(&self) -> Span {
5296 Span::empty()
5297 }
5298}
5299
5300#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5303#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5304#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5305pub struct AlterOperatorClass {
5306 pub name: ObjectName,
5308 pub using: Ident,
5310 pub operation: AlterOperatorClassOperation,
5312}
5313
5314#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5316#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5317#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5318pub enum AlterOperatorClassOperation {
5319 RenameTo {
5322 new_name: ObjectName,
5324 },
5325 OwnerTo(Owner),
5327 SetSchema {
5330 schema_name: ObjectName,
5332 },
5333}
5334
5335impl fmt::Display for AlterOperatorClass {
5336 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5337 write!(f, "ALTER OPERATOR CLASS {} USING {}", self.name, self.using)?;
5338 write!(f, " {}", self.operation)
5339 }
5340}
5341
5342impl fmt::Display for AlterOperatorClassOperation {
5343 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5344 match self {
5345 AlterOperatorClassOperation::RenameTo { new_name } => {
5346 write!(f, "RENAME TO {new_name}")
5347 }
5348 AlterOperatorClassOperation::OwnerTo(owner) => {
5349 write!(f, "OWNER TO {owner}")
5350 }
5351 AlterOperatorClassOperation::SetSchema { schema_name } => {
5352 write!(f, "SET SCHEMA {schema_name}")
5353 }
5354 }
5355 }
5356}
5357
5358impl Spanned for AlterOperatorClass {
5359 fn span(&self) -> Span {
5360 Span::empty()
5361 }
5362}
5363
5364#[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 AlterFunction {
5369 pub kind: AlterFunctionKind,
5371 pub function: FunctionDesc,
5373 pub aggregate_order_by: Option<Vec<OperateFunctionArg>>,
5377 pub aggregate_star: bool,
5381 pub operation: AlterFunctionOperation,
5383}
5384
5385#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5387#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5388#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5389pub enum AlterFunctionKind {
5390 Function,
5392 Aggregate,
5394}
5395
5396impl fmt::Display for AlterFunctionKind {
5397 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5398 match self {
5399 Self::Function => write!(f, "FUNCTION"),
5400 Self::Aggregate => write!(f, "AGGREGATE"),
5401 }
5402 }
5403}
5404
5405#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5407#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5408#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5409pub enum AlterFunctionOperation {
5410 RenameTo {
5412 new_name: Ident,
5414 },
5415 OwnerTo(Owner),
5417 SetSchema {
5419 schema_name: ObjectName,
5421 },
5422 DependsOnExtension {
5424 no: bool,
5426 extension_name: ObjectName,
5428 },
5429 Actions {
5431 actions: Vec<AlterFunctionAction>,
5433 restrict: bool,
5435 },
5436}
5437
5438#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5440#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5441#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5442pub enum AlterFunctionAction {
5443 CalledOnNull(FunctionCalledOnNull),
5445 Behavior(FunctionBehavior),
5447 Leakproof(bool),
5449 Security {
5451 external: bool,
5453 security: FunctionSecurity,
5455 },
5456 Parallel(FunctionParallel),
5458 Cost(Expr),
5460 Rows(Expr),
5462 Support(ObjectName),
5464 Set(FunctionDefinitionSetParam),
5467 Reset(ResetConfig),
5469}
5470
5471impl fmt::Display for AlterFunction {
5472 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5473 write!(f, "ALTER {} ", self.kind)?;
5474 match self.kind {
5475 AlterFunctionKind::Function => {
5476 write!(f, "{} ", self.function)?;
5477 }
5478 AlterFunctionKind::Aggregate => {
5479 write!(f, "{}(", self.function.name)?;
5480 if self.aggregate_star {
5481 write!(f, "*")?;
5482 } else {
5483 if let Some(args) = &self.function.args {
5484 write!(f, "{}", display_comma_separated(args))?;
5485 }
5486 if let Some(order_by_args) = &self.aggregate_order_by {
5487 if self
5488 .function
5489 .args
5490 .as_ref()
5491 .is_some_and(|args| !args.is_empty())
5492 {
5493 write!(f, " ")?;
5494 }
5495 write!(f, "ORDER BY {}", display_comma_separated(order_by_args))?;
5496 }
5497 }
5498 write!(f, ") ")?;
5499 }
5500 }
5501 write!(f, "{}", self.operation)
5502 }
5503}
5504
5505impl fmt::Display for AlterFunctionOperation {
5506 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5507 match self {
5508 AlterFunctionOperation::RenameTo { new_name } => {
5509 write!(f, "RENAME TO {new_name}")
5510 }
5511 AlterFunctionOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
5512 AlterFunctionOperation::SetSchema { schema_name } => {
5513 write!(f, "SET SCHEMA {schema_name}")
5514 }
5515 AlterFunctionOperation::DependsOnExtension { no, extension_name } => {
5516 if *no {
5517 write!(f, "NO DEPENDS ON EXTENSION {extension_name}")
5518 } else {
5519 write!(f, "DEPENDS ON EXTENSION {extension_name}")
5520 }
5521 }
5522 AlterFunctionOperation::Actions { actions, restrict } => {
5523 write!(f, "{}", display_separated(actions, " "))?;
5524 if *restrict {
5525 write!(f, " RESTRICT")?;
5526 }
5527 Ok(())
5528 }
5529 }
5530 }
5531}
5532
5533impl fmt::Display for AlterFunctionAction {
5534 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5535 match self {
5536 AlterFunctionAction::CalledOnNull(called_on_null) => write!(f, "{called_on_null}"),
5537 AlterFunctionAction::Behavior(behavior) => write!(f, "{behavior}"),
5538 AlterFunctionAction::Leakproof(leakproof) => {
5539 if *leakproof {
5540 write!(f, "LEAKPROOF")
5541 } else {
5542 write!(f, "NOT LEAKPROOF")
5543 }
5544 }
5545 AlterFunctionAction::Security { external, security } => {
5546 if *external {
5547 write!(f, "EXTERNAL ")?;
5548 }
5549 write!(f, "{security}")
5550 }
5551 AlterFunctionAction::Parallel(parallel) => write!(f, "{parallel}"),
5552 AlterFunctionAction::Cost(execution_cost) => write!(f, "COST {execution_cost}"),
5553 AlterFunctionAction::Rows(result_rows) => write!(f, "ROWS {result_rows}"),
5554 AlterFunctionAction::Support(support_function) => {
5555 write!(f, "SUPPORT {support_function}")
5556 }
5557 AlterFunctionAction::Set(set_param) => write!(f, "{set_param}"),
5558 AlterFunctionAction::Reset(reset_config) => match reset_config {
5559 ResetConfig::ALL => write!(f, "RESET ALL"),
5560 ResetConfig::ConfigName(name) => write!(f, "RESET {name}"),
5561 },
5562 }
5563 }
5564}
5565
5566impl Spanned for AlterFunction {
5567 fn span(&self) -> Span {
5568 Span::empty()
5569 }
5570}
5571
5572#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5576#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5577#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5578pub struct CreatePolicy {
5579 pub name: Ident,
5581 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5583 pub table_name: ObjectName,
5584 pub policy_type: Option<CreatePolicyType>,
5586 pub command: Option<CreatePolicyCommand>,
5588 pub to: Option<Vec<Owner>>,
5590 pub using: Option<Expr>,
5592 pub with_check: Option<Expr>,
5594}
5595
5596impl fmt::Display for CreatePolicy {
5597 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5598 write!(
5599 f,
5600 "CREATE POLICY {name} ON {table_name}",
5601 name = self.name,
5602 table_name = self.table_name,
5603 )?;
5604 if let Some(ref policy_type) = self.policy_type {
5605 write!(f, " AS {policy_type}")?;
5606 }
5607 if let Some(ref command) = self.command {
5608 write!(f, " FOR {command}")?;
5609 }
5610 if let Some(ref to) = self.to {
5611 write!(f, " TO {}", display_comma_separated(to))?;
5612 }
5613 if let Some(ref using) = self.using {
5614 write!(f, " USING ({using})")?;
5615 }
5616 if let Some(ref with_check) = self.with_check {
5617 write!(f, " WITH CHECK ({with_check})")?;
5618 }
5619 Ok(())
5620 }
5621}
5622
5623#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5629#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5630#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5631pub enum CreatePolicyType {
5632 Permissive,
5634 Restrictive,
5636}
5637
5638impl fmt::Display for CreatePolicyType {
5639 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5640 match self {
5641 CreatePolicyType::Permissive => write!(f, "PERMISSIVE"),
5642 CreatePolicyType::Restrictive => write!(f, "RESTRICTIVE"),
5643 }
5644 }
5645}
5646
5647#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5653#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5654#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5655pub enum CreatePolicyCommand {
5656 All,
5658 Select,
5660 Insert,
5662 Update,
5664 Delete,
5666}
5667
5668impl fmt::Display for CreatePolicyCommand {
5669 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5670 match self {
5671 CreatePolicyCommand::All => write!(f, "ALL"),
5672 CreatePolicyCommand::Select => write!(f, "SELECT"),
5673 CreatePolicyCommand::Insert => write!(f, "INSERT"),
5674 CreatePolicyCommand::Update => write!(f, "UPDATE"),
5675 CreatePolicyCommand::Delete => write!(f, "DELETE"),
5676 }
5677 }
5678}
5679
5680#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5684#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5685#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5686pub struct DropPolicy {
5687 pub if_exists: bool,
5689 pub name: Ident,
5691 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5693 pub table_name: ObjectName,
5694 pub drop_behavior: Option<DropBehavior>,
5696}
5697
5698impl fmt::Display for DropPolicy {
5699 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5700 write!(
5701 f,
5702 "DROP POLICY {if_exists}{name} ON {table_name}",
5703 if_exists = if self.if_exists { "IF EXISTS " } else { "" },
5704 name = self.name,
5705 table_name = self.table_name
5706 )?;
5707 if let Some(ref behavior) = self.drop_behavior {
5708 write!(f, " {behavior}")?;
5709 }
5710 Ok(())
5711 }
5712}
5713
5714impl From<CreatePolicy> for crate::ast::Statement {
5715 fn from(v: CreatePolicy) -> Self {
5716 crate::ast::Statement::CreatePolicy(v)
5717 }
5718}
5719
5720impl From<DropPolicy> for crate::ast::Statement {
5721 fn from(v: DropPolicy) -> Self {
5722 crate::ast::Statement::DropPolicy(v)
5723 }
5724}
5725
5726#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5733#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5734#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5735pub struct AlterPolicy {
5736 pub name: Ident,
5738 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5740 pub table_name: ObjectName,
5741 pub operation: AlterPolicyOperation,
5743}
5744
5745impl fmt::Display for AlterPolicy {
5746 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5747 write!(
5748 f,
5749 "ALTER POLICY {name} ON {table_name}{operation}",
5750 name = self.name,
5751 table_name = self.table_name,
5752 operation = self.operation
5753 )
5754 }
5755}
5756
5757impl From<AlterPolicy> for crate::ast::Statement {
5758 fn from(v: AlterPolicy) -> Self {
5759 crate::ast::Statement::AlterPolicy(v)
5760 }
5761}