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 SetLogged,
449 SetUnlogged,
453 OwnerTo {
457 new_owner: Owner,
459 },
460 ClusterBy {
463 exprs: Vec<Expr>,
465 },
466 DropClusteringKey,
468 AlterSortKey {
471 columns: Vec<Expr>,
473 },
474 SuspendRecluster,
476 ResumeRecluster,
478 Refresh {
484 subpath: Option<String>,
486 },
487 Suspend,
491 Resume,
495 Algorithm {
501 equals: bool,
503 algorithm: AlterTableAlgorithm,
505 },
506
507 Lock {
513 equals: bool,
515 lock: AlterTableLock,
517 },
518 AutoIncrement {
524 equals: bool,
526 value: ValueWithSpan,
528 },
529 ValidateConstraint {
531 name: Ident,
533 },
534 SetOptionsParens {
542 options: Vec<SqlOption>,
544 },
545}
546
547#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
551#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
552#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
553pub enum AlterPolicyOperation {
554 Rename {
556 new_name: Ident,
558 },
559 Apply {
561 to: Option<Vec<Owner>>,
563 using: Option<Expr>,
565 with_check: Option<Expr>,
567 },
568}
569
570impl fmt::Display for AlterPolicyOperation {
571 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
572 match self {
573 AlterPolicyOperation::Rename { new_name } => {
574 write!(f, " RENAME TO {new_name}")
575 }
576 AlterPolicyOperation::Apply {
577 to,
578 using,
579 with_check,
580 } => {
581 if let Some(to) = to {
582 write!(f, " TO {}", display_comma_separated(to))?;
583 }
584 if let Some(using) = using {
585 write!(f, " USING ({using})")?;
586 }
587 if let Some(with_check) = with_check {
588 write!(f, " WITH CHECK ({with_check})")?;
589 }
590 Ok(())
591 }
592 }
593 }
594}
595
596#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
600#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
601#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
602pub enum AlterTableAlgorithm {
604 Default,
606 Instant,
608 Inplace,
610 Copy,
612}
613
614impl fmt::Display for AlterTableAlgorithm {
615 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
616 f.write_str(match self {
617 Self::Default => "DEFAULT",
618 Self::Instant => "INSTANT",
619 Self::Inplace => "INPLACE",
620 Self::Copy => "COPY",
621 })
622 }
623}
624
625#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
629#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
630#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
631pub enum AlterTableLock {
633 Default,
635 None,
637 Shared,
639 Exclusive,
641}
642
643impl fmt::Display for AlterTableLock {
644 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
645 f.write_str(match self {
646 Self::Default => "DEFAULT",
647 Self::None => "NONE",
648 Self::Shared => "SHARED",
649 Self::Exclusive => "EXCLUSIVE",
650 })
651 }
652}
653
654#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
655#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
656#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
657pub enum Owner {
659 Ident(Ident),
661 CurrentRole,
663 CurrentUser,
665 SessionUser,
667}
668
669impl fmt::Display for Owner {
670 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
671 match self {
672 Owner::Ident(ident) => write!(f, "{ident}"),
673 Owner::CurrentRole => write!(f, "CURRENT_ROLE"),
674 Owner::CurrentUser => write!(f, "CURRENT_USER"),
675 Owner::SessionUser => write!(f, "SESSION_USER"),
676 }
677 }
678}
679
680#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
681#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
682#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
683pub enum AlterConnectorOwner {
685 User(Ident),
687 Role(Ident),
689}
690
691impl fmt::Display for AlterConnectorOwner {
692 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
693 match self {
694 AlterConnectorOwner::User(ident) => write!(f, "USER {ident}"),
695 AlterConnectorOwner::Role(ident) => write!(f, "ROLE {ident}"),
696 }
697 }
698}
699
700#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
701#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
702#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
703pub enum AlterIndexOperation {
705 RenameIndex {
707 index_name: ObjectName,
709 },
710}
711
712impl fmt::Display for AlterTableOperation {
713 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
714 match self {
715 AlterTableOperation::AddPartitions {
716 if_not_exists,
717 new_partitions,
718 } => write!(
719 f,
720 "ADD{ine} {}",
721 display_separated(new_partitions, " "),
722 ine = if *if_not_exists { " IF NOT EXISTS" } else { "" }
723 ),
724 AlterTableOperation::AddConstraint {
725 not_valid,
726 constraint,
727 } => {
728 write!(f, "ADD {constraint}")?;
729 if *not_valid {
730 write!(f, " NOT VALID")?;
731 }
732 Ok(())
733 }
734 AlterTableOperation::AddColumn {
735 column_keyword,
736 if_not_exists,
737 column_def,
738 column_position,
739 } => {
740 write!(f, "ADD")?;
741 if *column_keyword {
742 write!(f, " COLUMN")?;
743 }
744 if *if_not_exists {
745 write!(f, " IF NOT EXISTS")?;
746 }
747 write!(f, " {column_def}")?;
748
749 if let Some(position) = column_position {
750 write!(f, " {position}")?;
751 }
752
753 Ok(())
754 }
755 AlterTableOperation::AddProjection {
756 if_not_exists,
757 name,
758 select: query,
759 } => {
760 write!(f, "ADD PROJECTION")?;
761 if *if_not_exists {
762 write!(f, " IF NOT EXISTS")?;
763 }
764 write!(f, " {name} ({query})")
765 }
766 AlterTableOperation::Algorithm { equals, algorithm } => {
767 write!(
768 f,
769 "ALGORITHM {}{}",
770 if *equals { "= " } else { "" },
771 algorithm
772 )
773 }
774 AlterTableOperation::DropProjection { if_exists, name } => {
775 write!(f, "DROP PROJECTION")?;
776 if *if_exists {
777 write!(f, " IF EXISTS")?;
778 }
779 write!(f, " {name}")
780 }
781 AlterTableOperation::MaterializeProjection {
782 if_exists,
783 name,
784 partition,
785 } => {
786 write!(f, "MATERIALIZE PROJECTION")?;
787 if *if_exists {
788 write!(f, " IF EXISTS")?;
789 }
790 write!(f, " {name}")?;
791 if let Some(partition) = partition {
792 write!(f, " IN PARTITION {partition}")?;
793 }
794 Ok(())
795 }
796 AlterTableOperation::ClearProjection {
797 if_exists,
798 name,
799 partition,
800 } => {
801 write!(f, "CLEAR PROJECTION")?;
802 if *if_exists {
803 write!(f, " IF EXISTS")?;
804 }
805 write!(f, " {name}")?;
806 if let Some(partition) = partition {
807 write!(f, " IN PARTITION {partition}")?;
808 }
809 Ok(())
810 }
811 AlterTableOperation::AlterColumn { column_name, op } => {
812 write!(f, "ALTER COLUMN {column_name} {op}")
813 }
814 AlterTableOperation::DisableRowLevelSecurity => {
815 write!(f, "DISABLE ROW LEVEL SECURITY")
816 }
817 AlterTableOperation::DisableRule { name } => {
818 write!(f, "DISABLE RULE {name}")
819 }
820 AlterTableOperation::DisableTrigger { name } => {
821 write!(f, "DISABLE TRIGGER {name}")
822 }
823 AlterTableOperation::DropPartitions {
824 partitions,
825 if_exists,
826 } => write!(
827 f,
828 "DROP{ie} PARTITION ({})",
829 display_comma_separated(partitions),
830 ie = if *if_exists { " IF EXISTS" } else { "" }
831 ),
832 AlterTableOperation::DropConstraint {
833 if_exists,
834 name,
835 drop_behavior,
836 } => {
837 write!(
838 f,
839 "DROP CONSTRAINT {}{}",
840 if *if_exists { "IF EXISTS " } else { "" },
841 name
842 )?;
843 if let Some(drop_behavior) = drop_behavior {
844 write!(f, " {drop_behavior}")?;
845 }
846 Ok(())
847 }
848 AlterTableOperation::DropPrimaryKey { drop_behavior } => {
849 write!(f, "DROP PRIMARY KEY")?;
850 if let Some(drop_behavior) = drop_behavior {
851 write!(f, " {drop_behavior}")?;
852 }
853 Ok(())
854 }
855 AlterTableOperation::DropForeignKey {
856 name,
857 drop_behavior,
858 } => {
859 write!(f, "DROP FOREIGN KEY {name}")?;
860 if let Some(drop_behavior) = drop_behavior {
861 write!(f, " {drop_behavior}")?;
862 }
863 Ok(())
864 }
865 AlterTableOperation::DropIndex { name } => write!(f, "DROP INDEX {name}"),
866 AlterTableOperation::DropColumn {
867 has_column_keyword,
868 column_names: column_name,
869 if_exists,
870 drop_behavior,
871 } => {
872 write!(
873 f,
874 "DROP {}{}{}",
875 if *has_column_keyword { "COLUMN " } else { "" },
876 if *if_exists { "IF EXISTS " } else { "" },
877 display_comma_separated(column_name),
878 )?;
879 if let Some(drop_behavior) = drop_behavior {
880 write!(f, " {drop_behavior}")?;
881 }
882 Ok(())
883 }
884 AlterTableOperation::AttachPartition { partition } => {
885 write!(f, "ATTACH {partition}")
886 }
887 AlterTableOperation::DetachPartition { partition } => {
888 write!(f, "DETACH {partition}")
889 }
890 AlterTableOperation::EnableAlwaysRule { name } => {
891 write!(f, "ENABLE ALWAYS RULE {name}")
892 }
893 AlterTableOperation::EnableAlwaysTrigger { name } => {
894 write!(f, "ENABLE ALWAYS TRIGGER {name}")
895 }
896 AlterTableOperation::EnableReplicaRule { name } => {
897 write!(f, "ENABLE REPLICA RULE {name}")
898 }
899 AlterTableOperation::EnableReplicaTrigger { name } => {
900 write!(f, "ENABLE REPLICA TRIGGER {name}")
901 }
902 AlterTableOperation::EnableRowLevelSecurity => {
903 write!(f, "ENABLE ROW LEVEL SECURITY")
904 }
905 AlterTableOperation::ForceRowLevelSecurity => {
906 write!(f, "FORCE ROW LEVEL SECURITY")
907 }
908 AlterTableOperation::NoForceRowLevelSecurity => {
909 write!(f, "NO FORCE ROW LEVEL SECURITY")
910 }
911 AlterTableOperation::EnableRule { name } => {
912 write!(f, "ENABLE RULE {name}")
913 }
914 AlterTableOperation::EnableTrigger { name } => {
915 write!(f, "ENABLE TRIGGER {name}")
916 }
917 AlterTableOperation::RenamePartitions {
918 old_partitions,
919 new_partitions,
920 } => write!(
921 f,
922 "PARTITION ({}) RENAME TO PARTITION ({})",
923 display_comma_separated(old_partitions),
924 display_comma_separated(new_partitions)
925 ),
926 AlterTableOperation::RenameColumn {
927 old_column_name,
928 new_column_name,
929 } => write!(f, "RENAME COLUMN {old_column_name} TO {new_column_name}"),
930 AlterTableOperation::RenameTable { table_name } => {
931 write!(f, "RENAME {table_name}")
932 }
933 AlterTableOperation::ChangeColumn {
934 old_name,
935 new_name,
936 data_type,
937 options,
938 column_position,
939 } => {
940 write!(f, "CHANGE COLUMN {old_name} {new_name} {data_type}")?;
941 if !options.is_empty() {
942 write!(f, " {}", display_separated(options, " "))?;
943 }
944 if let Some(position) = column_position {
945 write!(f, " {position}")?;
946 }
947
948 Ok(())
949 }
950 AlterTableOperation::ModifyColumn {
951 col_name,
952 data_type,
953 options,
954 column_position,
955 } => {
956 write!(f, "MODIFY COLUMN {col_name} {data_type}")?;
957 if !options.is_empty() {
958 write!(f, " {}", display_separated(options, " "))?;
959 }
960 if let Some(position) = column_position {
961 write!(f, " {position}")?;
962 }
963
964 Ok(())
965 }
966 AlterTableOperation::RenameConstraint { old_name, new_name } => {
967 write!(f, "RENAME CONSTRAINT {old_name} TO {new_name}")
968 }
969 AlterTableOperation::SwapWith { table_name } => {
970 write!(f, "SWAP WITH {table_name}")
971 }
972 AlterTableOperation::OwnerTo { new_owner } => {
973 write!(f, "OWNER TO {new_owner}")
974 }
975 AlterTableOperation::SetTblProperties { table_properties } => {
976 write!(
977 f,
978 "SET TBLPROPERTIES({})",
979 display_comma_separated(table_properties)
980 )
981 }
982 AlterTableOperation::SetLogged => {
983 write!(f, "SET LOGGED")
984 }
985 AlterTableOperation::SetUnlogged => {
986 write!(f, "SET UNLOGGED")
987 }
988 AlterTableOperation::FreezePartition {
989 partition,
990 with_name,
991 } => {
992 write!(f, "FREEZE {partition}")?;
993 if let Some(name) = with_name {
994 write!(f, " WITH NAME {name}")?;
995 }
996 Ok(())
997 }
998 AlterTableOperation::UnfreezePartition {
999 partition,
1000 with_name,
1001 } => {
1002 write!(f, "UNFREEZE {partition}")?;
1003 if let Some(name) = with_name {
1004 write!(f, " WITH NAME {name}")?;
1005 }
1006 Ok(())
1007 }
1008 AlterTableOperation::ClusterBy { exprs } => {
1009 write!(f, "CLUSTER BY ({})", display_comma_separated(exprs))?;
1010 Ok(())
1011 }
1012 AlterTableOperation::DropClusteringKey => {
1013 write!(f, "DROP CLUSTERING KEY")?;
1014 Ok(())
1015 }
1016 AlterTableOperation::AlterSortKey { columns } => {
1017 write!(f, "ALTER SORTKEY({})", display_comma_separated(columns))?;
1018 Ok(())
1019 }
1020 AlterTableOperation::SuspendRecluster => {
1021 write!(f, "SUSPEND RECLUSTER")?;
1022 Ok(())
1023 }
1024 AlterTableOperation::ResumeRecluster => {
1025 write!(f, "RESUME RECLUSTER")?;
1026 Ok(())
1027 }
1028 AlterTableOperation::Refresh { subpath } => {
1029 write!(f, "REFRESH")?;
1030 if let Some(path) = subpath {
1031 write!(f, " '{path}'")?;
1032 }
1033 Ok(())
1034 }
1035 AlterTableOperation::Suspend => {
1036 write!(f, "SUSPEND")
1037 }
1038 AlterTableOperation::Resume => {
1039 write!(f, "RESUME")
1040 }
1041 AlterTableOperation::AutoIncrement { equals, value } => {
1042 write!(
1043 f,
1044 "AUTO_INCREMENT {}{}",
1045 if *equals { "= " } else { "" },
1046 value
1047 )
1048 }
1049 AlterTableOperation::Lock { equals, lock } => {
1050 write!(f, "LOCK {}{}", if *equals { "= " } else { "" }, lock)
1051 }
1052 AlterTableOperation::ReplicaIdentity { identity } => {
1053 write!(f, "REPLICA IDENTITY {identity}")
1054 }
1055 AlterTableOperation::ValidateConstraint { name } => {
1056 write!(f, "VALIDATE CONSTRAINT {name}")
1057 }
1058 AlterTableOperation::SetOptionsParens { options } => {
1059 write!(f, "SET ({})", display_comma_separated(options))
1060 }
1061 }
1062 }
1063}
1064
1065impl fmt::Display for AlterIndexOperation {
1066 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1067 match self {
1068 AlterIndexOperation::RenameIndex { index_name } => {
1069 write!(f, "RENAME TO {index_name}")
1070 }
1071 }
1072 }
1073}
1074
1075#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1077#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1078#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1079pub struct AlterType {
1080 pub name: ObjectName,
1082 pub operation: AlterTypeOperation,
1084}
1085
1086#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1088#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1089#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1090pub enum AlterTypeOperation {
1091 Rename(AlterTypeRename),
1093 AddValue(AlterTypeAddValue),
1095 RenameValue(AlterTypeRenameValue),
1097}
1098
1099#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1101#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1102#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1103pub struct AlterTypeRename {
1104 pub new_name: Ident,
1106}
1107
1108#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1110#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1111#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1112pub struct AlterTypeAddValue {
1113 pub if_not_exists: bool,
1115 pub value: Ident,
1117 pub position: Option<AlterTypeAddValuePosition>,
1119}
1120
1121#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1123#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1124#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1125pub enum AlterTypeAddValuePosition {
1126 Before(Ident),
1128 After(Ident),
1130}
1131
1132#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1134#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1135#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1136pub struct AlterTypeRenameValue {
1137 pub from: Ident,
1139 pub to: Ident,
1141}
1142
1143impl fmt::Display for AlterTypeOperation {
1144 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1145 match self {
1146 Self::Rename(AlterTypeRename { new_name }) => {
1147 write!(f, "RENAME TO {new_name}")
1148 }
1149 Self::AddValue(AlterTypeAddValue {
1150 if_not_exists,
1151 value,
1152 position,
1153 }) => {
1154 write!(f, "ADD VALUE")?;
1155 if *if_not_exists {
1156 write!(f, " IF NOT EXISTS")?;
1157 }
1158 write!(f, " {value}")?;
1159 match position {
1160 Some(AlterTypeAddValuePosition::Before(neighbor_value)) => {
1161 write!(f, " BEFORE {neighbor_value}")?;
1162 }
1163 Some(AlterTypeAddValuePosition::After(neighbor_value)) => {
1164 write!(f, " AFTER {neighbor_value}")?;
1165 }
1166 None => {}
1167 };
1168 Ok(())
1169 }
1170 Self::RenameValue(AlterTypeRenameValue { from, to }) => {
1171 write!(f, "RENAME VALUE {from} TO {to}")
1172 }
1173 }
1174 }
1175}
1176
1177#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1180#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1181#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1182pub struct AlterOperator {
1183 pub name: ObjectName,
1185 pub left_type: Option<DataType>,
1187 pub right_type: DataType,
1189 pub operation: AlterOperatorOperation,
1191}
1192
1193#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1195#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1196#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1197pub enum AlterOperatorOperation {
1198 OwnerTo(Owner),
1200 SetSchema {
1203 schema_name: ObjectName,
1205 },
1206 Set {
1208 options: Vec<OperatorOption>,
1210 },
1211}
1212
1213#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1215#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1216#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1217pub enum OperatorOption {
1218 Restrict(Option<ObjectName>),
1220 Join(Option<ObjectName>),
1222 Commutator(ObjectName),
1224 Negator(ObjectName),
1226 Hashes,
1228 Merges,
1230}
1231
1232impl fmt::Display for AlterOperator {
1233 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1234 write!(f, "ALTER OPERATOR {} (", self.name)?;
1235 if let Some(left_type) = &self.left_type {
1236 write!(f, "{}", left_type)?;
1237 } else {
1238 write!(f, "NONE")?;
1239 }
1240 write!(f, ", {}) {}", self.right_type, self.operation)
1241 }
1242}
1243
1244impl fmt::Display for AlterOperatorOperation {
1245 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1246 match self {
1247 Self::OwnerTo(owner) => write!(f, "OWNER TO {}", owner),
1248 Self::SetSchema { schema_name } => write!(f, "SET SCHEMA {}", schema_name),
1249 Self::Set { options } => {
1250 write!(f, "SET (")?;
1251 for (i, option) in options.iter().enumerate() {
1252 if i > 0 {
1253 write!(f, ", ")?;
1254 }
1255 write!(f, "{}", option)?;
1256 }
1257 write!(f, ")")
1258 }
1259 }
1260 }
1261}
1262
1263impl fmt::Display for OperatorOption {
1264 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1265 match self {
1266 Self::Restrict(Some(proc_name)) => write!(f, "RESTRICT = {}", proc_name),
1267 Self::Restrict(None) => write!(f, "RESTRICT = NONE"),
1268 Self::Join(Some(proc_name)) => write!(f, "JOIN = {}", proc_name),
1269 Self::Join(None) => write!(f, "JOIN = NONE"),
1270 Self::Commutator(op_name) => write!(f, "COMMUTATOR = {}", op_name),
1271 Self::Negator(op_name) => write!(f, "NEGATOR = {}", op_name),
1272 Self::Hashes => write!(f, "HASHES"),
1273 Self::Merges => write!(f, "MERGES"),
1274 }
1275 }
1276}
1277
1278#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1280#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1281#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1282pub enum AlterColumnOperation {
1283 SetNotNull,
1285 DropNotNull,
1287 SetDefault {
1290 value: Expr,
1292 },
1293 DropDefault,
1295 SetDataType {
1297 data_type: DataType,
1299 using: Option<Expr>,
1301 had_set: bool,
1303 },
1304
1305 AddGenerated {
1309 generated_as: Option<GeneratedAs>,
1311 sequence_options: Option<Vec<SequenceOptions>>,
1313 },
1314}
1315
1316impl fmt::Display for AlterColumnOperation {
1317 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1318 match self {
1319 AlterColumnOperation::SetNotNull => write!(f, "SET NOT NULL",),
1320 AlterColumnOperation::DropNotNull => write!(f, "DROP NOT NULL",),
1321 AlterColumnOperation::SetDefault { value } => {
1322 write!(f, "SET DEFAULT {value}")
1323 }
1324 AlterColumnOperation::DropDefault => {
1325 write!(f, "DROP DEFAULT")
1326 }
1327 AlterColumnOperation::SetDataType {
1328 data_type,
1329 using,
1330 had_set,
1331 } => {
1332 if *had_set {
1333 write!(f, "SET DATA ")?;
1334 }
1335 write!(f, "TYPE {data_type}")?;
1336 if let Some(expr) = using {
1337 write!(f, " USING {expr}")?;
1338 }
1339 Ok(())
1340 }
1341 AlterColumnOperation::AddGenerated {
1342 generated_as,
1343 sequence_options,
1344 } => {
1345 let generated_as = match generated_as {
1346 Some(GeneratedAs::Always) => " ALWAYS",
1347 Some(GeneratedAs::ByDefault) => " BY DEFAULT",
1348 _ => "",
1349 };
1350
1351 write!(f, "ADD GENERATED{generated_as} AS IDENTITY",)?;
1352 if let Some(options) = sequence_options {
1353 write!(f, " (")?;
1354
1355 for sequence_option in options {
1356 write!(f, "{sequence_option}")?;
1357 }
1358
1359 write!(f, " )")?;
1360 }
1361 Ok(())
1362 }
1363 }
1364 }
1365}
1366
1367#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1375#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1376#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1377pub enum KeyOrIndexDisplay {
1378 None,
1380 Key,
1382 Index,
1384}
1385
1386impl KeyOrIndexDisplay {
1387 pub fn is_none(self) -> bool {
1389 matches!(self, Self::None)
1390 }
1391}
1392
1393impl fmt::Display for KeyOrIndexDisplay {
1394 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1395 let left_space = matches!(f.align(), Some(fmt::Alignment::Right));
1396
1397 if left_space && !self.is_none() {
1398 f.write_char(' ')?
1399 }
1400
1401 match self {
1402 KeyOrIndexDisplay::None => {
1403 write!(f, "")
1404 }
1405 KeyOrIndexDisplay::Key => {
1406 write!(f, "KEY")
1407 }
1408 KeyOrIndexDisplay::Index => {
1409 write!(f, "INDEX")
1410 }
1411 }
1412 }
1413}
1414
1415#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1424#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1425#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1426pub enum IndexType {
1427 BTree,
1429 Hash,
1431 GIN,
1433 GiST,
1435 SPGiST,
1437 BRIN,
1439 Bloom,
1441 Custom(Ident),
1444}
1445
1446impl fmt::Display for IndexType {
1447 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1448 match self {
1449 Self::BTree => write!(f, "BTREE"),
1450 Self::Hash => write!(f, "HASH"),
1451 Self::GIN => write!(f, "GIN"),
1452 Self::GiST => write!(f, "GIST"),
1453 Self::SPGiST => write!(f, "SPGIST"),
1454 Self::BRIN => write!(f, "BRIN"),
1455 Self::Bloom => write!(f, "BLOOM"),
1456 Self::Custom(name) => write!(f, "{name}"),
1457 }
1458 }
1459}
1460
1461#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1467#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1468#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1469pub enum IndexOption {
1470 Using(IndexType),
1474 Comment(String),
1476}
1477
1478impl fmt::Display for IndexOption {
1479 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1480 match self {
1481 Self::Using(index_type) => write!(f, "USING {index_type}"),
1482 Self::Comment(s) => write!(f, "COMMENT '{s}'"),
1483 }
1484 }
1485}
1486
1487#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1491#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1492#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1493pub enum NullsDistinctOption {
1494 None,
1496 Distinct,
1498 NotDistinct,
1500}
1501
1502impl fmt::Display for NullsDistinctOption {
1503 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1504 match self {
1505 Self::None => Ok(()),
1506 Self::Distinct => write!(f, " NULLS DISTINCT"),
1507 Self::NotDistinct => write!(f, " NULLS NOT DISTINCT"),
1508 }
1509 }
1510}
1511
1512#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1513#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1514#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1515pub struct ProcedureParam {
1517 pub name: Ident,
1519 pub data_type: DataType,
1521 pub mode: Option<ArgMode>,
1523 pub default: Option<Expr>,
1525}
1526
1527impl fmt::Display for ProcedureParam {
1528 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1529 if let Some(mode) = &self.mode {
1530 if let Some(default) = &self.default {
1531 write!(f, "{mode} {} {} = {}", self.name, self.data_type, default)
1532 } else {
1533 write!(f, "{mode} {} {}", self.name, self.data_type)
1534 }
1535 } else if let Some(default) = &self.default {
1536 write!(f, "{} {} = {}", self.name, self.data_type, default)
1537 } else {
1538 write!(f, "{} {}", self.name, self.data_type)
1539 }
1540 }
1541}
1542
1543#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1545#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1546#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1547pub struct ColumnDef {
1548 pub name: Ident,
1550 pub data_type: DataType,
1552 pub options: Vec<ColumnOptionDef>,
1554}
1555
1556impl fmt::Display for ColumnDef {
1557 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1558 if self.data_type == DataType::Unspecified {
1559 write!(f, "{}", self.name)?;
1560 } else {
1561 write!(f, "{} {}", self.name, self.data_type)?;
1562 }
1563 for option in &self.options {
1564 write!(f, " {option}")?;
1565 }
1566 Ok(())
1567 }
1568}
1569
1570#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1587#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1588#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1589pub struct ViewColumnDef {
1590 pub name: Ident,
1592 pub data_type: Option<DataType>,
1594 pub options: Option<ColumnOptions>,
1596}
1597
1598#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1599#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1600#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1601pub enum ColumnOptions {
1603 CommaSeparated(Vec<ColumnOption>),
1605 SpaceSeparated(Vec<ColumnOption>),
1607}
1608
1609impl ColumnOptions {
1610 pub fn as_slice(&self) -> &[ColumnOption] {
1612 match self {
1613 ColumnOptions::CommaSeparated(options) => options.as_slice(),
1614 ColumnOptions::SpaceSeparated(options) => options.as_slice(),
1615 }
1616 }
1617}
1618
1619impl fmt::Display for ViewColumnDef {
1620 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1621 write!(f, "{}", self.name)?;
1622 if let Some(data_type) = self.data_type.as_ref() {
1623 write!(f, " {data_type}")?;
1624 }
1625 if let Some(options) = self.options.as_ref() {
1626 match options {
1627 ColumnOptions::CommaSeparated(column_options) => {
1628 write!(f, " {}", display_comma_separated(column_options.as_slice()))?;
1629 }
1630 ColumnOptions::SpaceSeparated(column_options) => {
1631 write!(f, " {}", display_separated(column_options.as_slice(), " "))?
1632 }
1633 }
1634 }
1635 Ok(())
1636 }
1637}
1638
1639#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1656#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1657#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1658pub struct ColumnOptionDef {
1659 pub name: Option<Ident>,
1661 pub option: ColumnOption,
1663}
1664
1665impl fmt::Display for ColumnOptionDef {
1666 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1667 write!(f, "{}{}", display_constraint_name(&self.name), self.option)
1668 }
1669}
1670
1671#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1679#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1680#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1681pub enum IdentityPropertyKind {
1682 Autoincrement(IdentityProperty),
1690 Identity(IdentityProperty),
1703}
1704
1705impl fmt::Display for IdentityPropertyKind {
1706 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1707 let (command, property) = match self {
1708 IdentityPropertyKind::Identity(property) => ("IDENTITY", property),
1709 IdentityPropertyKind::Autoincrement(property) => ("AUTOINCREMENT", property),
1710 };
1711 write!(f, "{command}")?;
1712 if let Some(parameters) = &property.parameters {
1713 write!(f, "{parameters}")?;
1714 }
1715 if let Some(order) = &property.order {
1716 write!(f, "{order}")?;
1717 }
1718 Ok(())
1719 }
1720}
1721
1722#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1724#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1725#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1726pub struct IdentityProperty {
1727 pub parameters: Option<IdentityPropertyFormatKind>,
1729 pub order: Option<IdentityPropertyOrder>,
1731}
1732
1733#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1748#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1749#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1750pub enum IdentityPropertyFormatKind {
1751 FunctionCall(IdentityParameters),
1759 StartAndIncrement(IdentityParameters),
1766}
1767
1768impl fmt::Display for IdentityPropertyFormatKind {
1769 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1770 match self {
1771 IdentityPropertyFormatKind::FunctionCall(parameters) => {
1772 write!(f, "({}, {})", parameters.seed, parameters.increment)
1773 }
1774 IdentityPropertyFormatKind::StartAndIncrement(parameters) => {
1775 write!(
1776 f,
1777 " START {} INCREMENT {}",
1778 parameters.seed, parameters.increment
1779 )
1780 }
1781 }
1782 }
1783}
1784#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1786#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1787#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1788pub struct IdentityParameters {
1789 pub seed: Expr,
1791 pub increment: Expr,
1793}
1794
1795#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1802#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1803#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1804pub enum IdentityPropertyOrder {
1805 Order,
1807 NoOrder,
1809}
1810
1811impl fmt::Display for IdentityPropertyOrder {
1812 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1813 match self {
1814 IdentityPropertyOrder::Order => write!(f, " ORDER"),
1815 IdentityPropertyOrder::NoOrder => write!(f, " NOORDER"),
1816 }
1817 }
1818}
1819
1820#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1828#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1829#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1830pub enum ColumnPolicy {
1831 MaskingPolicy(ColumnPolicyProperty),
1833 ProjectionPolicy(ColumnPolicyProperty),
1835}
1836
1837impl fmt::Display for ColumnPolicy {
1838 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1839 let (command, property) = match self {
1840 ColumnPolicy::MaskingPolicy(property) => ("MASKING POLICY", property),
1841 ColumnPolicy::ProjectionPolicy(property) => ("PROJECTION POLICY", property),
1842 };
1843 if property.with {
1844 write!(f, "WITH ")?;
1845 }
1846 write!(f, "{command} {}", property.policy_name)?;
1847 if let Some(using_columns) = &property.using_columns {
1848 write!(f, " USING ({})", display_comma_separated(using_columns))?;
1849 }
1850 Ok(())
1851 }
1852}
1853
1854#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1855#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1856#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1857pub struct ColumnPolicyProperty {
1859 pub with: bool,
1866 pub policy_name: ObjectName,
1868 pub using_columns: Option<Vec<Ident>>,
1870}
1871
1872#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1879#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1880#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1881pub struct TagsColumnOption {
1882 pub with: bool,
1889 pub tags: Vec<Tag>,
1891}
1892
1893impl fmt::Display for TagsColumnOption {
1894 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1895 if self.with {
1896 write!(f, "WITH ")?;
1897 }
1898 write!(f, "TAG ({})", display_comma_separated(&self.tags))?;
1899 Ok(())
1900 }
1901}
1902
1903#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1906#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1907#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1908pub enum ColumnOption {
1909 Null,
1911 NotNull,
1913 Default(Expr),
1915
1916 Materialized(Expr),
1921 Ephemeral(Option<Expr>),
1925 Alias(Expr),
1929
1930 PrimaryKey(PrimaryKeyConstraint),
1932 Unique(UniqueConstraint),
1934 ForeignKey(ForeignKeyConstraint),
1942 Check(CheckConstraint),
1944 DialectSpecific(Vec<Token>),
1948 CharacterSet(ObjectName),
1950 Collation(ObjectName),
1952 Comment(String),
1954 OnUpdate(Expr),
1956 Generated {
1959 generated_as: GeneratedAs,
1961 sequence_options: Option<Vec<SequenceOptions>>,
1963 generation_expr: Option<Expr>,
1965 generation_expr_mode: Option<GeneratedExpressionMode>,
1967 generated_keyword: bool,
1969 },
1970 Options(Vec<SqlOption>),
1978 Identity(IdentityPropertyKind),
1986 OnConflict(Keyword),
1989 Policy(ColumnPolicy),
1997 Tags(TagsColumnOption),
2004 Srid(Box<Expr>),
2011 Invisible,
2018}
2019
2020impl From<UniqueConstraint> for ColumnOption {
2021 fn from(c: UniqueConstraint) -> Self {
2022 ColumnOption::Unique(c)
2023 }
2024}
2025
2026impl From<PrimaryKeyConstraint> for ColumnOption {
2027 fn from(c: PrimaryKeyConstraint) -> Self {
2028 ColumnOption::PrimaryKey(c)
2029 }
2030}
2031
2032impl From<CheckConstraint> for ColumnOption {
2033 fn from(c: CheckConstraint) -> Self {
2034 ColumnOption::Check(c)
2035 }
2036}
2037impl From<ForeignKeyConstraint> for ColumnOption {
2038 fn from(fk: ForeignKeyConstraint) -> Self {
2039 ColumnOption::ForeignKey(fk)
2040 }
2041}
2042
2043impl fmt::Display for ColumnOption {
2044 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2045 use ColumnOption::*;
2046 match self {
2047 Null => write!(f, "NULL"),
2048 NotNull => write!(f, "NOT NULL"),
2049 Default(expr) => write!(f, "DEFAULT {expr}"),
2050 Materialized(expr) => write!(f, "MATERIALIZED {expr}"),
2051 Ephemeral(expr) => {
2052 if let Some(e) = expr {
2053 write!(f, "EPHEMERAL {e}")
2054 } else {
2055 write!(f, "EPHEMERAL")
2056 }
2057 }
2058 Alias(expr) => write!(f, "ALIAS {expr}"),
2059 PrimaryKey(constraint) => {
2060 write!(f, "PRIMARY KEY")?;
2061 if let Some(characteristics) = &constraint.characteristics {
2062 write!(f, " {characteristics}")?;
2063 }
2064 Ok(())
2065 }
2066 Unique(constraint) => {
2067 write!(f, "UNIQUE{:>}", constraint.index_type_display)?;
2068 if let Some(characteristics) = &constraint.characteristics {
2069 write!(f, " {characteristics}")?;
2070 }
2071 Ok(())
2072 }
2073 ForeignKey(constraint) => {
2074 write!(f, "REFERENCES {}", constraint.foreign_table)?;
2075 if !constraint.referred_columns.is_empty() {
2076 write!(
2077 f,
2078 " ({})",
2079 display_comma_separated(&constraint.referred_columns)
2080 )?;
2081 }
2082 if let Some(match_kind) = &constraint.match_kind {
2083 write!(f, " {match_kind}")?;
2084 }
2085 if let Some(action) = &constraint.on_delete {
2086 write!(f, " ON DELETE {action}")?;
2087 }
2088 if let Some(action) = &constraint.on_update {
2089 write!(f, " ON UPDATE {action}")?;
2090 }
2091 if let Some(characteristics) = &constraint.characteristics {
2092 write!(f, " {characteristics}")?;
2093 }
2094 Ok(())
2095 }
2096 Check(constraint) => write!(f, "{constraint}"),
2097 DialectSpecific(val) => write!(f, "{}", display_separated(val, " ")),
2098 CharacterSet(n) => write!(f, "CHARACTER SET {n}"),
2099 Collation(n) => write!(f, "COLLATE {n}"),
2100 Comment(v) => write!(f, "COMMENT '{}'", escape_single_quote_string(v)),
2101 OnUpdate(expr) => write!(f, "ON UPDATE {expr}"),
2102 Generated {
2103 generated_as,
2104 sequence_options,
2105 generation_expr,
2106 generation_expr_mode,
2107 generated_keyword,
2108 } => {
2109 if let Some(expr) = generation_expr {
2110 let modifier = match generation_expr_mode {
2111 None => "",
2112 Some(GeneratedExpressionMode::Virtual) => " VIRTUAL",
2113 Some(GeneratedExpressionMode::Stored) => " STORED",
2114 };
2115 if *generated_keyword {
2116 write!(f, "GENERATED ALWAYS AS ({expr}){modifier}")?;
2117 } else {
2118 write!(f, "AS ({expr}){modifier}")?;
2119 }
2120 Ok(())
2121 } else {
2122 let when = match generated_as {
2124 GeneratedAs::Always => "ALWAYS",
2125 GeneratedAs::ByDefault => "BY DEFAULT",
2126 GeneratedAs::ExpStored => "",
2128 };
2129 write!(f, "GENERATED {when} AS IDENTITY")?;
2130 if let Some(so) = sequence_options {
2131 if !so.is_empty() {
2132 write!(f, " (")?;
2133 }
2134 for sequence_option in so {
2135 write!(f, "{sequence_option}")?;
2136 }
2137 if !so.is_empty() {
2138 write!(f, " )")?;
2139 }
2140 }
2141 Ok(())
2142 }
2143 }
2144 Options(options) => {
2145 write!(f, "OPTIONS({})", display_comma_separated(options))
2146 }
2147 Identity(parameters) => {
2148 write!(f, "{parameters}")
2149 }
2150 OnConflict(keyword) => {
2151 write!(f, "ON CONFLICT {keyword:?}")?;
2152 Ok(())
2153 }
2154 Policy(parameters) => {
2155 write!(f, "{parameters}")
2156 }
2157 Tags(tags) => {
2158 write!(f, "{tags}")
2159 }
2160 Srid(srid) => {
2161 write!(f, "SRID {srid}")
2162 }
2163 Invisible => {
2164 write!(f, "INVISIBLE")
2165 }
2166 }
2167 }
2168}
2169
2170#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2173#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2174#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2175pub enum GeneratedAs {
2176 Always,
2178 ByDefault,
2180 ExpStored,
2182}
2183
2184#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2187#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2188#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2189pub enum GeneratedExpressionMode {
2190 Virtual,
2192 Stored,
2194}
2195
2196#[must_use]
2197pub(crate) fn display_constraint_name(name: &'_ Option<Ident>) -> impl fmt::Display + '_ {
2198 struct ConstraintName<'a>(&'a Option<Ident>);
2199 impl fmt::Display for ConstraintName<'_> {
2200 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2201 if let Some(name) = self.0 {
2202 write!(f, "CONSTRAINT {name} ")?;
2203 }
2204 Ok(())
2205 }
2206 }
2207 ConstraintName(name)
2208}
2209
2210#[must_use]
2214pub(crate) fn display_option<'a, T: fmt::Display>(
2215 prefix: &'a str,
2216 postfix: &'a str,
2217 option: &'a Option<T>,
2218) -> impl fmt::Display + 'a {
2219 struct OptionDisplay<'a, T>(&'a str, &'a str, &'a Option<T>);
2220 impl<T: fmt::Display> fmt::Display for OptionDisplay<'_, T> {
2221 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2222 if let Some(inner) = self.2 {
2223 let (prefix, postfix) = (self.0, self.1);
2224 write!(f, "{prefix}{inner}{postfix}")?;
2225 }
2226 Ok(())
2227 }
2228 }
2229 OptionDisplay(prefix, postfix, option)
2230}
2231
2232#[must_use]
2236pub(crate) fn display_option_spaced<T: fmt::Display>(option: &Option<T>) -> impl fmt::Display + '_ {
2237 display_option(" ", "", option)
2238}
2239
2240#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Default, Eq, Ord, Hash)]
2244#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2245#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2246pub struct ConstraintCharacteristics {
2247 pub deferrable: Option<bool>,
2249 pub initially: Option<DeferrableInitial>,
2251 pub enforced: Option<bool>,
2253}
2254
2255#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2257#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2258#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2259pub enum DeferrableInitial {
2260 Immediate,
2262 Deferred,
2264}
2265
2266impl ConstraintCharacteristics {
2267 fn deferrable_text(&self) -> Option<&'static str> {
2268 self.deferrable.map(|deferrable| {
2269 if deferrable {
2270 "DEFERRABLE"
2271 } else {
2272 "NOT DEFERRABLE"
2273 }
2274 })
2275 }
2276
2277 fn initially_immediate_text(&self) -> Option<&'static str> {
2278 self.initially
2279 .map(|initially_immediate| match initially_immediate {
2280 DeferrableInitial::Immediate => "INITIALLY IMMEDIATE",
2281 DeferrableInitial::Deferred => "INITIALLY DEFERRED",
2282 })
2283 }
2284
2285 fn enforced_text(&self) -> Option<&'static str> {
2286 self.enforced.map(
2287 |enforced| {
2288 if enforced {
2289 "ENFORCED"
2290 } else {
2291 "NOT ENFORCED"
2292 }
2293 },
2294 )
2295 }
2296}
2297
2298impl fmt::Display for ConstraintCharacteristics {
2299 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2300 let deferrable = self.deferrable_text();
2301 let initially_immediate = self.initially_immediate_text();
2302 let enforced = self.enforced_text();
2303
2304 match (deferrable, initially_immediate, enforced) {
2305 (None, None, None) => Ok(()),
2306 (None, None, Some(enforced)) => write!(f, "{enforced}"),
2307 (None, Some(initial), None) => write!(f, "{initial}"),
2308 (None, Some(initial), Some(enforced)) => write!(f, "{initial} {enforced}"),
2309 (Some(deferrable), None, None) => write!(f, "{deferrable}"),
2310 (Some(deferrable), None, Some(enforced)) => write!(f, "{deferrable} {enforced}"),
2311 (Some(deferrable), Some(initial), None) => write!(f, "{deferrable} {initial}"),
2312 (Some(deferrable), Some(initial), Some(enforced)) => {
2313 write!(f, "{deferrable} {initial} {enforced}")
2314 }
2315 }
2316 }
2317}
2318
2319#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2324#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2325#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2326pub enum ReferentialAction {
2327 Restrict,
2329 Cascade,
2331 SetNull,
2333 NoAction,
2335 SetDefault,
2337}
2338
2339impl fmt::Display for ReferentialAction {
2340 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2341 f.write_str(match self {
2342 ReferentialAction::Restrict => "RESTRICT",
2343 ReferentialAction::Cascade => "CASCADE",
2344 ReferentialAction::SetNull => "SET NULL",
2345 ReferentialAction::NoAction => "NO ACTION",
2346 ReferentialAction::SetDefault => "SET DEFAULT",
2347 })
2348 }
2349}
2350
2351#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2355#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2356#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2357pub enum DropBehavior {
2358 Restrict,
2360 Cascade,
2362}
2363
2364impl fmt::Display for DropBehavior {
2365 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2366 f.write_str(match self {
2367 DropBehavior::Restrict => "RESTRICT",
2368 DropBehavior::Cascade => "CASCADE",
2369 })
2370 }
2371}
2372
2373#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2375#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2376#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2377pub enum UserDefinedTypeRepresentation {
2378 Composite {
2380 attributes: Vec<UserDefinedTypeCompositeAttributeDef>,
2382 },
2383 Enum {
2388 labels: Vec<Ident>,
2390 },
2391 Range {
2395 options: Vec<UserDefinedTypeRangeOption>,
2397 },
2398 SqlDefinition {
2404 options: Vec<UserDefinedTypeSqlDefinitionOption>,
2406 },
2407}
2408
2409impl fmt::Display for UserDefinedTypeRepresentation {
2410 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2411 match self {
2412 Self::Composite { attributes } => {
2413 write!(f, "AS ({})", display_comma_separated(attributes))
2414 }
2415 Self::Enum { labels } => {
2416 write!(f, "AS ENUM ({})", display_comma_separated(labels))
2417 }
2418 Self::Range { options } => {
2419 write!(f, "AS RANGE ({})", display_comma_separated(options))
2420 }
2421 Self::SqlDefinition { options } => {
2422 write!(f, "({})", display_comma_separated(options))
2423 }
2424 }
2425 }
2426}
2427
2428#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2430#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2431#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2432pub struct UserDefinedTypeCompositeAttributeDef {
2433 pub name: Ident,
2435 pub data_type: DataType,
2437 pub collation: Option<ObjectName>,
2439}
2440
2441impl fmt::Display for UserDefinedTypeCompositeAttributeDef {
2442 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2443 write!(f, "{} {}", self.name, self.data_type)?;
2444 if let Some(collation) = &self.collation {
2445 write!(f, " COLLATE {collation}")?;
2446 }
2447 Ok(())
2448 }
2449}
2450
2451#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2474#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2475#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2476pub enum UserDefinedTypeInternalLength {
2477 Fixed(u64),
2479 Variable,
2481}
2482
2483impl fmt::Display for UserDefinedTypeInternalLength {
2484 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2485 match self {
2486 UserDefinedTypeInternalLength::Fixed(n) => write!(f, "{}", n),
2487 UserDefinedTypeInternalLength::Variable => write!(f, "VARIABLE"),
2488 }
2489 }
2490}
2491
2492#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2511#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2512#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2513pub enum Alignment {
2514 Char,
2516 Int2,
2518 Int4,
2520 Double,
2522}
2523
2524impl fmt::Display for Alignment {
2525 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2526 match self {
2527 Alignment::Char => write!(f, "char"),
2528 Alignment::Int2 => write!(f, "int2"),
2529 Alignment::Int4 => write!(f, "int4"),
2530 Alignment::Double => write!(f, "double"),
2531 }
2532 }
2533}
2534
2535#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2555#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2556#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2557pub enum UserDefinedTypeStorage {
2558 Plain,
2560 External,
2562 Extended,
2564 Main,
2566}
2567
2568impl fmt::Display for UserDefinedTypeStorage {
2569 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2570 match self {
2571 UserDefinedTypeStorage::Plain => write!(f, "plain"),
2572 UserDefinedTypeStorage::External => write!(f, "external"),
2573 UserDefinedTypeStorage::Extended => write!(f, "extended"),
2574 UserDefinedTypeStorage::Main => write!(f, "main"),
2575 }
2576 }
2577}
2578
2579#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2597#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2598#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2599pub enum UserDefinedTypeRangeOption {
2600 Subtype(DataType),
2602 SubtypeOpClass(ObjectName),
2604 Collation(ObjectName),
2606 Canonical(ObjectName),
2608 SubtypeDiff(ObjectName),
2610 MultirangeTypeName(ObjectName),
2612}
2613
2614impl fmt::Display for UserDefinedTypeRangeOption {
2615 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2616 match self {
2617 UserDefinedTypeRangeOption::Subtype(dt) => write!(f, "SUBTYPE = {}", dt),
2618 UserDefinedTypeRangeOption::SubtypeOpClass(name) => {
2619 write!(f, "SUBTYPE_OPCLASS = {}", name)
2620 }
2621 UserDefinedTypeRangeOption::Collation(name) => write!(f, "COLLATION = {}", name),
2622 UserDefinedTypeRangeOption::Canonical(name) => write!(f, "CANONICAL = {}", name),
2623 UserDefinedTypeRangeOption::SubtypeDiff(name) => write!(f, "SUBTYPE_DIFF = {}", name),
2624 UserDefinedTypeRangeOption::MultirangeTypeName(name) => {
2625 write!(f, "MULTIRANGE_TYPE_NAME = {}", name)
2626 }
2627 }
2628 }
2629}
2630
2631#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2652#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2653#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2654pub enum UserDefinedTypeSqlDefinitionOption {
2655 Input(ObjectName),
2657 Output(ObjectName),
2659 Receive(ObjectName),
2661 Send(ObjectName),
2663 TypmodIn(ObjectName),
2665 TypmodOut(ObjectName),
2667 Analyze(ObjectName),
2669 Subscript(ObjectName),
2671 InternalLength(UserDefinedTypeInternalLength),
2673 PassedByValue,
2675 Alignment(Alignment),
2677 Storage(UserDefinedTypeStorage),
2679 Like(ObjectName),
2681 Category(char),
2683 Preferred(bool),
2685 Default(Expr),
2687 Element(DataType),
2689 Delimiter(String),
2691 Collatable(bool),
2693}
2694
2695impl fmt::Display for UserDefinedTypeSqlDefinitionOption {
2696 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2697 match self {
2698 UserDefinedTypeSqlDefinitionOption::Input(name) => write!(f, "INPUT = {}", name),
2699 UserDefinedTypeSqlDefinitionOption::Output(name) => write!(f, "OUTPUT = {}", name),
2700 UserDefinedTypeSqlDefinitionOption::Receive(name) => write!(f, "RECEIVE = {}", name),
2701 UserDefinedTypeSqlDefinitionOption::Send(name) => write!(f, "SEND = {}", name),
2702 UserDefinedTypeSqlDefinitionOption::TypmodIn(name) => write!(f, "TYPMOD_IN = {}", name),
2703 UserDefinedTypeSqlDefinitionOption::TypmodOut(name) => {
2704 write!(f, "TYPMOD_OUT = {}", name)
2705 }
2706 UserDefinedTypeSqlDefinitionOption::Analyze(name) => write!(f, "ANALYZE = {}", name),
2707 UserDefinedTypeSqlDefinitionOption::Subscript(name) => {
2708 write!(f, "SUBSCRIPT = {}", name)
2709 }
2710 UserDefinedTypeSqlDefinitionOption::InternalLength(len) => {
2711 write!(f, "INTERNALLENGTH = {}", len)
2712 }
2713 UserDefinedTypeSqlDefinitionOption::PassedByValue => write!(f, "PASSEDBYVALUE"),
2714 UserDefinedTypeSqlDefinitionOption::Alignment(align) => {
2715 write!(f, "ALIGNMENT = {}", align)
2716 }
2717 UserDefinedTypeSqlDefinitionOption::Storage(storage) => {
2718 write!(f, "STORAGE = {}", storage)
2719 }
2720 UserDefinedTypeSqlDefinitionOption::Like(name) => write!(f, "LIKE = {}", name),
2721 UserDefinedTypeSqlDefinitionOption::Category(c) => write!(f, "CATEGORY = '{}'", c),
2722 UserDefinedTypeSqlDefinitionOption::Preferred(b) => write!(f, "PREFERRED = {}", b),
2723 UserDefinedTypeSqlDefinitionOption::Default(expr) => write!(f, "DEFAULT = {}", expr),
2724 UserDefinedTypeSqlDefinitionOption::Element(dt) => write!(f, "ELEMENT = {}", dt),
2725 UserDefinedTypeSqlDefinitionOption::Delimiter(s) => {
2726 write!(f, "DELIMITER = '{}'", escape_single_quote_string(s))
2727 }
2728 UserDefinedTypeSqlDefinitionOption::Collatable(b) => write!(f, "COLLATABLE = {}", b),
2729 }
2730 }
2731}
2732
2733#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2737#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2738#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2739pub enum Partition {
2740 Identifier(Ident),
2742 Expr(Expr),
2744 Part(Expr),
2747 Partitions(Vec<Expr>),
2749}
2750
2751impl fmt::Display for Partition {
2752 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2753 match self {
2754 Partition::Identifier(id) => write!(f, "PARTITION ID {id}"),
2755 Partition::Expr(expr) => write!(f, "PARTITION {expr}"),
2756 Partition::Part(expr) => write!(f, "PART {expr}"),
2757 Partition::Partitions(partitions) => {
2758 write!(f, "PARTITION ({})", display_comma_separated(partitions))
2759 }
2760 }
2761 }
2762}
2763
2764#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2767#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2768#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2769pub enum Deduplicate {
2770 All,
2772 ByExpression(Expr),
2774}
2775
2776impl fmt::Display for Deduplicate {
2777 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2778 match self {
2779 Deduplicate::All => write!(f, "DEDUPLICATE"),
2780 Deduplicate::ByExpression(expr) => write!(f, "DEDUPLICATE BY {expr}"),
2781 }
2782 }
2783}
2784
2785#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2790#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2791#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2792pub struct ClusteredBy {
2793 pub columns: Vec<Ident>,
2795 pub sorted_by: Option<Vec<OrderByExpr>>,
2797 pub num_buckets: Value,
2799}
2800
2801impl fmt::Display for ClusteredBy {
2802 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2803 write!(
2804 f,
2805 "CLUSTERED BY ({})",
2806 display_comma_separated(&self.columns)
2807 )?;
2808 if let Some(ref sorted_by) = self.sorted_by {
2809 write!(f, " SORTED BY ({})", display_comma_separated(sorted_by))?;
2810 }
2811 write!(f, " INTO {} BUCKETS", self.num_buckets)
2812 }
2813}
2814
2815#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2817#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2818#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2819pub struct CreateIndex {
2820 pub name: Option<ObjectName>,
2822 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2823 pub table_name: ObjectName,
2825 pub using: Option<IndexType>,
2828 pub columns: Vec<IndexColumn>,
2830 pub unique: bool,
2832 pub concurrently: bool,
2834 pub r#async: bool,
2838 pub if_not_exists: bool,
2840 pub include: Vec<Ident>,
2842 pub nulls_distinct: Option<bool>,
2844 pub with: Vec<Expr>,
2846 pub predicate: Option<Expr>,
2848 pub index_options: Vec<IndexOption>,
2850 pub alter_options: Vec<AlterTableOperation>,
2857}
2858
2859impl fmt::Display for CreateIndex {
2860 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2861 write!(
2862 f,
2863 "CREATE {unique}INDEX {concurrently}{async_}{if_not_exists}",
2864 unique = if self.unique { "UNIQUE " } else { "" },
2865 concurrently = if self.concurrently {
2866 "CONCURRENTLY "
2867 } else {
2868 ""
2869 },
2870 async_ = if self.r#async { "ASYNC " } else { "" },
2871 if_not_exists = if self.if_not_exists {
2872 "IF NOT EXISTS "
2873 } else {
2874 ""
2875 },
2876 )?;
2877 if let Some(value) = &self.name {
2878 write!(f, "{value} ")?;
2879 }
2880 write!(f, "ON {}", self.table_name)?;
2881 if let Some(value) = &self.using {
2882 write!(f, " USING {value} ")?;
2883 }
2884 write!(f, "({})", display_comma_separated(&self.columns))?;
2885 if !self.include.is_empty() {
2886 write!(f, " INCLUDE ({})", display_comma_separated(&self.include))?;
2887 }
2888 if let Some(value) = self.nulls_distinct {
2889 if value {
2890 write!(f, " NULLS DISTINCT")?;
2891 } else {
2892 write!(f, " NULLS NOT DISTINCT")?;
2893 }
2894 }
2895 if !self.with.is_empty() {
2896 write!(f, " WITH ({})", display_comma_separated(&self.with))?;
2897 }
2898 if let Some(predicate) = &self.predicate {
2899 write!(f, " WHERE {predicate}")?;
2900 }
2901 if !self.index_options.is_empty() {
2902 write!(f, " {}", display_separated(&self.index_options, " "))?;
2903 }
2904 if !self.alter_options.is_empty() {
2905 write!(f, " {}", display_separated(&self.alter_options, " "))?;
2906 }
2907 Ok(())
2908 }
2909}
2910
2911#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2913#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2914#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2915pub struct CreateTable {
2916 pub or_replace: bool,
2918 pub temporary: bool,
2920 pub unlogged: bool,
2922 pub external: bool,
2924 pub dynamic: bool,
2926 pub global: Option<bool>,
2928 pub if_not_exists: bool,
2930 pub transient: bool,
2932 pub volatile: bool,
2934 pub iceberg: bool,
2936 pub snapshot: bool,
2939 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2941 pub name: ObjectName,
2942 pub columns: Vec<ColumnDef>,
2944 pub constraints: Vec<TableConstraint>,
2946 pub hive_distribution: HiveDistributionStyle,
2948 pub hive_formats: Option<HiveFormat>,
2950 pub table_options: CreateTableOptions,
2952 pub file_format: Option<FileFormat>,
2954 pub location: Option<String>,
2956 pub query: Option<Box<Query>>,
2958 pub without_rowid: bool,
2960 pub like: Option<CreateTableLikeKind>,
2962 pub clone: Option<ObjectName>,
2964 pub version: Option<TableVersion>,
2966 pub comment: Option<CommentDef>,
2970 pub on_commit: Option<OnCommit>,
2973 pub on_cluster: Option<Ident>,
2976 pub primary_key: Option<Box<Expr>>,
2979 pub order_by: Option<OneOrManyWithParens<Expr>>,
2983 pub partition_by: Option<Box<Expr>>,
2986 pub cluster_by: Option<WrappedCollection<Vec<Expr>>>,
2991 pub clustered_by: Option<ClusteredBy>,
2994 pub inherits: Option<Vec<ObjectName>>,
2999 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3003 pub partition_of: Option<ObjectName>,
3004 pub for_values: Option<ForValues>,
3007 pub strict: bool,
3011 pub copy_grants: bool,
3014 pub enable_schema_evolution: Option<bool>,
3017 pub change_tracking: Option<bool>,
3020 pub data_retention_time_in_days: Option<u64>,
3023 pub max_data_extension_time_in_days: Option<u64>,
3026 pub default_ddl_collation: Option<String>,
3029 pub with_aggregation_policy: Option<ObjectName>,
3032 pub with_row_access_policy: Option<RowAccessPolicy>,
3035 pub with_storage_lifecycle_policy: Option<StorageLifecyclePolicy>,
3038 pub with_tags: Option<Vec<Tag>>,
3041 pub external_volume: Option<String>,
3044 pub with_connection: Option<ObjectName>,
3047 pub base_location: Option<String>,
3050 pub catalog: Option<String>,
3053 pub catalog_sync: Option<String>,
3056 pub storage_serialization_policy: Option<StorageSerializationPolicy>,
3059 pub target_lag: Option<String>,
3062 pub warehouse: Option<Ident>,
3065 pub refresh_mode: Option<RefreshModeKind>,
3068 pub initialize: Option<InitializeKind>,
3071 pub require_user: bool,
3074 pub diststyle: Option<DistStyle>,
3077 pub distkey: Option<Expr>,
3080 pub sortkey: Option<Vec<Expr>>,
3083 pub backup: Option<bool>,
3086 pub multiset: Option<bool>,
3091 pub fallback: Option<bool>,
3096 pub with_data: Option<WithData>,
3100}
3101
3102impl fmt::Display for CreateTable {
3103 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3104 write!(
3112 f,
3113 "CREATE {or_replace}{external}{global}{multiset}{temporary}{unlogged}{transient}{volatile}{dynamic}{iceberg}{snapshot}TABLE {if_not_exists}{name}",
3114 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3115 external = if self.external { "EXTERNAL " } else { "" },
3116 snapshot = if self.snapshot { "SNAPSHOT " } else { "" },
3117 global = self.global
3118 .map(|global| {
3119 if global {
3120 "GLOBAL "
3121 } else {
3122 "LOCAL "
3123 }
3124 })
3125 .unwrap_or(""),
3126 if_not_exists = if self.if_not_exists { "IF NOT EXISTS " } else { "" },
3127 multiset = self
3128 .multiset
3129 .map(|m| if m { "MULTISET " } else { "SET " })
3130 .unwrap_or(""),
3131 temporary = if self.temporary { "TEMPORARY " } else { "" },
3132 unlogged = if self.unlogged { "UNLOGGED " } else { "" },
3133 transient = if self.transient { "TRANSIENT " } else { "" },
3134 volatile = if self.volatile { "VOLATILE " } else { "" },
3135 iceberg = if self.iceberg { "ICEBERG " } else { "" },
3136 dynamic = if self.dynamic { "DYNAMIC " } else { "" },
3137 name = self.name,
3138 )?;
3139 if let Some(fallback) = self.fallback {
3140 write!(f, ", {}", if fallback { "FALLBACK" } else { "NO FALLBACK" })?;
3141 }
3142 if let Some(partition_of) = &self.partition_of {
3143 write!(f, " PARTITION OF {partition_of}")?;
3144 }
3145 if let Some(on_cluster) = &self.on_cluster {
3146 write!(f, " ON CLUSTER {on_cluster}")?;
3147 }
3148 if !self.columns.is_empty() || !self.constraints.is_empty() {
3149 f.write_str(" (")?;
3150 NewLine.fmt(f)?;
3151 Indent(DisplayCommaSeparated(&self.columns)).fmt(f)?;
3152 if !self.columns.is_empty() && !self.constraints.is_empty() {
3153 f.write_str(",")?;
3154 SpaceOrNewline.fmt(f)?;
3155 }
3156 Indent(DisplayCommaSeparated(&self.constraints)).fmt(f)?;
3157 NewLine.fmt(f)?;
3158 f.write_str(")")?;
3159 } else if self.query.is_none()
3160 && self.like.is_none()
3161 && self.clone.is_none()
3162 && self.partition_of.is_none()
3163 {
3164 f.write_str(" ()")?;
3166 } else if let Some(CreateTableLikeKind::Parenthesized(like_in_columns_list)) = &self.like {
3167 write!(f, " ({like_in_columns_list})")?;
3168 }
3169 if let Some(for_values) = &self.for_values {
3170 write!(f, " {for_values}")?;
3171 }
3172
3173 if let Some(comment) = &self.comment {
3176 write!(f, " COMMENT '{comment}'")?;
3177 }
3178
3179 if self.without_rowid {
3181 write!(f, " WITHOUT ROWID")?;
3182 }
3183
3184 if let Some(CreateTableLikeKind::Plain(like)) = &self.like {
3185 write!(f, " {like}")?;
3186 }
3187
3188 if let Some(c) = &self.clone {
3189 write!(f, " CLONE {c}")?;
3190 }
3191
3192 if let Some(version) = &self.version {
3193 write!(f, " {version}")?;
3194 }
3195
3196 match &self.hive_distribution {
3197 HiveDistributionStyle::PARTITIONED { columns } => {
3198 write!(f, " PARTITIONED BY ({})", display_comma_separated(columns))?;
3199 }
3200 HiveDistributionStyle::SKEWED {
3201 columns,
3202 on,
3203 stored_as_directories,
3204 } => {
3205 write!(
3206 f,
3207 " SKEWED BY ({})) ON ({})",
3208 display_comma_separated(columns),
3209 display_comma_separated(on)
3210 )?;
3211 if *stored_as_directories {
3212 write!(f, " STORED AS DIRECTORIES")?;
3213 }
3214 }
3215 _ => (),
3216 }
3217
3218 if let Some(clustered_by) = &self.clustered_by {
3219 write!(f, " {clustered_by}")?;
3220 }
3221
3222 if let Some(HiveFormat {
3223 row_format,
3224 serde_properties,
3225 storage,
3226 location,
3227 }) = &self.hive_formats
3228 {
3229 match row_format {
3230 Some(HiveRowFormat::SERDE { class }) => write!(f, " ROW FORMAT SERDE '{class}'")?,
3231 Some(HiveRowFormat::DELIMITED { delimiters }) => {
3232 write!(f, " ROW FORMAT DELIMITED")?;
3233 if !delimiters.is_empty() {
3234 write!(f, " {}", display_separated(delimiters, " "))?;
3235 }
3236 }
3237 None => (),
3238 }
3239 match storage {
3240 Some(HiveIOFormat::IOF {
3241 input_format,
3242 output_format,
3243 }) => write!(
3244 f,
3245 " STORED AS INPUTFORMAT {input_format} OUTPUTFORMAT {output_format}"
3246 )?,
3247 Some(HiveIOFormat::FileFormat { format }) if !self.external => {
3248 write!(f, " STORED AS {format}")?
3249 }
3250 Some(HiveIOFormat::Using { format }) => write!(f, " USING {format}")?,
3251 _ => (),
3252 }
3253 if let Some(serde_properties) = serde_properties.as_ref() {
3254 write!(
3255 f,
3256 " WITH SERDEPROPERTIES ({})",
3257 display_comma_separated(serde_properties)
3258 )?;
3259 }
3260 if !self.external {
3261 if let Some(loc) = location {
3262 write!(f, " LOCATION '{loc}'")?;
3263 }
3264 }
3265 }
3266 if self.external {
3267 if let Some(file_format) = self.file_format {
3268 write!(f, " STORED AS {file_format}")?;
3269 }
3270 if let Some(location) = &self.location {
3271 write!(f, " LOCATION '{location}'")?;
3272 }
3273 }
3274
3275 match &self.table_options {
3276 options @ CreateTableOptions::With(_)
3277 | options @ CreateTableOptions::Plain(_)
3278 | options @ CreateTableOptions::TableProperties(_) => write!(f, " {options}")?,
3279 _ => (),
3280 }
3281
3282 if let Some(primary_key) = &self.primary_key {
3283 write!(f, " PRIMARY KEY {primary_key}")?;
3284 }
3285 if let Some(order_by) = &self.order_by {
3286 write!(f, " ORDER BY {order_by}")?;
3287 }
3288 if let Some(inherits) = &self.inherits {
3289 write!(f, " INHERITS ({})", display_comma_separated(inherits))?;
3290 }
3291 if let Some(partition_by) = self.partition_by.as_ref() {
3292 write!(f, " PARTITION BY {partition_by}")?;
3293 }
3294 if let Some(cluster_by) = self.cluster_by.as_ref() {
3295 write!(f, " CLUSTER BY {cluster_by}")?;
3296 }
3297 if let Some(with_connection) = &self.with_connection {
3298 write!(f, " WITH CONNECTION {with_connection}")?;
3299 }
3300 if let options @ CreateTableOptions::Options(_) = &self.table_options {
3301 write!(f, " {options}")?;
3302 }
3303 if let Some(external_volume) = self.external_volume.as_ref() {
3304 write!(f, " EXTERNAL_VOLUME='{external_volume}'")?;
3305 }
3306
3307 if let Some(catalog) = self.catalog.as_ref() {
3308 write!(f, " CATALOG='{catalog}'")?;
3309 }
3310
3311 if self.iceberg {
3312 if let Some(base_location) = self.base_location.as_ref() {
3313 write!(f, " BASE_LOCATION='{base_location}'")?;
3314 }
3315 }
3316
3317 if let Some(catalog_sync) = self.catalog_sync.as_ref() {
3318 write!(f, " CATALOG_SYNC='{catalog_sync}'")?;
3319 }
3320
3321 if let Some(storage_serialization_policy) = self.storage_serialization_policy.as_ref() {
3322 write!(
3323 f,
3324 " STORAGE_SERIALIZATION_POLICY={storage_serialization_policy}"
3325 )?;
3326 }
3327
3328 if self.copy_grants {
3329 write!(f, " COPY GRANTS")?;
3330 }
3331
3332 if let Some(is_enabled) = self.enable_schema_evolution {
3333 write!(
3334 f,
3335 " ENABLE_SCHEMA_EVOLUTION={}",
3336 if is_enabled { "TRUE" } else { "FALSE" }
3337 )?;
3338 }
3339
3340 if let Some(is_enabled) = self.change_tracking {
3341 write!(
3342 f,
3343 " CHANGE_TRACKING={}",
3344 if is_enabled { "TRUE" } else { "FALSE" }
3345 )?;
3346 }
3347
3348 if let Some(data_retention_time_in_days) = self.data_retention_time_in_days {
3349 write!(
3350 f,
3351 " DATA_RETENTION_TIME_IN_DAYS={data_retention_time_in_days}",
3352 )?;
3353 }
3354
3355 if let Some(max_data_extension_time_in_days) = self.max_data_extension_time_in_days {
3356 write!(
3357 f,
3358 " MAX_DATA_EXTENSION_TIME_IN_DAYS={max_data_extension_time_in_days}",
3359 )?;
3360 }
3361
3362 if let Some(default_ddl_collation) = &self.default_ddl_collation {
3363 write!(f, " DEFAULT_DDL_COLLATION='{default_ddl_collation}'",)?;
3364 }
3365
3366 if let Some(with_aggregation_policy) = &self.with_aggregation_policy {
3367 write!(f, " WITH AGGREGATION POLICY {with_aggregation_policy}",)?;
3368 }
3369
3370 if let Some(row_access_policy) = &self.with_row_access_policy {
3371 write!(f, " {row_access_policy}",)?;
3372 }
3373
3374 if let Some(storage_lifecycle_policy) = &self.with_storage_lifecycle_policy {
3375 write!(f, " {storage_lifecycle_policy}",)?;
3376 }
3377
3378 if let Some(tag) = &self.with_tags {
3379 write!(f, " WITH TAG ({})", display_comma_separated(tag.as_slice()))?;
3380 }
3381
3382 if let Some(target_lag) = &self.target_lag {
3383 write!(f, " TARGET_LAG='{target_lag}'")?;
3384 }
3385
3386 if let Some(warehouse) = &self.warehouse {
3387 write!(f, " WAREHOUSE={warehouse}")?;
3388 }
3389
3390 if let Some(refresh_mode) = &self.refresh_mode {
3391 write!(f, " REFRESH_MODE={refresh_mode}")?;
3392 }
3393
3394 if let Some(initialize) = &self.initialize {
3395 write!(f, " INITIALIZE={initialize}")?;
3396 }
3397
3398 if self.require_user {
3399 write!(f, " REQUIRE USER")?;
3400 }
3401
3402 if self.on_commit.is_some() {
3403 let on_commit = match self.on_commit {
3404 Some(OnCommit::DeleteRows) => "ON COMMIT DELETE ROWS",
3405 Some(OnCommit::PreserveRows) => "ON COMMIT PRESERVE ROWS",
3406 Some(OnCommit::Drop) => "ON COMMIT DROP",
3407 None => "",
3408 };
3409 write!(f, " {on_commit}")?;
3410 }
3411 if self.strict {
3412 write!(f, " STRICT")?;
3413 }
3414 if let Some(backup) = self.backup {
3415 write!(f, " BACKUP {}", if backup { "YES" } else { "NO" })?;
3416 }
3417 if let Some(diststyle) = &self.diststyle {
3418 write!(f, " DISTSTYLE {diststyle}")?;
3419 }
3420 if let Some(distkey) = &self.distkey {
3421 write!(f, " DISTKEY({distkey})")?;
3422 }
3423 if let Some(sortkey) = &self.sortkey {
3424 write!(f, " SORTKEY({})", display_comma_separated(sortkey))?;
3425 }
3426 if let Some(query) = &self.query {
3427 write!(f, " AS {query}")?;
3428 }
3429 if let Some(with_data) = &self.with_data {
3430 write!(f, " {with_data}")?;
3431 }
3432 Ok(())
3433 }
3434}
3435
3436#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
3440#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3441#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3442pub struct WithData {
3443 pub data: bool,
3445 pub statistics: Option<bool>,
3448}
3449
3450impl fmt::Display for WithData {
3451 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3452 f.write_str("WITH ")?;
3453 if !self.data {
3454 f.write_str("NO ")?;
3455 }
3456 f.write_str("DATA")?;
3457 if let Some(stats) = self.statistics {
3458 f.write_str(" AND ")?;
3459 if !stats {
3460 f.write_str("NO ")?;
3461 }
3462 f.write_str("STATISTICS")?;
3463 }
3464 Ok(())
3465 }
3466}
3467
3468#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3474#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3475#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3476pub enum ForValues {
3477 In(Vec<Expr>),
3479 From {
3481 from: Vec<PartitionBoundValue>,
3483 to: Vec<PartitionBoundValue>,
3485 },
3486 With {
3488 modulus: u64,
3490 remainder: u64,
3492 },
3493 Default,
3495}
3496
3497impl fmt::Display for ForValues {
3498 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3499 match self {
3500 ForValues::In(values) => {
3501 write!(f, "FOR VALUES IN ({})", display_comma_separated(values))
3502 }
3503 ForValues::From { from, to } => {
3504 write!(
3505 f,
3506 "FOR VALUES FROM ({}) TO ({})",
3507 display_comma_separated(from),
3508 display_comma_separated(to)
3509 )
3510 }
3511 ForValues::With { modulus, remainder } => {
3512 write!(
3513 f,
3514 "FOR VALUES WITH (MODULUS {modulus}, REMAINDER {remainder})"
3515 )
3516 }
3517 ForValues::Default => write!(f, "DEFAULT"),
3518 }
3519 }
3520}
3521
3522#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3527#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3528#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3529pub enum PartitionBoundValue {
3530 Expr(Expr),
3532 MinValue,
3534 MaxValue,
3536}
3537
3538impl fmt::Display for PartitionBoundValue {
3539 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3540 match self {
3541 PartitionBoundValue::Expr(expr) => write!(f, "{expr}"),
3542 PartitionBoundValue::MinValue => write!(f, "MINVALUE"),
3543 PartitionBoundValue::MaxValue => write!(f, "MAXVALUE"),
3544 }
3545 }
3546}
3547
3548#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3552#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3553#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3554pub enum DistStyle {
3555 Auto,
3557 Even,
3559 Key,
3561 All,
3563}
3564
3565impl fmt::Display for DistStyle {
3566 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3567 match self {
3568 DistStyle::Auto => write!(f, "AUTO"),
3569 DistStyle::Even => write!(f, "EVEN"),
3570 DistStyle::Key => write!(f, "KEY"),
3571 DistStyle::All => write!(f, "ALL"),
3572 }
3573 }
3574}
3575
3576#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3577#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3578#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3579pub struct CreateDomain {
3592 pub name: ObjectName,
3594 pub data_type: DataType,
3596 pub collation: Option<Ident>,
3598 pub default: Option<Expr>,
3600 pub constraints: Vec<TableConstraint>,
3602}
3603
3604impl fmt::Display for CreateDomain {
3605 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3606 write!(
3607 f,
3608 "CREATE DOMAIN {name} AS {data_type}",
3609 name = self.name,
3610 data_type = self.data_type
3611 )?;
3612 if let Some(collation) = &self.collation {
3613 write!(f, " COLLATE {collation}")?;
3614 }
3615 if let Some(default) = &self.default {
3616 write!(f, " DEFAULT {default}")?;
3617 }
3618 if !self.constraints.is_empty() {
3619 write!(f, " {}", display_separated(&self.constraints, " "))?;
3620 }
3621 Ok(())
3622 }
3623}
3624
3625#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3627#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3628#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3629pub enum FunctionReturnType {
3630 DataType(DataType),
3632 SetOf(DataType),
3636}
3637
3638impl fmt::Display for FunctionReturnType {
3639 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3640 match self {
3641 FunctionReturnType::DataType(data_type) => write!(f, "{data_type}"),
3642 FunctionReturnType::SetOf(data_type) => write!(f, "SETOF {data_type}"),
3643 }
3644 }
3645}
3646
3647#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3648#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3649#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3650pub struct CreateFunction {
3652 pub or_alter: bool,
3656 pub or_replace: bool,
3658 pub temporary: bool,
3660 pub if_not_exists: bool,
3662 pub name: ObjectName,
3664 pub args: Option<Vec<OperateFunctionArg>>,
3666 pub return_type: Option<FunctionReturnType>,
3668 pub function_body: Option<CreateFunctionBody>,
3676 pub behavior: Option<FunctionBehavior>,
3682 pub called_on_null: Option<FunctionCalledOnNull>,
3686 pub parallel: Option<FunctionParallel>,
3690 pub security: Option<FunctionSecurity>,
3694 pub set_params: Vec<FunctionDefinitionSetParam>,
3698 pub using: Option<CreateFunctionUsing>,
3700 pub language: Option<Ident>,
3708 pub determinism_specifier: Option<FunctionDeterminismSpecifier>,
3712 pub options: Option<Vec<SqlOption>>,
3716 pub remote_connection: Option<ObjectName>,
3726}
3727
3728impl fmt::Display for CreateFunction {
3729 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3730 write!(
3731 f,
3732 "CREATE {or_alter}{or_replace}{temp}FUNCTION {if_not_exists}{name}",
3733 name = self.name,
3734 temp = if self.temporary { "TEMPORARY " } else { "" },
3735 or_alter = if self.or_alter { "OR ALTER " } else { "" },
3736 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3737 if_not_exists = if self.if_not_exists {
3738 "IF NOT EXISTS "
3739 } else {
3740 ""
3741 },
3742 )?;
3743 if let Some(args) = &self.args {
3744 write!(f, "({})", display_comma_separated(args))?;
3745 }
3746 if let Some(return_type) = &self.return_type {
3747 write!(f, " RETURNS {return_type}")?;
3748 }
3749 if let Some(determinism_specifier) = &self.determinism_specifier {
3750 write!(f, " {determinism_specifier}")?;
3751 }
3752 if let Some(language) = &self.language {
3753 write!(f, " LANGUAGE {language}")?;
3754 }
3755 if let Some(behavior) = &self.behavior {
3756 write!(f, " {behavior}")?;
3757 }
3758 if let Some(called_on_null) = &self.called_on_null {
3759 write!(f, " {called_on_null}")?;
3760 }
3761 if let Some(parallel) = &self.parallel {
3762 write!(f, " {parallel}")?;
3763 }
3764 if let Some(security) = &self.security {
3765 write!(f, " {security}")?;
3766 }
3767 for set_param in &self.set_params {
3768 write!(f, " {set_param}")?;
3769 }
3770 if let Some(remote_connection) = &self.remote_connection {
3771 write!(f, " REMOTE WITH CONNECTION {remote_connection}")?;
3772 }
3773 if let Some(CreateFunctionBody::AsBeforeOptions { body, link_symbol }) = &self.function_body
3774 {
3775 write!(f, " AS {body}")?;
3776 if let Some(link_symbol) = link_symbol {
3777 write!(f, ", {link_symbol}")?;
3778 }
3779 }
3780 if let Some(CreateFunctionBody::Return(function_body)) = &self.function_body {
3781 write!(f, " RETURN {function_body}")?;
3782 }
3783 if let Some(CreateFunctionBody::AsReturnExpr(function_body)) = &self.function_body {
3784 write!(f, " AS RETURN {function_body}")?;
3785 }
3786 if let Some(CreateFunctionBody::AsReturnSelect(function_body)) = &self.function_body {
3787 write!(f, " AS RETURN {function_body}")?;
3788 }
3789 if let Some(using) = &self.using {
3790 write!(f, " {using}")?;
3791 }
3792 if let Some(options) = &self.options {
3793 write!(
3794 f,
3795 " OPTIONS({})",
3796 display_comma_separated(options.as_slice())
3797 )?;
3798 }
3799 if let Some(CreateFunctionBody::AsAfterOptions(function_body)) = &self.function_body {
3800 write!(f, " AS {function_body}")?;
3801 }
3802 if let Some(CreateFunctionBody::AsBeginEnd(bes)) = &self.function_body {
3803 write!(f, " AS {bes}")?;
3804 }
3805 Ok(())
3806 }
3807}
3808
3809#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3819#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3820#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3821pub struct CreateConnector {
3822 pub name: Ident,
3824 pub if_not_exists: bool,
3826 pub connector_type: Option<String>,
3828 pub url: Option<String>,
3830 pub comment: Option<CommentDef>,
3832 pub with_dcproperties: Option<Vec<SqlOption>>,
3834}
3835
3836impl fmt::Display for CreateConnector {
3837 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3838 write!(
3839 f,
3840 "CREATE CONNECTOR {if_not_exists}{name}",
3841 if_not_exists = if self.if_not_exists {
3842 "IF NOT EXISTS "
3843 } else {
3844 ""
3845 },
3846 name = self.name,
3847 )?;
3848
3849 if let Some(connector_type) = &self.connector_type {
3850 write!(f, " TYPE '{connector_type}'")?;
3851 }
3852
3853 if let Some(url) = &self.url {
3854 write!(f, " URL '{url}'")?;
3855 }
3856
3857 if let Some(comment) = &self.comment {
3858 write!(f, " COMMENT = '{comment}'")?;
3859 }
3860
3861 if let Some(with_dcproperties) = &self.with_dcproperties {
3862 write!(
3863 f,
3864 " WITH DCPROPERTIES({})",
3865 display_comma_separated(with_dcproperties)
3866 )?;
3867 }
3868
3869 Ok(())
3870 }
3871}
3872
3873#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3878#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3879#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3880pub enum AlterSchemaOperation {
3881 SetDefaultCollate {
3883 collate: Expr,
3885 },
3886 AddReplica {
3888 replica: Ident,
3890 options: Option<Vec<SqlOption>>,
3892 },
3893 DropReplica {
3895 replica: Ident,
3897 },
3898 SetOptionsParens {
3900 options: Vec<SqlOption>,
3902 },
3903 Rename {
3905 name: ObjectName,
3907 },
3908 OwnerTo {
3910 owner: Owner,
3912 },
3913}
3914
3915impl fmt::Display for AlterSchemaOperation {
3916 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3917 match self {
3918 AlterSchemaOperation::SetDefaultCollate { collate } => {
3919 write!(f, "SET DEFAULT COLLATE {collate}")
3920 }
3921 AlterSchemaOperation::AddReplica { replica, options } => {
3922 write!(f, "ADD REPLICA {replica}")?;
3923 if let Some(options) = options {
3924 write!(f, " OPTIONS ({})", display_comma_separated(options))?;
3925 }
3926 Ok(())
3927 }
3928 AlterSchemaOperation::DropReplica { replica } => write!(f, "DROP REPLICA {replica}"),
3929 AlterSchemaOperation::SetOptionsParens { options } => {
3930 write!(f, "SET OPTIONS ({})", display_comma_separated(options))
3931 }
3932 AlterSchemaOperation::Rename { name } => write!(f, "RENAME TO {name}"),
3933 AlterSchemaOperation::OwnerTo { owner } => write!(f, "OWNER TO {owner}"),
3934 }
3935 }
3936}
3937#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3943#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3944#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3945pub enum RenameTableNameKind {
3946 As(ObjectName),
3948 To(ObjectName),
3950}
3951
3952impl fmt::Display for RenameTableNameKind {
3953 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3954 match self {
3955 RenameTableNameKind::As(name) => write!(f, "AS {name}"),
3956 RenameTableNameKind::To(name) => write!(f, "TO {name}"),
3957 }
3958 }
3959}
3960
3961#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3962#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3963#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3964pub struct AlterSchema {
3966 pub name: ObjectName,
3968 pub if_exists: bool,
3970 pub operations: Vec<AlterSchemaOperation>,
3972}
3973
3974impl fmt::Display for AlterSchema {
3975 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3976 write!(f, "ALTER SCHEMA ")?;
3977 if self.if_exists {
3978 write!(f, "IF EXISTS ")?;
3979 }
3980 write!(f, "{}", self.name)?;
3981 for operation in &self.operations {
3982 write!(f, " {operation}")?;
3983 }
3984
3985 Ok(())
3986 }
3987}
3988
3989impl Spanned for RenameTableNameKind {
3990 fn span(&self) -> Span {
3991 match self {
3992 RenameTableNameKind::As(name) => name.span(),
3993 RenameTableNameKind::To(name) => name.span(),
3994 }
3995 }
3996}
3997
3998#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
3999#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4000#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4001pub enum TriggerObjectKind {
4003 For(TriggerObject),
4005 ForEach(TriggerObject),
4007}
4008
4009impl Display for TriggerObjectKind {
4010 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4011 match self {
4012 TriggerObjectKind::For(obj) => write!(f, "FOR {obj}"),
4013 TriggerObjectKind::ForEach(obj) => write!(f, "FOR EACH {obj}"),
4014 }
4015 }
4016}
4017
4018#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4019#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4020#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4021pub struct CreateTrigger {
4035 pub or_alter: bool,
4039 pub temporary: bool,
4056 pub or_replace: bool,
4066 pub is_constraint: bool,
4068 pub name: ObjectName,
4070 pub period: Option<TriggerPeriod>,
4099 pub period_before_table: bool,
4110 pub events: Vec<TriggerEvent>,
4112 pub table_name: ObjectName,
4114 pub referenced_table_name: Option<ObjectName>,
4117 pub referencing: Vec<TriggerReferencing>,
4119 pub trigger_object: Option<TriggerObjectKind>,
4124 pub condition: Option<Expr>,
4126 pub exec_body: Option<TriggerExecBody>,
4128 pub statements_as: bool,
4130 pub statements: Option<ConditionalStatements>,
4132 pub characteristics: Option<ConstraintCharacteristics>,
4134}
4135
4136impl Display for CreateTrigger {
4137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4138 let CreateTrigger {
4139 or_alter,
4140 temporary,
4141 or_replace,
4142 is_constraint,
4143 name,
4144 period_before_table,
4145 period,
4146 events,
4147 table_name,
4148 referenced_table_name,
4149 referencing,
4150 trigger_object,
4151 condition,
4152 exec_body,
4153 statements_as,
4154 statements,
4155 characteristics,
4156 } = self;
4157 write!(
4158 f,
4159 "CREATE {temporary}{or_alter}{or_replace}{is_constraint}TRIGGER {name} ",
4160 temporary = if *temporary { "TEMPORARY " } else { "" },
4161 or_alter = if *or_alter { "OR ALTER " } else { "" },
4162 or_replace = if *or_replace { "OR REPLACE " } else { "" },
4163 is_constraint = if *is_constraint { "CONSTRAINT " } else { "" },
4164 )?;
4165
4166 if *period_before_table {
4167 if let Some(p) = period {
4168 write!(f, "{p} ")?;
4169 }
4170 if !events.is_empty() {
4171 write!(f, "{} ", display_separated(events, " OR "))?;
4172 }
4173 write!(f, "ON {table_name}")?;
4174 } else {
4175 write!(f, "ON {table_name} ")?;
4176 if let Some(p) = period {
4177 write!(f, "{p}")?;
4178 }
4179 if !events.is_empty() {
4180 write!(f, " {}", display_separated(events, ", "))?;
4181 }
4182 }
4183
4184 if let Some(referenced_table_name) = referenced_table_name {
4185 write!(f, " FROM {referenced_table_name}")?;
4186 }
4187
4188 if let Some(characteristics) = characteristics {
4189 write!(f, " {characteristics}")?;
4190 }
4191
4192 if !referencing.is_empty() {
4193 write!(f, " REFERENCING {}", display_separated(referencing, " "))?;
4194 }
4195
4196 if let Some(trigger_object) = trigger_object {
4197 write!(f, " {trigger_object}")?;
4198 }
4199 if let Some(condition) = condition {
4200 write!(f, " WHEN {condition}")?;
4201 }
4202 if let Some(exec_body) = exec_body {
4203 write!(f, " EXECUTE {exec_body}")?;
4204 }
4205 if let Some(statements) = statements {
4206 if *statements_as {
4207 write!(f, " AS")?;
4208 }
4209 write!(f, " {statements}")?;
4210 }
4211 Ok(())
4212 }
4213}
4214
4215#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4216#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4217#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4218pub struct DropTrigger {
4225 pub if_exists: bool,
4227 pub trigger_name: ObjectName,
4229 pub table_name: Option<ObjectName>,
4231 pub option: Option<ReferentialAction>,
4233}
4234
4235impl fmt::Display for DropTrigger {
4236 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4237 let DropTrigger {
4238 if_exists,
4239 trigger_name,
4240 table_name,
4241 option,
4242 } = self;
4243 write!(f, "DROP TRIGGER")?;
4244 if *if_exists {
4245 write!(f, " IF EXISTS")?;
4246 }
4247 match &table_name {
4248 Some(table_name) => write!(f, " {trigger_name} ON {table_name}")?,
4249 None => write!(f, " {trigger_name}")?,
4250 };
4251 if let Some(option) = option {
4252 write!(f, " {option}")?;
4253 }
4254 Ok(())
4255 }
4256}
4257
4258#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4264#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4265#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4266pub struct Truncate {
4267 pub table_names: Vec<super::TruncateTableTarget>,
4269 pub partitions: Option<Vec<Expr>>,
4271 pub table: bool,
4273 pub if_exists: bool,
4275 pub identity: Option<super::TruncateIdentityOption>,
4277 pub cascade: Option<super::CascadeOption>,
4279 pub on_cluster: Option<Ident>,
4282}
4283
4284impl fmt::Display for Truncate {
4285 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4286 let table = if self.table { "TABLE " } else { "" };
4287 let if_exists = if self.if_exists { "IF EXISTS " } else { "" };
4288
4289 write!(
4290 f,
4291 "TRUNCATE {table}{if_exists}{table_names}",
4292 table_names = display_comma_separated(&self.table_names)
4293 )?;
4294
4295 if let Some(identity) = &self.identity {
4296 match identity {
4297 super::TruncateIdentityOption::Restart => write!(f, " RESTART IDENTITY")?,
4298 super::TruncateIdentityOption::Continue => write!(f, " CONTINUE IDENTITY")?,
4299 }
4300 }
4301 if let Some(cascade) = &self.cascade {
4302 match cascade {
4303 super::CascadeOption::Cascade => write!(f, " CASCADE")?,
4304 super::CascadeOption::Restrict => write!(f, " RESTRICT")?,
4305 }
4306 }
4307
4308 if let Some(ref parts) = &self.partitions {
4309 if !parts.is_empty() {
4310 write!(f, " PARTITION ({})", display_comma_separated(parts))?;
4311 }
4312 }
4313 if let Some(on_cluster) = &self.on_cluster {
4314 write!(f, " ON CLUSTER {on_cluster}")?;
4315 }
4316 Ok(())
4317 }
4318}
4319
4320impl Spanned for Truncate {
4321 fn span(&self) -> Span {
4322 Span::union_iter(
4323 self.table_names.iter().map(|i| i.name.span()).chain(
4324 self.partitions
4325 .iter()
4326 .flat_map(|i| i.iter().map(|k| k.span())),
4327 ),
4328 )
4329 }
4330}
4331
4332#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4339#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4340#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4341pub struct Msck {
4342 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4344 pub table_name: ObjectName,
4345 pub repair: bool,
4347 pub partition_action: Option<super::AddDropSync>,
4349}
4350
4351impl fmt::Display for Msck {
4352 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4353 write!(
4354 f,
4355 "MSCK {repair}TABLE {table}",
4356 repair = if self.repair { "REPAIR " } else { "" },
4357 table = self.table_name
4358 )?;
4359 if let Some(pa) = &self.partition_action {
4360 write!(f, " {pa}")?;
4361 }
4362 Ok(())
4363 }
4364}
4365
4366impl Spanned for Msck {
4367 fn span(&self) -> Span {
4368 self.table_name.span()
4369 }
4370}
4371
4372#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4374#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4375#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4376pub struct CreateView {
4377 pub or_alter: bool,
4381 pub or_replace: bool,
4383 pub materialized: bool,
4385 pub secure: bool,
4388 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4390 pub name: ObjectName,
4391 pub name_before_not_exists: bool,
4402 pub columns: Vec<ViewColumnDef>,
4404 pub query: Box<Query>,
4406 pub options: CreateTableOptions,
4408 pub cluster_by: Vec<Ident>,
4410 pub comment: Option<String>,
4413 pub with_no_schema_binding: bool,
4415 pub if_not_exists: bool,
4417 pub temporary: bool,
4419 pub copy_grants: bool,
4422 pub to: Option<ObjectName>,
4425 pub params: Option<CreateViewParams>,
4427}
4428
4429impl fmt::Display for CreateView {
4430 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4431 write!(
4432 f,
4433 "CREATE {or_alter}{or_replace}",
4434 or_alter = if self.or_alter { "OR ALTER " } else { "" },
4435 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
4436 )?;
4437 if let Some(ref params) = self.params {
4438 params.fmt(f)?;
4439 }
4440 write!(
4441 f,
4442 "{secure}{materialized}{temporary}VIEW {if_not_and_name}{to}",
4443 if_not_and_name = if self.if_not_exists {
4444 if self.name_before_not_exists {
4445 format!("{} IF NOT EXISTS", self.name)
4446 } else {
4447 format!("IF NOT EXISTS {}", self.name)
4448 }
4449 } else {
4450 format!("{}", self.name)
4451 },
4452 secure = if self.secure { "SECURE " } else { "" },
4453 materialized = if self.materialized {
4454 "MATERIALIZED "
4455 } else {
4456 ""
4457 },
4458 temporary = if self.temporary { "TEMPORARY " } else { "" },
4459 to = self
4460 .to
4461 .as_ref()
4462 .map(|to| format!(" TO {to}"))
4463 .unwrap_or_default()
4464 )?;
4465 if self.copy_grants {
4466 write!(f, " COPY GRANTS")?;
4467 }
4468 if !self.columns.is_empty() {
4469 write!(f, " ({})", display_comma_separated(&self.columns))?;
4470 }
4471 if matches!(self.options, CreateTableOptions::With(_)) {
4472 write!(f, " {}", self.options)?;
4473 }
4474 if let Some(ref comment) = self.comment {
4475 write!(f, " COMMENT = '{}'", escape_single_quote_string(comment))?;
4476 }
4477 if !self.cluster_by.is_empty() {
4478 write!(
4479 f,
4480 " CLUSTER BY ({})",
4481 display_comma_separated(&self.cluster_by)
4482 )?;
4483 }
4484 if matches!(self.options, CreateTableOptions::Options(_)) {
4485 write!(f, " {}", self.options)?;
4486 }
4487 f.write_str(" AS")?;
4488 SpaceOrNewline.fmt(f)?;
4489 self.query.fmt(f)?;
4490 if self.with_no_schema_binding {
4491 write!(f, " WITH NO SCHEMA BINDING")?;
4492 }
4493 Ok(())
4494 }
4495}
4496
4497#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4500#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4501#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4502pub struct CreateExtension {
4503 pub name: Ident,
4505 pub if_not_exists: bool,
4507 pub cascade: bool,
4509 pub schema: Option<Ident>,
4511 pub version: Option<Ident>,
4513}
4514
4515impl fmt::Display for CreateExtension {
4516 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4517 write!(
4518 f,
4519 "CREATE EXTENSION {if_not_exists}{name}",
4520 if_not_exists = if self.if_not_exists {
4521 "IF NOT EXISTS "
4522 } else {
4523 ""
4524 },
4525 name = self.name
4526 )?;
4527 if self.cascade || self.schema.is_some() || self.version.is_some() {
4528 write!(f, " WITH")?;
4529
4530 if let Some(name) = &self.schema {
4531 write!(f, " SCHEMA {name}")?;
4532 }
4533 if let Some(version) = &self.version {
4534 write!(f, " VERSION {version}")?;
4535 }
4536 if self.cascade {
4537 write!(f, " CASCADE")?;
4538 }
4539 }
4540
4541 Ok(())
4542 }
4543}
4544
4545impl Spanned for CreateExtension {
4546 fn span(&self) -> Span {
4547 Span::empty()
4548 }
4549}
4550
4551#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4559#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4560#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4561pub struct DropExtension {
4562 pub names: Vec<Ident>,
4564 pub if_exists: bool,
4566 pub cascade_or_restrict: Option<ReferentialAction>,
4568}
4569
4570impl fmt::Display for DropExtension {
4571 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4572 write!(f, "DROP EXTENSION")?;
4573 if self.if_exists {
4574 write!(f, " IF EXISTS")?;
4575 }
4576 write!(f, " {}", display_comma_separated(&self.names))?;
4577 if let Some(cascade_or_restrict) = &self.cascade_or_restrict {
4578 write!(f, " {cascade_or_restrict}")?;
4579 }
4580 Ok(())
4581 }
4582}
4583
4584impl Spanned for DropExtension {
4585 fn span(&self) -> Span {
4586 Span::empty()
4587 }
4588}
4589
4590#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4593#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4594#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4595pub struct CreateCollation {
4596 pub if_not_exists: bool,
4598 pub name: ObjectName,
4600 pub definition: CreateCollationDefinition,
4602}
4603
4604#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4606#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4607#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4608pub enum CreateCollationDefinition {
4609 From(ObjectName),
4615 Options(Vec<SqlOption>),
4621}
4622
4623impl fmt::Display for CreateCollation {
4624 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4625 write!(
4626 f,
4627 "CREATE COLLATION {if_not_exists}{name}",
4628 if_not_exists = if self.if_not_exists {
4629 "IF NOT EXISTS "
4630 } else {
4631 ""
4632 },
4633 name = self.name
4634 )?;
4635 match &self.definition {
4636 CreateCollationDefinition::From(existing_collation) => {
4637 write!(f, " FROM {existing_collation}")
4638 }
4639 CreateCollationDefinition::Options(options) => {
4640 write!(f, " ({})", display_comma_separated(options))
4641 }
4642 }
4643 }
4644}
4645
4646impl Spanned for CreateCollation {
4647 fn span(&self) -> Span {
4648 Span::empty()
4649 }
4650}
4651
4652#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4655#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4656#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4657pub struct AlterCollation {
4658 pub name: ObjectName,
4660 pub operation: AlterCollationOperation,
4662}
4663
4664#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4666#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4667#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4668pub enum AlterCollationOperation {
4669 RenameTo {
4675 new_name: Ident,
4677 },
4678 OwnerTo(Owner),
4684 SetSchema {
4690 schema_name: ObjectName,
4692 },
4693 RefreshVersion,
4699}
4700
4701impl fmt::Display for AlterCollationOperation {
4702 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4703 match self {
4704 AlterCollationOperation::RenameTo { new_name } => write!(f, "RENAME TO {new_name}"),
4705 AlterCollationOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
4706 AlterCollationOperation::SetSchema { schema_name } => {
4707 write!(f, "SET SCHEMA {schema_name}")
4708 }
4709 AlterCollationOperation::RefreshVersion => write!(f, "REFRESH VERSION"),
4710 }
4711 }
4712}
4713
4714impl fmt::Display for AlterCollation {
4715 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4716 write!(f, "ALTER COLLATION {} {}", self.name, self.operation)
4717 }
4718}
4719
4720impl Spanned for AlterCollation {
4721 fn span(&self) -> Span {
4722 Span::empty()
4723 }
4724}
4725
4726#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4729#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4730#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4731pub enum AlterTableType {
4732 Iceberg,
4735 Dynamic,
4738 External,
4741}
4742
4743#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4745#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4746#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4747pub struct AlterTable {
4748 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4750 pub name: ObjectName,
4751 pub if_exists: bool,
4753 pub only: bool,
4755 pub operations: Vec<AlterTableOperation>,
4757 pub location: Option<HiveSetLocation>,
4759 pub on_cluster: Option<Ident>,
4763 pub table_type: Option<AlterTableType>,
4765 pub end_token: AttachedToken,
4767}
4768
4769impl fmt::Display for AlterTable {
4770 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4771 match &self.table_type {
4772 Some(AlterTableType::Iceberg) => write!(f, "ALTER ICEBERG TABLE ")?,
4773 Some(AlterTableType::Dynamic) => write!(f, "ALTER DYNAMIC TABLE ")?,
4774 Some(AlterTableType::External) => write!(f, "ALTER EXTERNAL TABLE ")?,
4775 None => write!(f, "ALTER TABLE ")?,
4776 }
4777
4778 if self.if_exists {
4779 write!(f, "IF EXISTS ")?;
4780 }
4781 if self.only {
4782 write!(f, "ONLY ")?;
4783 }
4784 write!(f, "{} ", self.name)?;
4785 if let Some(cluster) = &self.on_cluster {
4786 write!(f, "ON CLUSTER {cluster} ")?;
4787 }
4788 write!(f, "{}", display_comma_separated(&self.operations))?;
4789 if let Some(loc) = &self.location {
4790 write!(f, " {loc}")?
4791 }
4792 Ok(())
4793 }
4794}
4795
4796#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4798#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4799#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4800pub struct DropFunction {
4801 pub if_exists: bool,
4803 pub func_desc: Vec<FunctionDesc>,
4805 pub drop_behavior: Option<DropBehavior>,
4807}
4808
4809impl fmt::Display for DropFunction {
4810 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4811 write!(
4812 f,
4813 "DROP FUNCTION{} {}",
4814 if self.if_exists { " IF EXISTS" } else { "" },
4815 display_comma_separated(&self.func_desc),
4816 )?;
4817 if let Some(op) = &self.drop_behavior {
4818 write!(f, " {op}")?;
4819 }
4820 Ok(())
4821 }
4822}
4823
4824impl Spanned for DropFunction {
4825 fn span(&self) -> Span {
4826 Span::empty()
4827 }
4828}
4829
4830#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4833#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4834#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4835pub struct CreateOperator {
4836 pub name: ObjectName,
4838 pub function: ObjectName,
4840 pub is_procedure: bool,
4842 pub left_arg: Option<DataType>,
4844 pub right_arg: Option<DataType>,
4846 pub options: Vec<OperatorOption>,
4848}
4849
4850#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4853#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4854#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4855pub struct CreateOperatorFamily {
4856 pub name: ObjectName,
4858 pub using: Ident,
4860}
4861
4862#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4865#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4866#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4867pub struct CreateOperatorClass {
4868 pub name: ObjectName,
4870 pub default: bool,
4872 pub for_type: DataType,
4874 pub using: Ident,
4876 pub family: Option<ObjectName>,
4878 pub items: Vec<OperatorClassItem>,
4880}
4881
4882impl fmt::Display for CreateOperator {
4883 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4884 write!(f, "CREATE OPERATOR {} (", self.name)?;
4885
4886 let function_keyword = if self.is_procedure {
4887 "PROCEDURE"
4888 } else {
4889 "FUNCTION"
4890 };
4891 let mut params = vec![format!("{} = {}", function_keyword, self.function)];
4892
4893 if let Some(left_arg) = &self.left_arg {
4894 params.push(format!("LEFTARG = {}", left_arg));
4895 }
4896 if let Some(right_arg) = &self.right_arg {
4897 params.push(format!("RIGHTARG = {}", right_arg));
4898 }
4899
4900 for option in &self.options {
4901 params.push(option.to_string());
4902 }
4903
4904 write!(f, "{}", params.join(", "))?;
4905 write!(f, ")")
4906 }
4907}
4908
4909impl fmt::Display for CreateOperatorFamily {
4910 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4911 write!(
4912 f,
4913 "CREATE OPERATOR FAMILY {} USING {}",
4914 self.name, self.using
4915 )
4916 }
4917}
4918
4919impl fmt::Display for CreateOperatorClass {
4920 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4921 write!(f, "CREATE OPERATOR CLASS {}", self.name)?;
4922 if self.default {
4923 write!(f, " DEFAULT")?;
4924 }
4925 write!(f, " FOR TYPE {} USING {}", self.for_type, self.using)?;
4926 if let Some(family) = &self.family {
4927 write!(f, " FAMILY {}", family)?;
4928 }
4929 write!(f, " AS {}", display_comma_separated(&self.items))
4930 }
4931}
4932
4933#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4935#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4936#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4937pub struct OperatorArgTypes {
4938 pub left: DataType,
4940 pub right: DataType,
4942}
4943
4944impl fmt::Display for OperatorArgTypes {
4945 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4946 write!(f, "{}, {}", self.left, self.right)
4947 }
4948}
4949
4950#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4952#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4953#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4954pub enum OperatorClassItem {
4955 Operator {
4957 strategy_number: u64,
4959 operator_name: ObjectName,
4961 op_types: Option<OperatorArgTypes>,
4963 purpose: Option<OperatorPurpose>,
4965 },
4966 Function {
4968 support_number: u64,
4970 op_types: Option<Vec<DataType>>,
4972 function_name: ObjectName,
4974 argument_types: Vec<DataType>,
4976 },
4977 Storage {
4979 storage_type: DataType,
4981 },
4982}
4983
4984#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4986#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4987#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4988pub enum OperatorPurpose {
4989 ForSearch,
4991 ForOrderBy {
4993 sort_family: ObjectName,
4995 },
4996}
4997
4998impl fmt::Display for OperatorClassItem {
4999 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5000 match self {
5001 OperatorClassItem::Operator {
5002 strategy_number,
5003 operator_name,
5004 op_types,
5005 purpose,
5006 } => {
5007 write!(f, "OPERATOR {strategy_number} {operator_name}")?;
5008 if let Some(types) = op_types {
5009 write!(f, " ({types})")?;
5010 }
5011 if let Some(purpose) = purpose {
5012 write!(f, " {purpose}")?;
5013 }
5014 Ok(())
5015 }
5016 OperatorClassItem::Function {
5017 support_number,
5018 op_types,
5019 function_name,
5020 argument_types,
5021 } => {
5022 write!(f, "FUNCTION {support_number}")?;
5023 if let Some(types) = op_types {
5024 write!(f, " ({})", display_comma_separated(types))?;
5025 }
5026 write!(f, " {function_name}")?;
5027 if !argument_types.is_empty() {
5028 write!(f, "({})", display_comma_separated(argument_types))?;
5029 }
5030 Ok(())
5031 }
5032 OperatorClassItem::Storage { storage_type } => {
5033 write!(f, "STORAGE {storage_type}")
5034 }
5035 }
5036 }
5037}
5038
5039impl fmt::Display for OperatorPurpose {
5040 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5041 match self {
5042 OperatorPurpose::ForSearch => write!(f, "FOR SEARCH"),
5043 OperatorPurpose::ForOrderBy { sort_family } => {
5044 write!(f, "FOR ORDER BY {sort_family}")
5045 }
5046 }
5047 }
5048}
5049
5050#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5053#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5054#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5055pub struct DropOperator {
5056 pub if_exists: bool,
5058 pub operators: Vec<DropOperatorSignature>,
5060 pub drop_behavior: Option<DropBehavior>,
5062}
5063
5064#[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 DropOperatorSignature {
5069 pub name: ObjectName,
5071 pub left_type: Option<DataType>,
5073 pub right_type: DataType,
5075}
5076
5077impl fmt::Display for DropOperatorSignature {
5078 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5079 write!(f, "{} (", self.name)?;
5080 if let Some(left_type) = &self.left_type {
5081 write!(f, "{}", left_type)?;
5082 } else {
5083 write!(f, "NONE")?;
5084 }
5085 write!(f, ", {})", self.right_type)
5086 }
5087}
5088
5089impl fmt::Display for DropOperator {
5090 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5091 write!(f, "DROP OPERATOR")?;
5092 if self.if_exists {
5093 write!(f, " IF EXISTS")?;
5094 }
5095 write!(f, " {}", display_comma_separated(&self.operators))?;
5096 if let Some(drop_behavior) = &self.drop_behavior {
5097 write!(f, " {}", drop_behavior)?;
5098 }
5099 Ok(())
5100 }
5101}
5102
5103impl Spanned for DropOperator {
5104 fn span(&self) -> Span {
5105 Span::empty()
5106 }
5107}
5108
5109#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5112#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5113#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5114pub struct DropOperatorFamily {
5115 pub if_exists: bool,
5117 pub names: Vec<ObjectName>,
5119 pub using: Ident,
5121 pub drop_behavior: Option<DropBehavior>,
5123}
5124
5125impl fmt::Display for DropOperatorFamily {
5126 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5127 write!(f, "DROP OPERATOR FAMILY")?;
5128 if self.if_exists {
5129 write!(f, " IF EXISTS")?;
5130 }
5131 write!(f, " {}", display_comma_separated(&self.names))?;
5132 write!(f, " USING {}", self.using)?;
5133 if let Some(drop_behavior) = &self.drop_behavior {
5134 write!(f, " {}", drop_behavior)?;
5135 }
5136 Ok(())
5137 }
5138}
5139
5140impl Spanned for DropOperatorFamily {
5141 fn span(&self) -> Span {
5142 Span::empty()
5143 }
5144}
5145
5146#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5149#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5150#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5151pub struct DropOperatorClass {
5152 pub if_exists: bool,
5154 pub names: Vec<ObjectName>,
5156 pub using: Ident,
5158 pub drop_behavior: Option<DropBehavior>,
5160}
5161
5162impl fmt::Display for DropOperatorClass {
5163 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5164 write!(f, "DROP OPERATOR CLASS")?;
5165 if self.if_exists {
5166 write!(f, " IF EXISTS")?;
5167 }
5168 write!(f, " {}", display_comma_separated(&self.names))?;
5169 write!(f, " USING {}", self.using)?;
5170 if let Some(drop_behavior) = &self.drop_behavior {
5171 write!(f, " {}", drop_behavior)?;
5172 }
5173 Ok(())
5174 }
5175}
5176
5177impl Spanned for DropOperatorClass {
5178 fn span(&self) -> Span {
5179 Span::empty()
5180 }
5181}
5182
5183#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5185#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5186#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5187pub enum OperatorFamilyItem {
5188 Operator {
5190 strategy_number: u64,
5192 operator_name: ObjectName,
5194 op_types: Vec<DataType>,
5196 purpose: Option<OperatorPurpose>,
5198 },
5199 Function {
5201 support_number: u64,
5203 op_types: Option<Vec<DataType>>,
5205 function_name: ObjectName,
5207 argument_types: Vec<DataType>,
5209 },
5210}
5211
5212#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5214#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5215#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5216pub enum OperatorFamilyDropItem {
5217 Operator {
5219 strategy_number: u64,
5221 op_types: Vec<DataType>,
5223 },
5224 Function {
5226 support_number: u64,
5228 op_types: Vec<DataType>,
5230 },
5231}
5232
5233impl fmt::Display for OperatorFamilyItem {
5234 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5235 match self {
5236 OperatorFamilyItem::Operator {
5237 strategy_number,
5238 operator_name,
5239 op_types,
5240 purpose,
5241 } => {
5242 write!(
5243 f,
5244 "OPERATOR {strategy_number} {operator_name} ({})",
5245 display_comma_separated(op_types)
5246 )?;
5247 if let Some(purpose) = purpose {
5248 write!(f, " {purpose}")?;
5249 }
5250 Ok(())
5251 }
5252 OperatorFamilyItem::Function {
5253 support_number,
5254 op_types,
5255 function_name,
5256 argument_types,
5257 } => {
5258 write!(f, "FUNCTION {support_number}")?;
5259 if let Some(types) = op_types {
5260 write!(f, " ({})", display_comma_separated(types))?;
5261 }
5262 write!(f, " {function_name}")?;
5263 if !argument_types.is_empty() {
5264 write!(f, "({})", display_comma_separated(argument_types))?;
5265 }
5266 Ok(())
5267 }
5268 }
5269 }
5270}
5271
5272impl fmt::Display for OperatorFamilyDropItem {
5273 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5274 match self {
5275 OperatorFamilyDropItem::Operator {
5276 strategy_number,
5277 op_types,
5278 } => {
5279 write!(
5280 f,
5281 "OPERATOR {strategy_number} ({})",
5282 display_comma_separated(op_types)
5283 )
5284 }
5285 OperatorFamilyDropItem::Function {
5286 support_number,
5287 op_types,
5288 } => {
5289 write!(
5290 f,
5291 "FUNCTION {support_number} ({})",
5292 display_comma_separated(op_types)
5293 )
5294 }
5295 }
5296 }
5297}
5298
5299#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5302#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5303#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5304pub struct AlterOperatorFamily {
5305 pub name: ObjectName,
5307 pub using: Ident,
5309 pub operation: AlterOperatorFamilyOperation,
5311}
5312
5313#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5315#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5316#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5317pub enum AlterOperatorFamilyOperation {
5318 Add {
5320 items: Vec<OperatorFamilyItem>,
5322 },
5323 Drop {
5325 items: Vec<OperatorFamilyDropItem>,
5327 },
5328 RenameTo {
5330 new_name: ObjectName,
5332 },
5333 OwnerTo(Owner),
5335 SetSchema {
5337 schema_name: ObjectName,
5339 },
5340}
5341
5342impl fmt::Display for AlterOperatorFamily {
5343 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5344 write!(
5345 f,
5346 "ALTER OPERATOR FAMILY {} USING {}",
5347 self.name, self.using
5348 )?;
5349 write!(f, " {}", self.operation)
5350 }
5351}
5352
5353impl fmt::Display for AlterOperatorFamilyOperation {
5354 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5355 match self {
5356 AlterOperatorFamilyOperation::Add { items } => {
5357 write!(f, "ADD {}", display_comma_separated(items))
5358 }
5359 AlterOperatorFamilyOperation::Drop { items } => {
5360 write!(f, "DROP {}", display_comma_separated(items))
5361 }
5362 AlterOperatorFamilyOperation::RenameTo { new_name } => {
5363 write!(f, "RENAME TO {new_name}")
5364 }
5365 AlterOperatorFamilyOperation::OwnerTo(owner) => {
5366 write!(f, "OWNER TO {owner}")
5367 }
5368 AlterOperatorFamilyOperation::SetSchema { schema_name } => {
5369 write!(f, "SET SCHEMA {schema_name}")
5370 }
5371 }
5372 }
5373}
5374
5375impl Spanned for AlterOperatorFamily {
5376 fn span(&self) -> Span {
5377 Span::empty()
5378 }
5379}
5380
5381#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5384#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5385#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5386pub struct AlterOperatorClass {
5387 pub name: ObjectName,
5389 pub using: Ident,
5391 pub operation: AlterOperatorClassOperation,
5393}
5394
5395#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5397#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5398#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5399pub enum AlterOperatorClassOperation {
5400 RenameTo {
5403 new_name: ObjectName,
5405 },
5406 OwnerTo(Owner),
5408 SetSchema {
5411 schema_name: ObjectName,
5413 },
5414}
5415
5416impl fmt::Display for AlterOperatorClass {
5417 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5418 write!(f, "ALTER OPERATOR CLASS {} USING {}", self.name, self.using)?;
5419 write!(f, " {}", self.operation)
5420 }
5421}
5422
5423impl fmt::Display for AlterOperatorClassOperation {
5424 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5425 match self {
5426 AlterOperatorClassOperation::RenameTo { new_name } => {
5427 write!(f, "RENAME TO {new_name}")
5428 }
5429 AlterOperatorClassOperation::OwnerTo(owner) => {
5430 write!(f, "OWNER TO {owner}")
5431 }
5432 AlterOperatorClassOperation::SetSchema { schema_name } => {
5433 write!(f, "SET SCHEMA {schema_name}")
5434 }
5435 }
5436 }
5437}
5438
5439impl Spanned for AlterOperatorClass {
5440 fn span(&self) -> Span {
5441 Span::empty()
5442 }
5443}
5444
5445#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5447#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5448#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5449pub struct AlterFunction {
5450 pub kind: AlterFunctionKind,
5452 pub function: FunctionDesc,
5454 pub aggregate_order_by: Option<Vec<OperateFunctionArg>>,
5458 pub aggregate_star: bool,
5462 pub operation: AlterFunctionOperation,
5464}
5465
5466#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5468#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5469#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5470pub enum AlterFunctionKind {
5471 Function,
5473 Aggregate,
5475}
5476
5477impl fmt::Display for AlterFunctionKind {
5478 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5479 match self {
5480 Self::Function => write!(f, "FUNCTION"),
5481 Self::Aggregate => write!(f, "AGGREGATE"),
5482 }
5483 }
5484}
5485
5486#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5488#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5489#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5490pub enum AlterFunctionOperation {
5491 RenameTo {
5493 new_name: Ident,
5495 },
5496 OwnerTo(Owner),
5498 SetSchema {
5500 schema_name: ObjectName,
5502 },
5503 DependsOnExtension {
5505 no: bool,
5507 extension_name: ObjectName,
5509 },
5510 Actions {
5512 actions: Vec<AlterFunctionAction>,
5514 restrict: bool,
5516 },
5517}
5518
5519#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5521#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5522#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5523pub enum AlterFunctionAction {
5524 CalledOnNull(FunctionCalledOnNull),
5526 Behavior(FunctionBehavior),
5528 Leakproof(bool),
5530 Security {
5532 external: bool,
5534 security: FunctionSecurity,
5536 },
5537 Parallel(FunctionParallel),
5539 Cost(Expr),
5541 Rows(Expr),
5543 Support(ObjectName),
5545 Set(FunctionDefinitionSetParam),
5548 Reset(ResetConfig),
5550}
5551
5552impl fmt::Display for AlterFunction {
5553 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5554 write!(f, "ALTER {} ", self.kind)?;
5555 match self.kind {
5556 AlterFunctionKind::Function => {
5557 write!(f, "{} ", self.function)?;
5558 }
5559 AlterFunctionKind::Aggregate => {
5560 write!(f, "{}(", self.function.name)?;
5561 if self.aggregate_star {
5562 write!(f, "*")?;
5563 } else {
5564 if let Some(args) = &self.function.args {
5565 write!(f, "{}", display_comma_separated(args))?;
5566 }
5567 if let Some(order_by_args) = &self.aggregate_order_by {
5568 if self
5569 .function
5570 .args
5571 .as_ref()
5572 .is_some_and(|args| !args.is_empty())
5573 {
5574 write!(f, " ")?;
5575 }
5576 write!(f, "ORDER BY {}", display_comma_separated(order_by_args))?;
5577 }
5578 }
5579 write!(f, ") ")?;
5580 }
5581 }
5582 write!(f, "{}", self.operation)
5583 }
5584}
5585
5586impl fmt::Display for AlterFunctionOperation {
5587 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5588 match self {
5589 AlterFunctionOperation::RenameTo { new_name } => {
5590 write!(f, "RENAME TO {new_name}")
5591 }
5592 AlterFunctionOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
5593 AlterFunctionOperation::SetSchema { schema_name } => {
5594 write!(f, "SET SCHEMA {schema_name}")
5595 }
5596 AlterFunctionOperation::DependsOnExtension { no, extension_name } => {
5597 if *no {
5598 write!(f, "NO DEPENDS ON EXTENSION {extension_name}")
5599 } else {
5600 write!(f, "DEPENDS ON EXTENSION {extension_name}")
5601 }
5602 }
5603 AlterFunctionOperation::Actions { actions, restrict } => {
5604 write!(f, "{}", display_separated(actions, " "))?;
5605 if *restrict {
5606 write!(f, " RESTRICT")?;
5607 }
5608 Ok(())
5609 }
5610 }
5611 }
5612}
5613
5614impl fmt::Display for AlterFunctionAction {
5615 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5616 match self {
5617 AlterFunctionAction::CalledOnNull(called_on_null) => write!(f, "{called_on_null}"),
5618 AlterFunctionAction::Behavior(behavior) => write!(f, "{behavior}"),
5619 AlterFunctionAction::Leakproof(leakproof) => {
5620 if *leakproof {
5621 write!(f, "LEAKPROOF")
5622 } else {
5623 write!(f, "NOT LEAKPROOF")
5624 }
5625 }
5626 AlterFunctionAction::Security { external, security } => {
5627 if *external {
5628 write!(f, "EXTERNAL ")?;
5629 }
5630 write!(f, "{security}")
5631 }
5632 AlterFunctionAction::Parallel(parallel) => write!(f, "{parallel}"),
5633 AlterFunctionAction::Cost(execution_cost) => write!(f, "COST {execution_cost}"),
5634 AlterFunctionAction::Rows(result_rows) => write!(f, "ROWS {result_rows}"),
5635 AlterFunctionAction::Support(support_function) => {
5636 write!(f, "SUPPORT {support_function}")
5637 }
5638 AlterFunctionAction::Set(set_param) => write!(f, "{set_param}"),
5639 AlterFunctionAction::Reset(reset_config) => match reset_config {
5640 ResetConfig::ALL => write!(f, "RESET ALL"),
5641 ResetConfig::ConfigName(name) => write!(f, "RESET {name}"),
5642 },
5643 }
5644 }
5645}
5646
5647impl Spanned for AlterFunction {
5648 fn span(&self) -> Span {
5649 Span::empty()
5650 }
5651}
5652
5653#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5657#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5658#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5659pub enum TextSearchObjectType {
5660 Dictionary,
5662 Configuration,
5664 Template,
5666 Parser,
5668}
5669
5670impl fmt::Display for TextSearchObjectType {
5671 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5672 match self {
5673 TextSearchObjectType::Dictionary => write!(f, "DICTIONARY"),
5674 TextSearchObjectType::Configuration => write!(f, "CONFIGURATION"),
5675 TextSearchObjectType::Template => write!(f, "TEMPLATE"),
5676 TextSearchObjectType::Parser => write!(f, "PARSER"),
5677 }
5678 }
5679}
5680
5681#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5685#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5686#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5687pub struct CreateTextSearch {
5688 pub object_type: TextSearchObjectType,
5690 pub name: ObjectName,
5692 pub options: Vec<SqlOption>,
5694}
5695
5696impl fmt::Display for CreateTextSearch {
5697 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5698 write!(
5699 f,
5700 "CREATE TEXT SEARCH {} {} ({})",
5701 self.object_type,
5702 self.name,
5703 display_comma_separated(&self.options)
5704 )
5705 }
5706}
5707
5708impl Spanned for CreateTextSearch {
5709 fn span(&self) -> Span {
5710 Span::empty()
5711 }
5712}
5713
5714#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5718#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5719#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5720pub struct AlterTextSearchOption {
5721 pub key: Ident,
5723 pub value: Option<Expr>,
5725}
5726
5727impl fmt::Display for AlterTextSearchOption {
5728 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5729 match &self.value {
5730 Some(value) => write!(f, "{} = {}", self.key, value),
5731 None => write!(f, "{}", self.key),
5732 }
5733 }
5734}
5735
5736#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5740#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5741#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5742pub enum AlterTextSearchOperation {
5743 RenameTo {
5745 new_name: Ident,
5747 },
5748 OwnerTo(Owner),
5750 SetSchema {
5752 schema_name: ObjectName,
5754 },
5755 SetOptions {
5757 options: Vec<AlterTextSearchOption>,
5759 },
5760}
5761
5762impl fmt::Display for AlterTextSearchOperation {
5763 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5764 match self {
5765 AlterTextSearchOperation::RenameTo { new_name } => write!(f, "RENAME TO {new_name}"),
5766 AlterTextSearchOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
5767 AlterTextSearchOperation::SetSchema { schema_name } => {
5768 write!(f, "SET SCHEMA {schema_name}")
5769 }
5770 AlterTextSearchOperation::SetOptions { options } => {
5771 write!(f, "({})", display_comma_separated(options))
5772 }
5773 }
5774 }
5775}
5776
5777#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5781#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5782#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5783pub struct AlterTextSearch {
5784 pub object_type: TextSearchObjectType,
5786 pub name: ObjectName,
5788 pub operation: AlterTextSearchOperation,
5790}
5791
5792impl fmt::Display for AlterTextSearch {
5793 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5794 write!(
5795 f,
5796 "ALTER TEXT SEARCH {} {} {}",
5797 self.object_type, self.name, self.operation
5798 )
5799 }
5800}
5801
5802impl Spanned for AlterTextSearch {
5803 fn span(&self) -> Span {
5804 Span::empty()
5805 }
5806}
5807
5808#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5812#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5813#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5814pub struct CreatePolicy {
5815 pub name: Ident,
5817 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5819 pub table_name: ObjectName,
5820 pub policy_type: Option<CreatePolicyType>,
5822 pub command: Option<CreatePolicyCommand>,
5824 pub to: Option<Vec<Owner>>,
5826 pub using: Option<Expr>,
5828 pub with_check: Option<Expr>,
5830}
5831
5832impl fmt::Display for CreatePolicy {
5833 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5834 write!(
5835 f,
5836 "CREATE POLICY {name} ON {table_name}",
5837 name = self.name,
5838 table_name = self.table_name,
5839 )?;
5840 if let Some(ref policy_type) = self.policy_type {
5841 write!(f, " AS {policy_type}")?;
5842 }
5843 if let Some(ref command) = self.command {
5844 write!(f, " FOR {command}")?;
5845 }
5846 if let Some(ref to) = self.to {
5847 write!(f, " TO {}", display_comma_separated(to))?;
5848 }
5849 if let Some(ref using) = self.using {
5850 write!(f, " USING ({using})")?;
5851 }
5852 if let Some(ref with_check) = self.with_check {
5853 write!(f, " WITH CHECK ({with_check})")?;
5854 }
5855 Ok(())
5856 }
5857}
5858
5859#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5865#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5866#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5867pub enum CreatePolicyType {
5868 Permissive,
5870 Restrictive,
5872}
5873
5874impl fmt::Display for CreatePolicyType {
5875 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5876 match self {
5877 CreatePolicyType::Permissive => write!(f, "PERMISSIVE"),
5878 CreatePolicyType::Restrictive => write!(f, "RESTRICTIVE"),
5879 }
5880 }
5881}
5882
5883#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5889#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5890#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5891pub enum CreatePolicyCommand {
5892 All,
5894 Select,
5896 Insert,
5898 Update,
5900 Delete,
5902}
5903
5904impl fmt::Display for CreatePolicyCommand {
5905 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5906 match self {
5907 CreatePolicyCommand::All => write!(f, "ALL"),
5908 CreatePolicyCommand::Select => write!(f, "SELECT"),
5909 CreatePolicyCommand::Insert => write!(f, "INSERT"),
5910 CreatePolicyCommand::Update => write!(f, "UPDATE"),
5911 CreatePolicyCommand::Delete => write!(f, "DELETE"),
5912 }
5913 }
5914}
5915
5916#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5920#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5921#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5922pub struct DropPolicy {
5923 pub if_exists: bool,
5925 pub name: Ident,
5927 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5929 pub table_name: ObjectName,
5930 pub drop_behavior: Option<DropBehavior>,
5932}
5933
5934impl fmt::Display for DropPolicy {
5935 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5936 write!(
5937 f,
5938 "DROP POLICY {if_exists}{name} ON {table_name}",
5939 if_exists = if self.if_exists { "IF EXISTS " } else { "" },
5940 name = self.name,
5941 table_name = self.table_name
5942 )?;
5943 if let Some(ref behavior) = self.drop_behavior {
5944 write!(f, " {behavior}")?;
5945 }
5946 Ok(())
5947 }
5948}
5949
5950impl From<CreatePolicy> for crate::ast::Statement {
5951 fn from(v: CreatePolicy) -> Self {
5952 crate::ast::Statement::CreatePolicy(v)
5953 }
5954}
5955
5956impl From<DropPolicy> for crate::ast::Statement {
5957 fn from(v: DropPolicy) -> Self {
5958 crate::ast::Statement::DropPolicy(v)
5959 }
5960}
5961
5962#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5969#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5970#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5971pub struct AlterPolicy {
5972 pub name: Ident,
5974 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5976 pub table_name: ObjectName,
5977 pub operation: AlterPolicyOperation,
5979}
5980
5981impl fmt::Display for AlterPolicy {
5982 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5983 write!(
5984 f,
5985 "ALTER POLICY {name} ON {table_name}{operation}",
5986 name = self.name,
5987 table_name = self.table_name,
5988 operation = self.operation
5989 )
5990 }
5991}
5992
5993impl From<AlterPolicy> for crate::ast::Statement {
5994 fn from(v: AlterPolicy) -> Self {
5995 crate::ast::Statement::AlterPolicy(v)
5996 }
5997}