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 if_not_exists: bool,
2823 pub include: Vec<Ident>,
2825 pub nulls_distinct: Option<bool>,
2827 pub with: Vec<Expr>,
2829 pub predicate: Option<Expr>,
2831 pub index_options: Vec<IndexOption>,
2833 pub alter_options: Vec<AlterTableOperation>,
2840}
2841
2842impl fmt::Display for CreateIndex {
2843 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2844 write!(
2845 f,
2846 "CREATE {unique}INDEX {concurrently}{if_not_exists}",
2847 unique = if self.unique { "UNIQUE " } else { "" },
2848 concurrently = if self.concurrently {
2849 "CONCURRENTLY "
2850 } else {
2851 ""
2852 },
2853 if_not_exists = if self.if_not_exists {
2854 "IF NOT EXISTS "
2855 } else {
2856 ""
2857 },
2858 )?;
2859 if let Some(value) = &self.name {
2860 write!(f, "{value} ")?;
2861 }
2862 write!(f, "ON {}", self.table_name)?;
2863 if let Some(value) = &self.using {
2864 write!(f, " USING {value} ")?;
2865 }
2866 write!(f, "({})", display_comma_separated(&self.columns))?;
2867 if !self.include.is_empty() {
2868 write!(f, " INCLUDE ({})", display_comma_separated(&self.include))?;
2869 }
2870 if let Some(value) = self.nulls_distinct {
2871 if value {
2872 write!(f, " NULLS DISTINCT")?;
2873 } else {
2874 write!(f, " NULLS NOT DISTINCT")?;
2875 }
2876 }
2877 if !self.with.is_empty() {
2878 write!(f, " WITH ({})", display_comma_separated(&self.with))?;
2879 }
2880 if let Some(predicate) = &self.predicate {
2881 write!(f, " WHERE {predicate}")?;
2882 }
2883 if !self.index_options.is_empty() {
2884 write!(f, " {}", display_separated(&self.index_options, " "))?;
2885 }
2886 if !self.alter_options.is_empty() {
2887 write!(f, " {}", display_separated(&self.alter_options, " "))?;
2888 }
2889 Ok(())
2890 }
2891}
2892
2893#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2895#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2896#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2897pub struct CreateTable {
2898 pub or_replace: bool,
2900 pub temporary: bool,
2902 pub external: bool,
2904 pub dynamic: bool,
2906 pub global: Option<bool>,
2908 pub if_not_exists: bool,
2910 pub transient: bool,
2912 pub volatile: bool,
2914 pub iceberg: bool,
2916 pub snapshot: bool,
2919 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2921 pub name: ObjectName,
2922 pub columns: Vec<ColumnDef>,
2924 pub constraints: Vec<TableConstraint>,
2926 pub hive_distribution: HiveDistributionStyle,
2928 pub hive_formats: Option<HiveFormat>,
2930 pub table_options: CreateTableOptions,
2932 pub file_format: Option<FileFormat>,
2934 pub location: Option<String>,
2936 pub query: Option<Box<Query>>,
2938 pub without_rowid: bool,
2940 pub like: Option<CreateTableLikeKind>,
2942 pub clone: Option<ObjectName>,
2944 pub version: Option<TableVersion>,
2946 pub comment: Option<CommentDef>,
2950 pub on_commit: Option<OnCommit>,
2953 pub on_cluster: Option<Ident>,
2956 pub primary_key: Option<Box<Expr>>,
2959 pub order_by: Option<OneOrManyWithParens<Expr>>,
2963 pub partition_by: Option<Box<Expr>>,
2966 pub cluster_by: Option<WrappedCollection<Vec<Expr>>>,
2971 pub clustered_by: Option<ClusteredBy>,
2974 pub inherits: Option<Vec<ObjectName>>,
2979 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2983 pub partition_of: Option<ObjectName>,
2984 pub for_values: Option<ForValues>,
2987 pub strict: bool,
2991 pub copy_grants: bool,
2994 pub enable_schema_evolution: Option<bool>,
2997 pub change_tracking: Option<bool>,
3000 pub data_retention_time_in_days: Option<u64>,
3003 pub max_data_extension_time_in_days: Option<u64>,
3006 pub default_ddl_collation: Option<String>,
3009 pub with_aggregation_policy: Option<ObjectName>,
3012 pub with_row_access_policy: Option<RowAccessPolicy>,
3015 pub with_storage_lifecycle_policy: Option<StorageLifecyclePolicy>,
3018 pub with_tags: Option<Vec<Tag>>,
3021 pub external_volume: Option<String>,
3024 pub base_location: Option<String>,
3027 pub catalog: Option<String>,
3030 pub catalog_sync: Option<String>,
3033 pub storage_serialization_policy: Option<StorageSerializationPolicy>,
3036 pub target_lag: Option<String>,
3039 pub warehouse: Option<Ident>,
3042 pub refresh_mode: Option<RefreshModeKind>,
3045 pub initialize: Option<InitializeKind>,
3048 pub require_user: bool,
3051 pub diststyle: Option<DistStyle>,
3054 pub distkey: Option<Expr>,
3057 pub sortkey: Option<Vec<Expr>>,
3060 pub backup: Option<bool>,
3063}
3064
3065impl fmt::Display for CreateTable {
3066 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3067 write!(
3075 f,
3076 "CREATE {or_replace}{external}{global}{temporary}{transient}{volatile}{dynamic}{iceberg}{snapshot}TABLE {if_not_exists}{name}",
3077 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3078 external = if self.external { "EXTERNAL " } else { "" },
3079 snapshot = if self.snapshot { "SNAPSHOT " } else { "" },
3080 global = self.global
3081 .map(|global| {
3082 if global {
3083 "GLOBAL "
3084 } else {
3085 "LOCAL "
3086 }
3087 })
3088 .unwrap_or(""),
3089 if_not_exists = if self.if_not_exists { "IF NOT EXISTS " } else { "" },
3090 temporary = if self.temporary { "TEMPORARY " } else { "" },
3091 transient = if self.transient { "TRANSIENT " } else { "" },
3092 volatile = if self.volatile { "VOLATILE " } else { "" },
3093 iceberg = if self.iceberg { "ICEBERG " } else { "" },
3095 dynamic = if self.dynamic { "DYNAMIC " } else { "" },
3096 name = self.name,
3097 )?;
3098 if let Some(partition_of) = &self.partition_of {
3099 write!(f, " PARTITION OF {partition_of}")?;
3100 }
3101 if let Some(on_cluster) = &self.on_cluster {
3102 write!(f, " ON CLUSTER {on_cluster}")?;
3103 }
3104 if !self.columns.is_empty() || !self.constraints.is_empty() {
3105 f.write_str(" (")?;
3106 NewLine.fmt(f)?;
3107 Indent(DisplayCommaSeparated(&self.columns)).fmt(f)?;
3108 if !self.columns.is_empty() && !self.constraints.is_empty() {
3109 f.write_str(",")?;
3110 SpaceOrNewline.fmt(f)?;
3111 }
3112 Indent(DisplayCommaSeparated(&self.constraints)).fmt(f)?;
3113 NewLine.fmt(f)?;
3114 f.write_str(")")?;
3115 } else if self.query.is_none()
3116 && self.like.is_none()
3117 && self.clone.is_none()
3118 && self.partition_of.is_none()
3119 {
3120 f.write_str(" ()")?;
3122 } else if let Some(CreateTableLikeKind::Parenthesized(like_in_columns_list)) = &self.like {
3123 write!(f, " ({like_in_columns_list})")?;
3124 }
3125 if let Some(for_values) = &self.for_values {
3126 write!(f, " {for_values}")?;
3127 }
3128
3129 if let Some(comment) = &self.comment {
3132 write!(f, " COMMENT '{comment}'")?;
3133 }
3134
3135 if self.without_rowid {
3137 write!(f, " WITHOUT ROWID")?;
3138 }
3139
3140 if let Some(CreateTableLikeKind::Plain(like)) = &self.like {
3141 write!(f, " {like}")?;
3142 }
3143
3144 if let Some(c) = &self.clone {
3145 write!(f, " CLONE {c}")?;
3146 }
3147
3148 if let Some(version) = &self.version {
3149 write!(f, " {version}")?;
3150 }
3151
3152 match &self.hive_distribution {
3153 HiveDistributionStyle::PARTITIONED { columns } => {
3154 write!(f, " PARTITIONED BY ({})", display_comma_separated(columns))?;
3155 }
3156 HiveDistributionStyle::SKEWED {
3157 columns,
3158 on,
3159 stored_as_directories,
3160 } => {
3161 write!(
3162 f,
3163 " SKEWED BY ({})) ON ({})",
3164 display_comma_separated(columns),
3165 display_comma_separated(on)
3166 )?;
3167 if *stored_as_directories {
3168 write!(f, " STORED AS DIRECTORIES")?;
3169 }
3170 }
3171 _ => (),
3172 }
3173
3174 if let Some(clustered_by) = &self.clustered_by {
3175 write!(f, " {clustered_by}")?;
3176 }
3177
3178 if let Some(HiveFormat {
3179 row_format,
3180 serde_properties,
3181 storage,
3182 location,
3183 }) = &self.hive_formats
3184 {
3185 match row_format {
3186 Some(HiveRowFormat::SERDE { class }) => write!(f, " ROW FORMAT SERDE '{class}'")?,
3187 Some(HiveRowFormat::DELIMITED { delimiters }) => {
3188 write!(f, " ROW FORMAT DELIMITED")?;
3189 if !delimiters.is_empty() {
3190 write!(f, " {}", display_separated(delimiters, " "))?;
3191 }
3192 }
3193 None => (),
3194 }
3195 match storage {
3196 Some(HiveIOFormat::IOF {
3197 input_format,
3198 output_format,
3199 }) => write!(
3200 f,
3201 " STORED AS INPUTFORMAT {input_format} OUTPUTFORMAT {output_format}"
3202 )?,
3203 Some(HiveIOFormat::FileFormat { format }) if !self.external => {
3204 write!(f, " STORED AS {format}")?
3205 }
3206 _ => (),
3207 }
3208 if let Some(serde_properties) = serde_properties.as_ref() {
3209 write!(
3210 f,
3211 " WITH SERDEPROPERTIES ({})",
3212 display_comma_separated(serde_properties)
3213 )?;
3214 }
3215 if !self.external {
3216 if let Some(loc) = location {
3217 write!(f, " LOCATION '{loc}'")?;
3218 }
3219 }
3220 }
3221 if self.external {
3222 if let Some(file_format) = self.file_format {
3223 write!(f, " STORED AS {file_format}")?;
3224 }
3225 if let Some(location) = &self.location {
3226 write!(f, " LOCATION '{location}'")?;
3227 }
3228 }
3229
3230 match &self.table_options {
3231 options @ CreateTableOptions::With(_)
3232 | options @ CreateTableOptions::Plain(_)
3233 | options @ CreateTableOptions::TableProperties(_) => write!(f, " {options}")?,
3234 _ => (),
3235 }
3236
3237 if let Some(primary_key) = &self.primary_key {
3238 write!(f, " PRIMARY KEY {primary_key}")?;
3239 }
3240 if let Some(order_by) = &self.order_by {
3241 write!(f, " ORDER BY {order_by}")?;
3242 }
3243 if let Some(inherits) = &self.inherits {
3244 write!(f, " INHERITS ({})", display_comma_separated(inherits))?;
3245 }
3246 if let Some(partition_by) = self.partition_by.as_ref() {
3247 write!(f, " PARTITION BY {partition_by}")?;
3248 }
3249 if let Some(cluster_by) = self.cluster_by.as_ref() {
3250 write!(f, " CLUSTER BY {cluster_by}")?;
3251 }
3252 if let options @ CreateTableOptions::Options(_) = &self.table_options {
3253 write!(f, " {options}")?;
3254 }
3255 if let Some(external_volume) = self.external_volume.as_ref() {
3256 write!(f, " EXTERNAL_VOLUME='{external_volume}'")?;
3257 }
3258
3259 if let Some(catalog) = self.catalog.as_ref() {
3260 write!(f, " CATALOG='{catalog}'")?;
3261 }
3262
3263 if self.iceberg {
3264 if let Some(base_location) = self.base_location.as_ref() {
3265 write!(f, " BASE_LOCATION='{base_location}'")?;
3266 }
3267 }
3268
3269 if let Some(catalog_sync) = self.catalog_sync.as_ref() {
3270 write!(f, " CATALOG_SYNC='{catalog_sync}'")?;
3271 }
3272
3273 if let Some(storage_serialization_policy) = self.storage_serialization_policy.as_ref() {
3274 write!(
3275 f,
3276 " STORAGE_SERIALIZATION_POLICY={storage_serialization_policy}"
3277 )?;
3278 }
3279
3280 if self.copy_grants {
3281 write!(f, " COPY GRANTS")?;
3282 }
3283
3284 if let Some(is_enabled) = self.enable_schema_evolution {
3285 write!(
3286 f,
3287 " ENABLE_SCHEMA_EVOLUTION={}",
3288 if is_enabled { "TRUE" } else { "FALSE" }
3289 )?;
3290 }
3291
3292 if let Some(is_enabled) = self.change_tracking {
3293 write!(
3294 f,
3295 " CHANGE_TRACKING={}",
3296 if is_enabled { "TRUE" } else { "FALSE" }
3297 )?;
3298 }
3299
3300 if let Some(data_retention_time_in_days) = self.data_retention_time_in_days {
3301 write!(
3302 f,
3303 " DATA_RETENTION_TIME_IN_DAYS={data_retention_time_in_days}",
3304 )?;
3305 }
3306
3307 if let Some(max_data_extension_time_in_days) = self.max_data_extension_time_in_days {
3308 write!(
3309 f,
3310 " MAX_DATA_EXTENSION_TIME_IN_DAYS={max_data_extension_time_in_days}",
3311 )?;
3312 }
3313
3314 if let Some(default_ddl_collation) = &self.default_ddl_collation {
3315 write!(f, " DEFAULT_DDL_COLLATION='{default_ddl_collation}'",)?;
3316 }
3317
3318 if let Some(with_aggregation_policy) = &self.with_aggregation_policy {
3319 write!(f, " WITH AGGREGATION POLICY {with_aggregation_policy}",)?;
3320 }
3321
3322 if let Some(row_access_policy) = &self.with_row_access_policy {
3323 write!(f, " {row_access_policy}",)?;
3324 }
3325
3326 if let Some(storage_lifecycle_policy) = &self.with_storage_lifecycle_policy {
3327 write!(f, " {storage_lifecycle_policy}",)?;
3328 }
3329
3330 if let Some(tag) = &self.with_tags {
3331 write!(f, " WITH TAG ({})", display_comma_separated(tag.as_slice()))?;
3332 }
3333
3334 if let Some(target_lag) = &self.target_lag {
3335 write!(f, " TARGET_LAG='{target_lag}'")?;
3336 }
3337
3338 if let Some(warehouse) = &self.warehouse {
3339 write!(f, " WAREHOUSE={warehouse}")?;
3340 }
3341
3342 if let Some(refresh_mode) = &self.refresh_mode {
3343 write!(f, " REFRESH_MODE={refresh_mode}")?;
3344 }
3345
3346 if let Some(initialize) = &self.initialize {
3347 write!(f, " INITIALIZE={initialize}")?;
3348 }
3349
3350 if self.require_user {
3351 write!(f, " REQUIRE USER")?;
3352 }
3353
3354 if self.on_commit.is_some() {
3355 let on_commit = match self.on_commit {
3356 Some(OnCommit::DeleteRows) => "ON COMMIT DELETE ROWS",
3357 Some(OnCommit::PreserveRows) => "ON COMMIT PRESERVE ROWS",
3358 Some(OnCommit::Drop) => "ON COMMIT DROP",
3359 None => "",
3360 };
3361 write!(f, " {on_commit}")?;
3362 }
3363 if self.strict {
3364 write!(f, " STRICT")?;
3365 }
3366 if let Some(backup) = self.backup {
3367 write!(f, " BACKUP {}", if backup { "YES" } else { "NO" })?;
3368 }
3369 if let Some(diststyle) = &self.diststyle {
3370 write!(f, " DISTSTYLE {diststyle}")?;
3371 }
3372 if let Some(distkey) = &self.distkey {
3373 write!(f, " DISTKEY({distkey})")?;
3374 }
3375 if let Some(sortkey) = &self.sortkey {
3376 write!(f, " SORTKEY({})", display_comma_separated(sortkey))?;
3377 }
3378 if let Some(query) = &self.query {
3379 write!(f, " AS {query}")?;
3380 }
3381 Ok(())
3382 }
3383}
3384
3385#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3391#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3392#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3393pub enum ForValues {
3394 In(Vec<Expr>),
3396 From {
3398 from: Vec<PartitionBoundValue>,
3400 to: Vec<PartitionBoundValue>,
3402 },
3403 With {
3405 modulus: u64,
3407 remainder: u64,
3409 },
3410 Default,
3412}
3413
3414impl fmt::Display for ForValues {
3415 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3416 match self {
3417 ForValues::In(values) => {
3418 write!(f, "FOR VALUES IN ({})", display_comma_separated(values))
3419 }
3420 ForValues::From { from, to } => {
3421 write!(
3422 f,
3423 "FOR VALUES FROM ({}) TO ({})",
3424 display_comma_separated(from),
3425 display_comma_separated(to)
3426 )
3427 }
3428 ForValues::With { modulus, remainder } => {
3429 write!(
3430 f,
3431 "FOR VALUES WITH (MODULUS {modulus}, REMAINDER {remainder})"
3432 )
3433 }
3434 ForValues::Default => write!(f, "DEFAULT"),
3435 }
3436 }
3437}
3438
3439#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3444#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3445#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3446pub enum PartitionBoundValue {
3447 Expr(Expr),
3449 MinValue,
3451 MaxValue,
3453}
3454
3455impl fmt::Display for PartitionBoundValue {
3456 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3457 match self {
3458 PartitionBoundValue::Expr(expr) => write!(f, "{expr}"),
3459 PartitionBoundValue::MinValue => write!(f, "MINVALUE"),
3460 PartitionBoundValue::MaxValue => write!(f, "MAXVALUE"),
3461 }
3462 }
3463}
3464
3465#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3469#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3470#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3471pub enum DistStyle {
3472 Auto,
3474 Even,
3476 Key,
3478 All,
3480}
3481
3482impl fmt::Display for DistStyle {
3483 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3484 match self {
3485 DistStyle::Auto => write!(f, "AUTO"),
3486 DistStyle::Even => write!(f, "EVEN"),
3487 DistStyle::Key => write!(f, "KEY"),
3488 DistStyle::All => write!(f, "ALL"),
3489 }
3490 }
3491}
3492
3493
3494#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3495#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3496#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3497pub struct CreateDomain {
3510 pub name: ObjectName,
3512 pub data_type: DataType,
3514 pub collation: Option<Ident>,
3516 pub default: Option<Expr>,
3518 pub constraints: Vec<TableConstraint>,
3520}
3521
3522impl fmt::Display for CreateDomain {
3523 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3524 write!(
3525 f,
3526 "CREATE DOMAIN {name} AS {data_type}",
3527 name = self.name,
3528 data_type = self.data_type
3529 )?;
3530 if let Some(collation) = &self.collation {
3531 write!(f, " COLLATE {collation}")?;
3532 }
3533 if let Some(default) = &self.default {
3534 write!(f, " DEFAULT {default}")?;
3535 }
3536 if !self.constraints.is_empty() {
3537 write!(f, " {}", display_separated(&self.constraints, " "))?;
3538 }
3539 Ok(())
3540 }
3541}
3542
3543#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3545#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3546#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3547pub enum FunctionReturnType {
3548 DataType(DataType),
3550 SetOf(DataType),
3554}
3555
3556impl fmt::Display for FunctionReturnType {
3557 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3558 match self {
3559 FunctionReturnType::DataType(data_type) => write!(f, "{data_type}"),
3560 FunctionReturnType::SetOf(data_type) => write!(f, "SETOF {data_type}"),
3561 }
3562 }
3563}
3564
3565#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3566#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3567#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3568pub struct CreateFunction {
3570 pub or_alter: bool,
3574 pub or_replace: bool,
3576 pub temporary: bool,
3578 pub if_not_exists: bool,
3580 pub name: ObjectName,
3582 pub args: Option<Vec<OperateFunctionArg>>,
3584 pub return_type: Option<FunctionReturnType>,
3586 pub function_body: Option<CreateFunctionBody>,
3594 pub behavior: Option<FunctionBehavior>,
3600 pub called_on_null: Option<FunctionCalledOnNull>,
3604 pub parallel: Option<FunctionParallel>,
3608 pub security: Option<FunctionSecurity>,
3612 pub set_params: Vec<FunctionDefinitionSetParam>,
3616 pub using: Option<CreateFunctionUsing>,
3618 pub language: Option<Ident>,
3626 pub determinism_specifier: Option<FunctionDeterminismSpecifier>,
3630 pub options: Option<Vec<SqlOption>>,
3634 pub remote_connection: Option<ObjectName>,
3644}
3645
3646impl fmt::Display for CreateFunction {
3647 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3648 write!(
3649 f,
3650 "CREATE {or_alter}{or_replace}{temp}FUNCTION {if_not_exists}{name}",
3651 name = self.name,
3652 temp = if self.temporary { "TEMPORARY " } else { "" },
3653 or_alter = if self.or_alter { "OR ALTER " } else { "" },
3654 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3655 if_not_exists = if self.if_not_exists {
3656 "IF NOT EXISTS "
3657 } else {
3658 ""
3659 },
3660 )?;
3661 if let Some(args) = &self.args {
3662 write!(f, "({})", display_comma_separated(args))?;
3663 }
3664 if let Some(return_type) = &self.return_type {
3665 write!(f, " RETURNS {return_type}")?;
3666 }
3667 if let Some(determinism_specifier) = &self.determinism_specifier {
3668 write!(f, " {determinism_specifier}")?;
3669 }
3670 if let Some(language) = &self.language {
3671 write!(f, " LANGUAGE {language}")?;
3672 }
3673 if let Some(behavior) = &self.behavior {
3674 write!(f, " {behavior}")?;
3675 }
3676 if let Some(called_on_null) = &self.called_on_null {
3677 write!(f, " {called_on_null}")?;
3678 }
3679 if let Some(parallel) = &self.parallel {
3680 write!(f, " {parallel}")?;
3681 }
3682 if let Some(security) = &self.security {
3683 write!(f, " {security}")?;
3684 }
3685 for set_param in &self.set_params {
3686 write!(f, " {set_param}")?;
3687 }
3688 if let Some(remote_connection) = &self.remote_connection {
3689 write!(f, " REMOTE WITH CONNECTION {remote_connection}")?;
3690 }
3691 if let Some(CreateFunctionBody::AsBeforeOptions { body, link_symbol }) = &self.function_body
3692 {
3693 write!(f, " AS {body}")?;
3694 if let Some(link_symbol) = link_symbol {
3695 write!(f, ", {link_symbol}")?;
3696 }
3697 }
3698 if let Some(CreateFunctionBody::Return(function_body)) = &self.function_body {
3699 write!(f, " RETURN {function_body}")?;
3700 }
3701 if let Some(CreateFunctionBody::AsReturnExpr(function_body)) = &self.function_body {
3702 write!(f, " AS RETURN {function_body}")?;
3703 }
3704 if let Some(CreateFunctionBody::AsReturnSelect(function_body)) = &self.function_body {
3705 write!(f, " AS RETURN {function_body}")?;
3706 }
3707 if let Some(using) = &self.using {
3708 write!(f, " {using}")?;
3709 }
3710 if let Some(options) = &self.options {
3711 write!(
3712 f,
3713 " OPTIONS({})",
3714 display_comma_separated(options.as_slice())
3715 )?;
3716 }
3717 if let Some(CreateFunctionBody::AsAfterOptions(function_body)) = &self.function_body {
3718 write!(f, " AS {function_body}")?;
3719 }
3720 if let Some(CreateFunctionBody::AsBeginEnd(bes)) = &self.function_body {
3721 write!(f, " AS {bes}")?;
3722 }
3723 Ok(())
3724 }
3725}
3726
3727#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3737#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3738#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3739pub struct CreateConnector {
3740 pub name: Ident,
3742 pub if_not_exists: bool,
3744 pub connector_type: Option<String>,
3746 pub url: Option<String>,
3748 pub comment: Option<CommentDef>,
3750 pub with_dcproperties: Option<Vec<SqlOption>>,
3752}
3753
3754impl fmt::Display for CreateConnector {
3755 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3756 write!(
3757 f,
3758 "CREATE CONNECTOR {if_not_exists}{name}",
3759 if_not_exists = if self.if_not_exists {
3760 "IF NOT EXISTS "
3761 } else {
3762 ""
3763 },
3764 name = self.name,
3765 )?;
3766
3767 if let Some(connector_type) = &self.connector_type {
3768 write!(f, " TYPE '{connector_type}'")?;
3769 }
3770
3771 if let Some(url) = &self.url {
3772 write!(f, " URL '{url}'")?;
3773 }
3774
3775 if let Some(comment) = &self.comment {
3776 write!(f, " COMMENT = '{comment}'")?;
3777 }
3778
3779 if let Some(with_dcproperties) = &self.with_dcproperties {
3780 write!(
3781 f,
3782 " WITH DCPROPERTIES({})",
3783 display_comma_separated(with_dcproperties)
3784 )?;
3785 }
3786
3787 Ok(())
3788 }
3789}
3790
3791#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3796#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3797#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3798pub enum AlterSchemaOperation {
3799 SetDefaultCollate {
3801 collate: Expr,
3803 },
3804 AddReplica {
3806 replica: Ident,
3808 options: Option<Vec<SqlOption>>,
3810 },
3811 DropReplica {
3813 replica: Ident,
3815 },
3816 SetOptionsParens {
3818 options: Vec<SqlOption>,
3820 },
3821 Rename {
3823 name: ObjectName,
3825 },
3826 OwnerTo {
3828 owner: Owner,
3830 },
3831}
3832
3833impl fmt::Display for AlterSchemaOperation {
3834 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3835 match self {
3836 AlterSchemaOperation::SetDefaultCollate { collate } => {
3837 write!(f, "SET DEFAULT COLLATE {collate}")
3838 }
3839 AlterSchemaOperation::AddReplica { replica, options } => {
3840 write!(f, "ADD REPLICA {replica}")?;
3841 if let Some(options) = options {
3842 write!(f, " OPTIONS ({})", display_comma_separated(options))?;
3843 }
3844 Ok(())
3845 }
3846 AlterSchemaOperation::DropReplica { replica } => write!(f, "DROP REPLICA {replica}"),
3847 AlterSchemaOperation::SetOptionsParens { options } => {
3848 write!(f, "SET OPTIONS ({})", display_comma_separated(options))
3849 }
3850 AlterSchemaOperation::Rename { name } => write!(f, "RENAME TO {name}"),
3851 AlterSchemaOperation::OwnerTo { owner } => write!(f, "OWNER TO {owner}"),
3852 }
3853 }
3854}
3855#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3861#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3862#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3863pub enum RenameTableNameKind {
3864 As(ObjectName),
3866 To(ObjectName),
3868}
3869
3870impl fmt::Display for RenameTableNameKind {
3871 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3872 match self {
3873 RenameTableNameKind::As(name) => write!(f, "AS {name}"),
3874 RenameTableNameKind::To(name) => write!(f, "TO {name}"),
3875 }
3876 }
3877}
3878
3879#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3880#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3881#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3882pub struct AlterSchema {
3884 pub name: ObjectName,
3886 pub if_exists: bool,
3888 pub operations: Vec<AlterSchemaOperation>,
3890}
3891
3892impl fmt::Display for AlterSchema {
3893 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3894 write!(f, "ALTER SCHEMA ")?;
3895 if self.if_exists {
3896 write!(f, "IF EXISTS ")?;
3897 }
3898 write!(f, "{}", self.name)?;
3899 for operation in &self.operations {
3900 write!(f, " {operation}")?;
3901 }
3902
3903 Ok(())
3904 }
3905}
3906
3907impl Spanned for RenameTableNameKind {
3908 fn span(&self) -> Span {
3909 match self {
3910 RenameTableNameKind::As(name) => name.span(),
3911 RenameTableNameKind::To(name) => name.span(),
3912 }
3913 }
3914}
3915
3916#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
3917#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3918#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3919pub enum TriggerObjectKind {
3921 For(TriggerObject),
3923 ForEach(TriggerObject),
3925}
3926
3927impl Display for TriggerObjectKind {
3928 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3929 match self {
3930 TriggerObjectKind::For(obj) => write!(f, "FOR {obj}"),
3931 TriggerObjectKind::ForEach(obj) => write!(f, "FOR EACH {obj}"),
3932 }
3933 }
3934}
3935
3936#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3937#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3938#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3939pub struct CreateTrigger {
3953 pub or_alter: bool,
3957 pub temporary: bool,
3974 pub or_replace: bool,
3984 pub is_constraint: bool,
3986 pub name: ObjectName,
3988 pub period: Option<TriggerPeriod>,
4017 pub period_before_table: bool,
4028 pub events: Vec<TriggerEvent>,
4030 pub table_name: ObjectName,
4032 pub referenced_table_name: Option<ObjectName>,
4035 pub referencing: Vec<TriggerReferencing>,
4037 pub trigger_object: Option<TriggerObjectKind>,
4042 pub condition: Option<Expr>,
4044 pub exec_body: Option<TriggerExecBody>,
4046 pub statements_as: bool,
4048 pub statements: Option<ConditionalStatements>,
4050 pub characteristics: Option<ConstraintCharacteristics>,
4052}
4053
4054impl Display for CreateTrigger {
4055 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4056 let CreateTrigger {
4057 or_alter,
4058 temporary,
4059 or_replace,
4060 is_constraint,
4061 name,
4062 period_before_table,
4063 period,
4064 events,
4065 table_name,
4066 referenced_table_name,
4067 referencing,
4068 trigger_object,
4069 condition,
4070 exec_body,
4071 statements_as,
4072 statements,
4073 characteristics,
4074 } = self;
4075 write!(
4076 f,
4077 "CREATE {temporary}{or_alter}{or_replace}{is_constraint}TRIGGER {name} ",
4078 temporary = if *temporary { "TEMPORARY " } else { "" },
4079 or_alter = if *or_alter { "OR ALTER " } else { "" },
4080 or_replace = if *or_replace { "OR REPLACE " } else { "" },
4081 is_constraint = if *is_constraint { "CONSTRAINT " } else { "" },
4082 )?;
4083
4084 if *period_before_table {
4085 if let Some(p) = period {
4086 write!(f, "{p} ")?;
4087 }
4088 if !events.is_empty() {
4089 write!(f, "{} ", display_separated(events, " OR "))?;
4090 }
4091 write!(f, "ON {table_name}")?;
4092 } else {
4093 write!(f, "ON {table_name} ")?;
4094 if let Some(p) = period {
4095 write!(f, "{p}")?;
4096 }
4097 if !events.is_empty() {
4098 write!(f, " {}", display_separated(events, ", "))?;
4099 }
4100 }
4101
4102 if let Some(referenced_table_name) = referenced_table_name {
4103 write!(f, " FROM {referenced_table_name}")?;
4104 }
4105
4106 if let Some(characteristics) = characteristics {
4107 write!(f, " {characteristics}")?;
4108 }
4109
4110 if !referencing.is_empty() {
4111 write!(f, " REFERENCING {}", display_separated(referencing, " "))?;
4112 }
4113
4114 if let Some(trigger_object) = trigger_object {
4115 write!(f, " {trigger_object}")?;
4116 }
4117 if let Some(condition) = condition {
4118 write!(f, " WHEN {condition}")?;
4119 }
4120 if let Some(exec_body) = exec_body {
4121 write!(f, " EXECUTE {exec_body}")?;
4122 }
4123 if let Some(statements) = statements {
4124 if *statements_as {
4125 write!(f, " AS")?;
4126 }
4127 write!(f, " {statements}")?;
4128 }
4129 Ok(())
4130 }
4131}
4132
4133#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4134#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4135#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4136pub struct DropTrigger {
4143 pub if_exists: bool,
4145 pub trigger_name: ObjectName,
4147 pub table_name: Option<ObjectName>,
4149 pub option: Option<ReferentialAction>,
4151}
4152
4153impl fmt::Display for DropTrigger {
4154 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4155 let DropTrigger {
4156 if_exists,
4157 trigger_name,
4158 table_name,
4159 option,
4160 } = self;
4161 write!(f, "DROP TRIGGER")?;
4162 if *if_exists {
4163 write!(f, " IF EXISTS")?;
4164 }
4165 match &table_name {
4166 Some(table_name) => write!(f, " {trigger_name} ON {table_name}")?,
4167 None => write!(f, " {trigger_name}")?,
4168 };
4169 if let Some(option) = option {
4170 write!(f, " {option}")?;
4171 }
4172 Ok(())
4173 }
4174}
4175
4176#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4182#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4183#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4184pub struct Truncate {
4185 pub table_names: Vec<super::TruncateTableTarget>,
4187 pub partitions: Option<Vec<Expr>>,
4189 pub table: bool,
4191 pub if_exists: bool,
4193 pub identity: Option<super::TruncateIdentityOption>,
4195 pub cascade: Option<super::CascadeOption>,
4197 pub on_cluster: Option<Ident>,
4200}
4201
4202impl fmt::Display for Truncate {
4203 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4204 let table = if self.table { "TABLE " } else { "" };
4205 let if_exists = if self.if_exists { "IF EXISTS " } else { "" };
4206
4207 write!(
4208 f,
4209 "TRUNCATE {table}{if_exists}{table_names}",
4210 table_names = display_comma_separated(&self.table_names)
4211 )?;
4212
4213 if let Some(identity) = &self.identity {
4214 match identity {
4215 super::TruncateIdentityOption::Restart => write!(f, " RESTART IDENTITY")?,
4216 super::TruncateIdentityOption::Continue => write!(f, " CONTINUE IDENTITY")?,
4217 }
4218 }
4219 if let Some(cascade) = &self.cascade {
4220 match cascade {
4221 super::CascadeOption::Cascade => write!(f, " CASCADE")?,
4222 super::CascadeOption::Restrict => write!(f, " RESTRICT")?,
4223 }
4224 }
4225
4226 if let Some(ref parts) = &self.partitions {
4227 if !parts.is_empty() {
4228 write!(f, " PARTITION ({})", display_comma_separated(parts))?;
4229 }
4230 }
4231 if let Some(on_cluster) = &self.on_cluster {
4232 write!(f, " ON CLUSTER {on_cluster}")?;
4233 }
4234 Ok(())
4235 }
4236}
4237
4238impl Spanned for Truncate {
4239 fn span(&self) -> Span {
4240 Span::union_iter(
4241 self.table_names.iter().map(|i| i.name.span()).chain(
4242 self.partitions
4243 .iter()
4244 .flat_map(|i| i.iter().map(|k| k.span())),
4245 ),
4246 )
4247 }
4248}
4249
4250#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4257#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4258#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4259pub struct Msck {
4260 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4262 pub table_name: ObjectName,
4263 pub repair: bool,
4265 pub partition_action: Option<super::AddDropSync>,
4267}
4268
4269impl fmt::Display for Msck {
4270 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4271 write!(
4272 f,
4273 "MSCK {repair}TABLE {table}",
4274 repair = if self.repair { "REPAIR " } else { "" },
4275 table = self.table_name
4276 )?;
4277 if let Some(pa) = &self.partition_action {
4278 write!(f, " {pa}")?;
4279 }
4280 Ok(())
4281 }
4282}
4283
4284impl Spanned for Msck {
4285 fn span(&self) -> Span {
4286 self.table_name.span()
4287 }
4288}
4289
4290#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4292#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4293#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4294pub struct CreateView {
4295 pub or_alter: bool,
4299 pub or_replace: bool,
4301 pub materialized: bool,
4303 pub secure: bool,
4306 pub name: ObjectName,
4308 pub name_before_not_exists: bool,
4319 pub columns: Vec<ViewColumnDef>,
4321 pub query: Box<Query>,
4323 pub options: CreateTableOptions,
4325 pub cluster_by: Vec<Ident>,
4327 pub comment: Option<String>,
4330 pub with_no_schema_binding: bool,
4332 pub if_not_exists: bool,
4334 pub temporary: bool,
4336 pub copy_grants: bool,
4339 pub to: Option<ObjectName>,
4342 pub params: Option<CreateViewParams>,
4344}
4345
4346impl fmt::Display for CreateView {
4347 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4348 write!(
4349 f,
4350 "CREATE {or_alter}{or_replace}",
4351 or_alter = if self.or_alter { "OR ALTER " } else { "" },
4352 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
4353 )?;
4354 if let Some(ref params) = self.params {
4355 params.fmt(f)?;
4356 }
4357 write!(
4358 f,
4359 "{secure}{materialized}{temporary}VIEW {if_not_and_name}{to}",
4360 if_not_and_name = if self.if_not_exists {
4361 if self.name_before_not_exists {
4362 format!("{} IF NOT EXISTS", self.name)
4363 } else {
4364 format!("IF NOT EXISTS {}", self.name)
4365 }
4366 } else {
4367 format!("{}", self.name)
4368 },
4369 secure = if self.secure { "SECURE " } else { "" },
4370 materialized = if self.materialized {
4371 "MATERIALIZED "
4372 } else {
4373 ""
4374 },
4375 temporary = if self.temporary { "TEMPORARY " } else { "" },
4376 to = self
4377 .to
4378 .as_ref()
4379 .map(|to| format!(" TO {to}"))
4380 .unwrap_or_default()
4381 )?;
4382 if self.copy_grants {
4383 write!(f, " COPY GRANTS")?;
4384 }
4385 if !self.columns.is_empty() {
4386 write!(f, " ({})", display_comma_separated(&self.columns))?;
4387 }
4388 if matches!(self.options, CreateTableOptions::With(_)) {
4389 write!(f, " {}", self.options)?;
4390 }
4391 if let Some(ref comment) = self.comment {
4392 write!(f, " COMMENT = '{}'", escape_single_quote_string(comment))?;
4393 }
4394 if !self.cluster_by.is_empty() {
4395 write!(
4396 f,
4397 " CLUSTER BY ({})",
4398 display_comma_separated(&self.cluster_by)
4399 )?;
4400 }
4401 if matches!(self.options, CreateTableOptions::Options(_)) {
4402 write!(f, " {}", self.options)?;
4403 }
4404 f.write_str(" AS")?;
4405 SpaceOrNewline.fmt(f)?;
4406 self.query.fmt(f)?;
4407 if self.with_no_schema_binding {
4408 write!(f, " WITH NO SCHEMA BINDING")?;
4409 }
4410 Ok(())
4411 }
4412}
4413
4414#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4417#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4418#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4419pub struct CreateExtension {
4420 pub name: Ident,
4422 pub if_not_exists: bool,
4424 pub cascade: bool,
4426 pub schema: Option<Ident>,
4428 pub version: Option<Ident>,
4430}
4431
4432impl fmt::Display for CreateExtension {
4433 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4434 write!(
4435 f,
4436 "CREATE EXTENSION {if_not_exists}{name}",
4437 if_not_exists = if self.if_not_exists {
4438 "IF NOT EXISTS "
4439 } else {
4440 ""
4441 },
4442 name = self.name
4443 )?;
4444 if self.cascade || self.schema.is_some() || self.version.is_some() {
4445 write!(f, " WITH")?;
4446
4447 if let Some(name) = &self.schema {
4448 write!(f, " SCHEMA {name}")?;
4449 }
4450 if let Some(version) = &self.version {
4451 write!(f, " VERSION {version}")?;
4452 }
4453 if self.cascade {
4454 write!(f, " CASCADE")?;
4455 }
4456 }
4457
4458 Ok(())
4459 }
4460}
4461
4462impl Spanned for CreateExtension {
4463 fn span(&self) -> Span {
4464 Span::empty()
4465 }
4466}
4467
4468#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4476#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4477#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4478pub struct DropExtension {
4479 pub names: Vec<Ident>,
4481 pub if_exists: bool,
4483 pub cascade_or_restrict: Option<ReferentialAction>,
4485}
4486
4487impl fmt::Display for DropExtension {
4488 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4489 write!(f, "DROP EXTENSION")?;
4490 if self.if_exists {
4491 write!(f, " IF EXISTS")?;
4492 }
4493 write!(f, " {}", display_comma_separated(&self.names))?;
4494 if let Some(cascade_or_restrict) = &self.cascade_or_restrict {
4495 write!(f, " {cascade_or_restrict}")?;
4496 }
4497 Ok(())
4498 }
4499}
4500
4501impl Spanned for DropExtension {
4502 fn span(&self) -> Span {
4503 Span::empty()
4504 }
4505}
4506
4507#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4510#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4511#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4512pub struct CreateCollation {
4513 pub if_not_exists: bool,
4515 pub name: ObjectName,
4517 pub definition: CreateCollationDefinition,
4519}
4520
4521#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4523#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4524#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4525pub enum CreateCollationDefinition {
4526 From(ObjectName),
4532 Options(Vec<SqlOption>),
4538}
4539
4540impl fmt::Display for CreateCollation {
4541 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4542 write!(
4543 f,
4544 "CREATE COLLATION {if_not_exists}{name}",
4545 if_not_exists = if self.if_not_exists {
4546 "IF NOT EXISTS "
4547 } else {
4548 ""
4549 },
4550 name = self.name
4551 )?;
4552 match &self.definition {
4553 CreateCollationDefinition::From(existing_collation) => {
4554 write!(f, " FROM {existing_collation}")
4555 }
4556 CreateCollationDefinition::Options(options) => {
4557 write!(f, " ({})", display_comma_separated(options))
4558 }
4559 }
4560 }
4561}
4562
4563impl Spanned for CreateCollation {
4564 fn span(&self) -> Span {
4565 Span::empty()
4566 }
4567}
4568
4569#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4572#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4573#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4574pub struct AlterCollation {
4575 pub name: ObjectName,
4577 pub operation: AlterCollationOperation,
4579}
4580
4581#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4583#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4584#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4585pub enum AlterCollationOperation {
4586 RenameTo {
4592 new_name: Ident,
4594 },
4595 OwnerTo(Owner),
4601 SetSchema {
4607 schema_name: ObjectName,
4609 },
4610 RefreshVersion,
4616}
4617
4618impl fmt::Display for AlterCollationOperation {
4619 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4620 match self {
4621 AlterCollationOperation::RenameTo { new_name } => write!(f, "RENAME TO {new_name}"),
4622 AlterCollationOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
4623 AlterCollationOperation::SetSchema { schema_name } => {
4624 write!(f, "SET SCHEMA {schema_name}")
4625 }
4626 AlterCollationOperation::RefreshVersion => write!(f, "REFRESH VERSION"),
4627 }
4628 }
4629}
4630
4631impl fmt::Display for AlterCollation {
4632 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4633 write!(f, "ALTER COLLATION {} {}", self.name, self.operation)
4634 }
4635}
4636
4637impl Spanned for AlterCollation {
4638 fn span(&self) -> Span {
4639 Span::empty()
4640 }
4641}
4642
4643#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4646#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4647#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4648pub enum AlterTableType {
4649 Iceberg,
4652 Dynamic,
4655 External,
4658}
4659
4660#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4662#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4663#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4664pub struct AlterTable {
4665 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4667 pub name: ObjectName,
4668 pub if_exists: bool,
4670 pub only: bool,
4672 pub operations: Vec<AlterTableOperation>,
4674 pub location: Option<HiveSetLocation>,
4676 pub on_cluster: Option<Ident>,
4680 pub table_type: Option<AlterTableType>,
4682 pub end_token: AttachedToken,
4684}
4685
4686impl fmt::Display for AlterTable {
4687 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4688 match &self.table_type {
4689 Some(AlterTableType::Iceberg) => write!(f, "ALTER ICEBERG TABLE ")?,
4690 Some(AlterTableType::Dynamic) => write!(f, "ALTER DYNAMIC TABLE ")?,
4691 Some(AlterTableType::External) => write!(f, "ALTER EXTERNAL TABLE ")?,
4692 None => write!(f, "ALTER TABLE ")?,
4693 }
4694
4695 if self.if_exists {
4696 write!(f, "IF EXISTS ")?;
4697 }
4698 if self.only {
4699 write!(f, "ONLY ")?;
4700 }
4701 write!(f, "{} ", &self.name)?;
4702 if let Some(cluster) = &self.on_cluster {
4703 write!(f, "ON CLUSTER {cluster} ")?;
4704 }
4705 write!(f, "{}", display_comma_separated(&self.operations))?;
4706 if let Some(loc) = &self.location {
4707 write!(f, " {loc}")?
4708 }
4709 Ok(())
4710 }
4711}
4712
4713#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4715#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4716#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4717pub struct DropFunction {
4718 pub if_exists: bool,
4720 pub func_desc: Vec<FunctionDesc>,
4722 pub drop_behavior: Option<DropBehavior>,
4724}
4725
4726impl fmt::Display for DropFunction {
4727 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4728 write!(
4729 f,
4730 "DROP FUNCTION{} {}",
4731 if self.if_exists { " IF EXISTS" } else { "" },
4732 display_comma_separated(&self.func_desc),
4733 )?;
4734 if let Some(op) = &self.drop_behavior {
4735 write!(f, " {op}")?;
4736 }
4737 Ok(())
4738 }
4739}
4740
4741impl Spanned for DropFunction {
4742 fn span(&self) -> Span {
4743 Span::empty()
4744 }
4745}
4746
4747#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4750#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4751#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4752pub struct CreateOperator {
4753 pub name: ObjectName,
4755 pub function: ObjectName,
4757 pub is_procedure: bool,
4759 pub left_arg: Option<DataType>,
4761 pub right_arg: Option<DataType>,
4763 pub options: Vec<OperatorOption>,
4765}
4766
4767#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4770#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4771#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4772pub struct CreateOperatorFamily {
4773 pub name: ObjectName,
4775 pub using: Ident,
4777}
4778
4779#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4782#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4783#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4784pub struct CreateOperatorClass {
4785 pub name: ObjectName,
4787 pub default: bool,
4789 pub for_type: DataType,
4791 pub using: Ident,
4793 pub family: Option<ObjectName>,
4795 pub items: Vec<OperatorClassItem>,
4797}
4798
4799impl fmt::Display for CreateOperator {
4800 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4801 write!(f, "CREATE OPERATOR {} (", self.name)?;
4802
4803 let function_keyword = if self.is_procedure {
4804 "PROCEDURE"
4805 } else {
4806 "FUNCTION"
4807 };
4808 let mut params = vec![format!("{} = {}", function_keyword, self.function)];
4809
4810 if let Some(left_arg) = &self.left_arg {
4811 params.push(format!("LEFTARG = {}", left_arg));
4812 }
4813 if let Some(right_arg) = &self.right_arg {
4814 params.push(format!("RIGHTARG = {}", right_arg));
4815 }
4816
4817 for option in &self.options {
4818 params.push(option.to_string());
4819 }
4820
4821 write!(f, "{}", params.join(", "))?;
4822 write!(f, ")")
4823 }
4824}
4825
4826impl fmt::Display for CreateOperatorFamily {
4827 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4828 write!(
4829 f,
4830 "CREATE OPERATOR FAMILY {} USING {}",
4831 self.name, self.using
4832 )
4833 }
4834}
4835
4836impl fmt::Display for CreateOperatorClass {
4837 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4838 write!(f, "CREATE OPERATOR CLASS {}", self.name)?;
4839 if self.default {
4840 write!(f, " DEFAULT")?;
4841 }
4842 write!(f, " FOR TYPE {} USING {}", self.for_type, self.using)?;
4843 if let Some(family) = &self.family {
4844 write!(f, " FAMILY {}", family)?;
4845 }
4846 write!(f, " AS {}", display_comma_separated(&self.items))
4847 }
4848}
4849
4850#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4852#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4853#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4854pub struct OperatorArgTypes {
4855 pub left: DataType,
4857 pub right: DataType,
4859}
4860
4861impl fmt::Display for OperatorArgTypes {
4862 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4863 write!(f, "{}, {}", self.left, self.right)
4864 }
4865}
4866
4867#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4869#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4870#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4871pub enum OperatorClassItem {
4872 Operator {
4874 strategy_number: u64,
4876 operator_name: ObjectName,
4878 op_types: Option<OperatorArgTypes>,
4880 purpose: Option<OperatorPurpose>,
4882 },
4883 Function {
4885 support_number: u64,
4887 op_types: Option<Vec<DataType>>,
4889 function_name: ObjectName,
4891 argument_types: Vec<DataType>,
4893 },
4894 Storage {
4896 storage_type: DataType,
4898 },
4899}
4900
4901#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4903#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4904#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4905pub enum OperatorPurpose {
4906 ForSearch,
4908 ForOrderBy {
4910 sort_family: ObjectName,
4912 },
4913}
4914
4915impl fmt::Display for OperatorClassItem {
4916 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4917 match self {
4918 OperatorClassItem::Operator {
4919 strategy_number,
4920 operator_name,
4921 op_types,
4922 purpose,
4923 } => {
4924 write!(f, "OPERATOR {strategy_number} {operator_name}")?;
4925 if let Some(types) = op_types {
4926 write!(f, " ({types})")?;
4927 }
4928 if let Some(purpose) = purpose {
4929 write!(f, " {purpose}")?;
4930 }
4931 Ok(())
4932 }
4933 OperatorClassItem::Function {
4934 support_number,
4935 op_types,
4936 function_name,
4937 argument_types,
4938 } => {
4939 write!(f, "FUNCTION {support_number}")?;
4940 if let Some(types) = op_types {
4941 write!(f, " ({})", display_comma_separated(types))?;
4942 }
4943 write!(f, " {function_name}")?;
4944 if !argument_types.is_empty() {
4945 write!(f, "({})", display_comma_separated(argument_types))?;
4946 }
4947 Ok(())
4948 }
4949 OperatorClassItem::Storage { storage_type } => {
4950 write!(f, "STORAGE {storage_type}")
4951 }
4952 }
4953 }
4954}
4955
4956impl fmt::Display for OperatorPurpose {
4957 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4958 match self {
4959 OperatorPurpose::ForSearch => write!(f, "FOR SEARCH"),
4960 OperatorPurpose::ForOrderBy { sort_family } => {
4961 write!(f, "FOR ORDER BY {sort_family}")
4962 }
4963 }
4964 }
4965}
4966
4967#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4970#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4971#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4972pub struct DropOperator {
4973 pub if_exists: bool,
4975 pub operators: Vec<DropOperatorSignature>,
4977 pub drop_behavior: Option<DropBehavior>,
4979}
4980
4981#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4983#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4984#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4985pub struct DropOperatorSignature {
4986 pub name: ObjectName,
4988 pub left_type: Option<DataType>,
4990 pub right_type: DataType,
4992}
4993
4994impl fmt::Display for DropOperatorSignature {
4995 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4996 write!(f, "{} (", self.name)?;
4997 if let Some(left_type) = &self.left_type {
4998 write!(f, "{}", left_type)?;
4999 } else {
5000 write!(f, "NONE")?;
5001 }
5002 write!(f, ", {})", self.right_type)
5003 }
5004}
5005
5006impl fmt::Display for DropOperator {
5007 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5008 write!(f, "DROP OPERATOR")?;
5009 if self.if_exists {
5010 write!(f, " IF EXISTS")?;
5011 }
5012 write!(f, " {}", display_comma_separated(&self.operators))?;
5013 if let Some(drop_behavior) = &self.drop_behavior {
5014 write!(f, " {}", drop_behavior)?;
5015 }
5016 Ok(())
5017 }
5018}
5019
5020impl Spanned for DropOperator {
5021 fn span(&self) -> Span {
5022 Span::empty()
5023 }
5024}
5025
5026#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5029#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5030#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5031pub struct DropOperatorFamily {
5032 pub if_exists: bool,
5034 pub names: Vec<ObjectName>,
5036 pub using: Ident,
5038 pub drop_behavior: Option<DropBehavior>,
5040}
5041
5042impl fmt::Display for DropOperatorFamily {
5043 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5044 write!(f, "DROP OPERATOR FAMILY")?;
5045 if self.if_exists {
5046 write!(f, " IF EXISTS")?;
5047 }
5048 write!(f, " {}", display_comma_separated(&self.names))?;
5049 write!(f, " USING {}", self.using)?;
5050 if let Some(drop_behavior) = &self.drop_behavior {
5051 write!(f, " {}", drop_behavior)?;
5052 }
5053 Ok(())
5054 }
5055}
5056
5057impl Spanned for DropOperatorFamily {
5058 fn span(&self) -> Span {
5059 Span::empty()
5060 }
5061}
5062
5063#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5066#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5067#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5068pub struct DropOperatorClass {
5069 pub if_exists: bool,
5071 pub names: Vec<ObjectName>,
5073 pub using: Ident,
5075 pub drop_behavior: Option<DropBehavior>,
5077}
5078
5079impl fmt::Display for DropOperatorClass {
5080 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5081 write!(f, "DROP OPERATOR CLASS")?;
5082 if self.if_exists {
5083 write!(f, " IF EXISTS")?;
5084 }
5085 write!(f, " {}", display_comma_separated(&self.names))?;
5086 write!(f, " USING {}", self.using)?;
5087 if let Some(drop_behavior) = &self.drop_behavior {
5088 write!(f, " {}", drop_behavior)?;
5089 }
5090 Ok(())
5091 }
5092}
5093
5094impl Spanned for DropOperatorClass {
5095 fn span(&self) -> Span {
5096 Span::empty()
5097 }
5098}
5099
5100#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5102#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5103#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5104pub enum OperatorFamilyItem {
5105 Operator {
5107 strategy_number: u64,
5109 operator_name: ObjectName,
5111 op_types: Vec<DataType>,
5113 purpose: Option<OperatorPurpose>,
5115 },
5116 Function {
5118 support_number: u64,
5120 op_types: Option<Vec<DataType>>,
5122 function_name: ObjectName,
5124 argument_types: Vec<DataType>,
5126 },
5127}
5128
5129#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5131#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5132#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5133pub enum OperatorFamilyDropItem {
5134 Operator {
5136 strategy_number: u64,
5138 op_types: Vec<DataType>,
5140 },
5141 Function {
5143 support_number: u64,
5145 op_types: Vec<DataType>,
5147 },
5148}
5149
5150impl fmt::Display for OperatorFamilyItem {
5151 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5152 match self {
5153 OperatorFamilyItem::Operator {
5154 strategy_number,
5155 operator_name,
5156 op_types,
5157 purpose,
5158 } => {
5159 write!(
5160 f,
5161 "OPERATOR {strategy_number} {operator_name} ({})",
5162 display_comma_separated(op_types)
5163 )?;
5164 if let Some(purpose) = purpose {
5165 write!(f, " {purpose}")?;
5166 }
5167 Ok(())
5168 }
5169 OperatorFamilyItem::Function {
5170 support_number,
5171 op_types,
5172 function_name,
5173 argument_types,
5174 } => {
5175 write!(f, "FUNCTION {support_number}")?;
5176 if let Some(types) = op_types {
5177 write!(f, " ({})", display_comma_separated(types))?;
5178 }
5179 write!(f, " {function_name}")?;
5180 if !argument_types.is_empty() {
5181 write!(f, "({})", display_comma_separated(argument_types))?;
5182 }
5183 Ok(())
5184 }
5185 }
5186 }
5187}
5188
5189impl fmt::Display for OperatorFamilyDropItem {
5190 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5191 match self {
5192 OperatorFamilyDropItem::Operator {
5193 strategy_number,
5194 op_types,
5195 } => {
5196 write!(
5197 f,
5198 "OPERATOR {strategy_number} ({})",
5199 display_comma_separated(op_types)
5200 )
5201 }
5202 OperatorFamilyDropItem::Function {
5203 support_number,
5204 op_types,
5205 } => {
5206 write!(
5207 f,
5208 "FUNCTION {support_number} ({})",
5209 display_comma_separated(op_types)
5210 )
5211 }
5212 }
5213 }
5214}
5215
5216#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5219#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5220#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5221pub struct AlterOperatorFamily {
5222 pub name: ObjectName,
5224 pub using: Ident,
5226 pub operation: AlterOperatorFamilyOperation,
5228}
5229
5230#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5232#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5233#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5234pub enum AlterOperatorFamilyOperation {
5235 Add {
5237 items: Vec<OperatorFamilyItem>,
5239 },
5240 Drop {
5242 items: Vec<OperatorFamilyDropItem>,
5244 },
5245 RenameTo {
5247 new_name: ObjectName,
5249 },
5250 OwnerTo(Owner),
5252 SetSchema {
5254 schema_name: ObjectName,
5256 },
5257}
5258
5259impl fmt::Display for AlterOperatorFamily {
5260 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5261 write!(
5262 f,
5263 "ALTER OPERATOR FAMILY {} USING {}",
5264 self.name, self.using
5265 )?;
5266 write!(f, " {}", self.operation)
5267 }
5268}
5269
5270impl fmt::Display for AlterOperatorFamilyOperation {
5271 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5272 match self {
5273 AlterOperatorFamilyOperation::Add { items } => {
5274 write!(f, "ADD {}", display_comma_separated(items))
5275 }
5276 AlterOperatorFamilyOperation::Drop { items } => {
5277 write!(f, "DROP {}", display_comma_separated(items))
5278 }
5279 AlterOperatorFamilyOperation::RenameTo { new_name } => {
5280 write!(f, "RENAME TO {new_name}")
5281 }
5282 AlterOperatorFamilyOperation::OwnerTo(owner) => {
5283 write!(f, "OWNER TO {owner}")
5284 }
5285 AlterOperatorFamilyOperation::SetSchema { schema_name } => {
5286 write!(f, "SET SCHEMA {schema_name}")
5287 }
5288 }
5289 }
5290}
5291
5292impl Spanned for AlterOperatorFamily {
5293 fn span(&self) -> Span {
5294 Span::empty()
5295 }
5296}
5297
5298#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5301#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5302#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5303pub struct AlterOperatorClass {
5304 pub name: ObjectName,
5306 pub using: Ident,
5308 pub operation: AlterOperatorClassOperation,
5310}
5311
5312#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5314#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5315#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5316pub enum AlterOperatorClassOperation {
5317 RenameTo {
5320 new_name: ObjectName,
5322 },
5323 OwnerTo(Owner),
5325 SetSchema {
5328 schema_name: ObjectName,
5330 },
5331}
5332
5333impl fmt::Display for AlterOperatorClass {
5334 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5335 write!(f, "ALTER OPERATOR CLASS {} USING {}", self.name, self.using)?;
5336 write!(f, " {}", self.operation)
5337 }
5338}
5339
5340impl fmt::Display for AlterOperatorClassOperation {
5341 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5342 match self {
5343 AlterOperatorClassOperation::RenameTo { new_name } => {
5344 write!(f, "RENAME TO {new_name}")
5345 }
5346 AlterOperatorClassOperation::OwnerTo(owner) => {
5347 write!(f, "OWNER TO {owner}")
5348 }
5349 AlterOperatorClassOperation::SetSchema { schema_name } => {
5350 write!(f, "SET SCHEMA {schema_name}")
5351 }
5352 }
5353 }
5354}
5355
5356impl Spanned for AlterOperatorClass {
5357 fn span(&self) -> Span {
5358 Span::empty()
5359 }
5360}
5361
5362#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5364#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5365#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5366pub struct AlterFunction {
5367 pub kind: AlterFunctionKind,
5369 pub function: FunctionDesc,
5371 pub aggregate_order_by: Option<Vec<OperateFunctionArg>>,
5375 pub aggregate_star: bool,
5379 pub operation: AlterFunctionOperation,
5381}
5382
5383#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5385#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5386#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5387pub enum AlterFunctionKind {
5388 Function,
5390 Aggregate,
5392}
5393
5394impl fmt::Display for AlterFunctionKind {
5395 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5396 match self {
5397 Self::Function => write!(f, "FUNCTION"),
5398 Self::Aggregate => write!(f, "AGGREGATE"),
5399 }
5400 }
5401}
5402
5403#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5405#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5406#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5407pub enum AlterFunctionOperation {
5408 RenameTo {
5410 new_name: Ident,
5412 },
5413 OwnerTo(Owner),
5415 SetSchema {
5417 schema_name: ObjectName,
5419 },
5420 DependsOnExtension {
5422 no: bool,
5424 extension_name: ObjectName,
5426 },
5427 Actions {
5429 actions: Vec<AlterFunctionAction>,
5431 restrict: bool,
5433 },
5434}
5435
5436#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5438#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5439#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5440pub enum AlterFunctionAction {
5441 CalledOnNull(FunctionCalledOnNull),
5443 Behavior(FunctionBehavior),
5445 Leakproof(bool),
5447 Security {
5449 external: bool,
5451 security: FunctionSecurity,
5453 },
5454 Parallel(FunctionParallel),
5456 Cost(Expr),
5458 Rows(Expr),
5460 Support(ObjectName),
5462 Set(FunctionDefinitionSetParam),
5465 Reset(ResetConfig),
5467}
5468
5469impl fmt::Display for AlterFunction {
5470 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5471 write!(f, "ALTER {} ", self.kind)?;
5472 match self.kind {
5473 AlterFunctionKind::Function => {
5474 write!(f, "{} ", self.function)?;
5475 }
5476 AlterFunctionKind::Aggregate => {
5477 write!(f, "{}(", self.function.name)?;
5478 if self.aggregate_star {
5479 write!(f, "*")?;
5480 } else {
5481 if let Some(args) = &self.function.args {
5482 write!(f, "{}", display_comma_separated(args))?;
5483 }
5484 if let Some(order_by_args) = &self.aggregate_order_by {
5485 if self
5486 .function
5487 .args
5488 .as_ref()
5489 .is_some_and(|args| !args.is_empty())
5490 {
5491 write!(f, " ")?;
5492 }
5493 write!(f, "ORDER BY {}", display_comma_separated(order_by_args))?;
5494 }
5495 }
5496 write!(f, ") ")?;
5497 }
5498 }
5499 write!(f, "{}", self.operation)
5500 }
5501}
5502
5503impl fmt::Display for AlterFunctionOperation {
5504 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5505 match self {
5506 AlterFunctionOperation::RenameTo { new_name } => {
5507 write!(f, "RENAME TO {new_name}")
5508 }
5509 AlterFunctionOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
5510 AlterFunctionOperation::SetSchema { schema_name } => {
5511 write!(f, "SET SCHEMA {schema_name}")
5512 }
5513 AlterFunctionOperation::DependsOnExtension { no, extension_name } => {
5514 if *no {
5515 write!(f, "NO DEPENDS ON EXTENSION {extension_name}")
5516 } else {
5517 write!(f, "DEPENDS ON EXTENSION {extension_name}")
5518 }
5519 }
5520 AlterFunctionOperation::Actions { actions, restrict } => {
5521 write!(f, "{}", display_separated(actions, " "))?;
5522 if *restrict {
5523 write!(f, " RESTRICT")?;
5524 }
5525 Ok(())
5526 }
5527 }
5528 }
5529}
5530
5531impl fmt::Display for AlterFunctionAction {
5532 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5533 match self {
5534 AlterFunctionAction::CalledOnNull(called_on_null) => write!(f, "{called_on_null}"),
5535 AlterFunctionAction::Behavior(behavior) => write!(f, "{behavior}"),
5536 AlterFunctionAction::Leakproof(leakproof) => {
5537 if *leakproof {
5538 write!(f, "LEAKPROOF")
5539 } else {
5540 write!(f, "NOT LEAKPROOF")
5541 }
5542 }
5543 AlterFunctionAction::Security { external, security } => {
5544 if *external {
5545 write!(f, "EXTERNAL ")?;
5546 }
5547 write!(f, "{security}")
5548 }
5549 AlterFunctionAction::Parallel(parallel) => write!(f, "{parallel}"),
5550 AlterFunctionAction::Cost(execution_cost) => write!(f, "COST {execution_cost}"),
5551 AlterFunctionAction::Rows(result_rows) => write!(f, "ROWS {result_rows}"),
5552 AlterFunctionAction::Support(support_function) => {
5553 write!(f, "SUPPORT {support_function}")
5554 }
5555 AlterFunctionAction::Set(set_param) => write!(f, "{set_param}"),
5556 AlterFunctionAction::Reset(reset_config) => match reset_config {
5557 ResetConfig::ALL => write!(f, "RESET ALL"),
5558 ResetConfig::ConfigName(name) => write!(f, "RESET {name}"),
5559 },
5560 }
5561 }
5562}
5563
5564impl Spanned for AlterFunction {
5565 fn span(&self) -> Span {
5566 Span::empty()
5567 }
5568}
5569
5570#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5574#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5575#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5576pub struct CreatePolicy {
5577 pub name: Ident,
5579 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5581 pub table_name: ObjectName,
5582 pub policy_type: Option<CreatePolicyType>,
5584 pub command: Option<CreatePolicyCommand>,
5586 pub to: Option<Vec<Owner>>,
5588 pub using: Option<Expr>,
5590 pub with_check: Option<Expr>,
5592}
5593
5594impl fmt::Display for CreatePolicy {
5595 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5596 write!(
5597 f,
5598 "CREATE POLICY {name} ON {table_name}",
5599 name = self.name,
5600 table_name = self.table_name,
5601 )?;
5602 if let Some(ref policy_type) = self.policy_type {
5603 write!(f, " AS {policy_type}")?;
5604 }
5605 if let Some(ref command) = self.command {
5606 write!(f, " FOR {command}")?;
5607 }
5608 if let Some(ref to) = self.to {
5609 write!(f, " TO {}", display_comma_separated(to))?;
5610 }
5611 if let Some(ref using) = self.using {
5612 write!(f, " USING ({using})")?;
5613 }
5614 if let Some(ref with_check) = self.with_check {
5615 write!(f, " WITH CHECK ({with_check})")?;
5616 }
5617 Ok(())
5618 }
5619}
5620
5621#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5627#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5628#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5629pub enum CreatePolicyType {
5630 Permissive,
5632 Restrictive,
5634}
5635
5636impl fmt::Display for CreatePolicyType {
5637 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5638 match self {
5639 CreatePolicyType::Permissive => write!(f, "PERMISSIVE"),
5640 CreatePolicyType::Restrictive => write!(f, "RESTRICTIVE"),
5641 }
5642 }
5643}
5644
5645#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5651#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5652#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5653pub enum CreatePolicyCommand {
5654 All,
5656 Select,
5658 Insert,
5660 Update,
5662 Delete,
5664}
5665
5666impl fmt::Display for CreatePolicyCommand {
5667 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5668 match self {
5669 CreatePolicyCommand::All => write!(f, "ALL"),
5670 CreatePolicyCommand::Select => write!(f, "SELECT"),
5671 CreatePolicyCommand::Insert => write!(f, "INSERT"),
5672 CreatePolicyCommand::Update => write!(f, "UPDATE"),
5673 CreatePolicyCommand::Delete => write!(f, "DELETE"),
5674 }
5675 }
5676}
5677
5678#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5682#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5683#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5684pub struct DropPolicy {
5685 pub if_exists: bool,
5687 pub name: Ident,
5689 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5691 pub table_name: ObjectName,
5692 pub drop_behavior: Option<DropBehavior>,
5694}
5695
5696impl fmt::Display for DropPolicy {
5697 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5698 write!(
5699 f,
5700 "DROP POLICY {if_exists}{name} ON {table_name}",
5701 if_exists = if self.if_exists { "IF EXISTS " } else { "" },
5702 name = self.name,
5703 table_name = self.table_name
5704 )?;
5705 if let Some(ref behavior) = self.drop_behavior {
5706 write!(f, " {behavior}")?;
5707 }
5708 Ok(())
5709 }
5710}
5711
5712impl From<CreatePolicy> for crate::ast::Statement {
5713 fn from(v: CreatePolicy) -> Self {
5714 crate::ast::Statement::CreatePolicy(v)
5715 }
5716}
5717
5718impl From<DropPolicy> for crate::ast::Statement {
5719 fn from(v: DropPolicy) -> Self {
5720 crate::ast::Statement::DropPolicy(v)
5721 }
5722}
5723
5724#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5731#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5732#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5733pub struct AlterPolicy {
5734 pub name: Ident,
5736 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5738 pub table_name: ObjectName,
5739 pub operation: AlterPolicyOperation,
5741}
5742
5743impl fmt::Display for AlterPolicy {
5744 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5745 write!(
5746 f,
5747 "ALTER POLICY {name} ON {table_name}{operation}",
5748 name = self.name,
5749 table_name = self.table_name,
5750 operation = self.operation
5751 )
5752 }
5753}
5754
5755impl From<AlterPolicy> for crate::ast::Statement {
5756 fn from(v: AlterPolicy) -> Self {
5757 crate::ast::Statement::AlterPolicy(v)
5758 }
5759}