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 pub fulltext_or_spatial: Option<FullTextOrSpatialKind>,
2863}
2864
2865#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Copy)]
2869#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2870#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2871pub enum FullTextOrSpatialKind {
2872 Fulltext,
2874 Spatial,
2876}
2877
2878impl fmt::Display for FullTextOrSpatialKind {
2879 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2880 match self {
2881 FullTextOrSpatialKind::Fulltext => f.write_str("FULLTEXT"),
2882 FullTextOrSpatialKind::Spatial => f.write_str("SPATIAL"),
2883 }
2884 }
2885}
2886
2887impl fmt::Display for CreateIndex {
2888 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2889 let kind_prefix = match self.fulltext_or_spatial {
2890 Some(kind) => format!("{kind} "),
2891 None => String::new(),
2892 };
2893 write!(
2894 f,
2895 "CREATE {kind_prefix}{unique}INDEX {concurrently}{async_}{if_not_exists}",
2896 unique = if self.unique { "UNIQUE " } else { "" },
2897 concurrently = if self.concurrently {
2898 "CONCURRENTLY "
2899 } else {
2900 ""
2901 },
2902 async_ = if self.r#async { "ASYNC " } else { "" },
2903 if_not_exists = if self.if_not_exists {
2904 "IF NOT EXISTS "
2905 } else {
2906 ""
2907 },
2908 )?;
2909 if let Some(value) = &self.name {
2910 write!(f, "{value} ")?;
2911 }
2912 write!(f, "ON {}", self.table_name)?;
2913 if let Some(value) = &self.using {
2914 write!(f, " USING {value} ")?;
2915 }
2916 write!(f, "({})", display_comma_separated(&self.columns))?;
2917 if !self.include.is_empty() {
2918 write!(f, " INCLUDE ({})", display_comma_separated(&self.include))?;
2919 }
2920 if let Some(value) = self.nulls_distinct {
2921 if value {
2922 write!(f, " NULLS DISTINCT")?;
2923 } else {
2924 write!(f, " NULLS NOT DISTINCT")?;
2925 }
2926 }
2927 if !self.with.is_empty() {
2928 write!(f, " WITH ({})", display_comma_separated(&self.with))?;
2929 }
2930 if let Some(predicate) = &self.predicate {
2931 write!(f, " WHERE {predicate}")?;
2932 }
2933 if !self.index_options.is_empty() {
2934 write!(f, " {}", display_separated(&self.index_options, " "))?;
2935 }
2936 if !self.alter_options.is_empty() {
2937 write!(f, " {}", display_separated(&self.alter_options, " "))?;
2938 }
2939 Ok(())
2940 }
2941}
2942
2943#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2945#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2946#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2947pub struct CreateTable {
2948 pub or_replace: bool,
2950 pub temporary: bool,
2952 pub unlogged: bool,
2954 pub external: bool,
2956 pub dynamic: bool,
2958 pub global: Option<bool>,
2960 pub if_not_exists: bool,
2962 pub transient: bool,
2964 pub volatile: bool,
2966 pub iceberg: bool,
2968 pub snapshot: bool,
2971 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2973 pub name: ObjectName,
2974 pub columns: Vec<ColumnDef>,
2976 pub constraints: Vec<TableConstraint>,
2978 pub hive_distribution: HiveDistributionStyle,
2980 pub hive_formats: Option<HiveFormat>,
2982 pub table_options: CreateTableOptions,
2984 pub file_format: Option<FileFormat>,
2986 pub location: Option<String>,
2988 pub query: Option<Box<Query>>,
2990 pub without_rowid: bool,
2992 pub like: Option<CreateTableLikeKind>,
2994 pub clone: Option<ObjectName>,
2996 pub version: Option<TableVersion>,
2998 pub comment: Option<CommentDef>,
3002 pub on_commit: Option<OnCommit>,
3005 pub on_cluster: Option<Ident>,
3008 pub primary_key: Option<Box<Expr>>,
3011 pub order_by: Option<OneOrManyWithParens<Expr>>,
3015 pub partition_by: Option<Box<Expr>>,
3018 pub cluster_by: Option<WrappedCollection<Vec<Expr>>>,
3023 pub clustered_by: Option<ClusteredBy>,
3026 pub inherits: Option<Vec<ObjectName>>,
3031 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3035 pub partition_of: Option<ObjectName>,
3036 pub for_values: Option<ForValues>,
3039 pub strict: bool,
3043 pub copy_grants: bool,
3046 pub enable_schema_evolution: Option<bool>,
3049 pub change_tracking: Option<bool>,
3052 pub data_retention_time_in_days: Option<u64>,
3055 pub max_data_extension_time_in_days: Option<u64>,
3058 pub default_ddl_collation: Option<String>,
3061 pub with_aggregation_policy: Option<ObjectName>,
3064 pub with_row_access_policy: Option<RowAccessPolicy>,
3067 pub with_storage_lifecycle_policy: Option<StorageLifecyclePolicy>,
3070 pub with_tags: Option<Vec<Tag>>,
3073 pub external_volume: Option<String>,
3076 pub with_connection: Option<ObjectName>,
3079 pub base_location: Option<String>,
3082 pub catalog: Option<String>,
3085 pub catalog_sync: Option<String>,
3088 pub storage_serialization_policy: Option<StorageSerializationPolicy>,
3091 pub target_lag: Option<String>,
3094 pub warehouse: Option<Ident>,
3097 pub refresh_mode: Option<RefreshModeKind>,
3100 pub initialize: Option<InitializeKind>,
3103 pub require_user: bool,
3106 pub diststyle: Option<DistStyle>,
3109 pub distkey: Option<Expr>,
3112 pub sortkey: Option<Vec<Expr>>,
3115 pub backup: Option<bool>,
3118 pub multiset: Option<bool>,
3123 pub fallback: Option<bool>,
3128 pub with_data: Option<WithData>,
3132}
3133
3134impl fmt::Display for CreateTable {
3135 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3136 write!(
3144 f,
3145 "CREATE {or_replace}{external}{global}{multiset}{temporary}{unlogged}{transient}{volatile}{dynamic}{iceberg}{snapshot}TABLE {if_not_exists}{name}",
3146 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3147 external = if self.external { "EXTERNAL " } else { "" },
3148 snapshot = if self.snapshot { "SNAPSHOT " } else { "" },
3149 global = self.global
3150 .map(|global| {
3151 if global {
3152 "GLOBAL "
3153 } else {
3154 "LOCAL "
3155 }
3156 })
3157 .unwrap_or(""),
3158 if_not_exists = if self.if_not_exists { "IF NOT EXISTS " } else { "" },
3159 multiset = self
3160 .multiset
3161 .map(|m| if m { "MULTISET " } else { "SET " })
3162 .unwrap_or(""),
3163 temporary = if self.temporary { "TEMPORARY " } else { "" },
3164 unlogged = if self.unlogged { "UNLOGGED " } else { "" },
3165 transient = if self.transient { "TRANSIENT " } else { "" },
3166 volatile = if self.volatile { "VOLATILE " } else { "" },
3167 iceberg = if self.iceberg { "ICEBERG " } else { "" },
3168 dynamic = if self.dynamic { "DYNAMIC " } else { "" },
3169 name = self.name,
3170 )?;
3171 if let Some(fallback) = self.fallback {
3172 write!(f, ", {}", if fallback { "FALLBACK" } else { "NO FALLBACK" })?;
3173 }
3174 if let Some(partition_of) = &self.partition_of {
3175 write!(f, " PARTITION OF {partition_of}")?;
3176 }
3177 if let Some(on_cluster) = &self.on_cluster {
3178 write!(f, " ON CLUSTER {on_cluster}")?;
3179 }
3180 if !self.columns.is_empty() || !self.constraints.is_empty() {
3181 f.write_str(" (")?;
3182 NewLine.fmt(f)?;
3183 Indent(DisplayCommaSeparated(&self.columns)).fmt(f)?;
3184 if !self.columns.is_empty() && !self.constraints.is_empty() {
3185 f.write_str(",")?;
3186 SpaceOrNewline.fmt(f)?;
3187 }
3188 Indent(DisplayCommaSeparated(&self.constraints)).fmt(f)?;
3189 NewLine.fmt(f)?;
3190 f.write_str(")")?;
3191 } else if self.query.is_none()
3192 && self.like.is_none()
3193 && self.clone.is_none()
3194 && self.partition_of.is_none()
3195 {
3196 f.write_str(" ()")?;
3198 } else if let Some(CreateTableLikeKind::Parenthesized(like_in_columns_list)) = &self.like {
3199 write!(f, " ({like_in_columns_list})")?;
3200 }
3201 if let Some(for_values) = &self.for_values {
3202 write!(f, " {for_values}")?;
3203 }
3204
3205 if let Some(comment) = &self.comment {
3208 write!(f, " COMMENT '{comment}'")?;
3209 }
3210
3211 if self.without_rowid {
3213 write!(f, " WITHOUT ROWID")?;
3214 }
3215
3216 if let Some(CreateTableLikeKind::Plain(like)) = &self.like {
3217 write!(f, " {like}")?;
3218 }
3219
3220 if let Some(c) = &self.clone {
3221 write!(f, " CLONE {c}")?;
3222 }
3223
3224 if let Some(version) = &self.version {
3225 write!(f, " {version}")?;
3226 }
3227
3228 match &self.hive_distribution {
3229 HiveDistributionStyle::PARTITIONED { columns } => {
3230 write!(f, " PARTITIONED BY ({})", display_comma_separated(columns))?;
3231 }
3232 HiveDistributionStyle::SKEWED {
3233 columns,
3234 on,
3235 stored_as_directories,
3236 } => {
3237 write!(
3238 f,
3239 " SKEWED BY ({})) ON ({})",
3240 display_comma_separated(columns),
3241 display_comma_separated(on)
3242 )?;
3243 if *stored_as_directories {
3244 write!(f, " STORED AS DIRECTORIES")?;
3245 }
3246 }
3247 _ => (),
3248 }
3249
3250 if let Some(clustered_by) = &self.clustered_by {
3251 write!(f, " {clustered_by}")?;
3252 }
3253
3254 if let Some(HiveFormat {
3255 row_format,
3256 serde_properties,
3257 storage,
3258 location,
3259 }) = &self.hive_formats
3260 {
3261 match row_format {
3262 Some(HiveRowFormat::SERDE { class }) => write!(f, " ROW FORMAT SERDE '{class}'")?,
3263 Some(HiveRowFormat::DELIMITED { delimiters }) => {
3264 write!(f, " ROW FORMAT DELIMITED")?;
3265 if !delimiters.is_empty() {
3266 write!(f, " {}", display_separated(delimiters, " "))?;
3267 }
3268 }
3269 None => (),
3270 }
3271 match storage {
3272 Some(HiveIOFormat::IOF {
3273 input_format,
3274 output_format,
3275 }) => write!(
3276 f,
3277 " STORED AS INPUTFORMAT {input_format} OUTPUTFORMAT {output_format}"
3278 )?,
3279 Some(HiveIOFormat::FileFormat { format }) if !self.external => {
3280 write!(f, " STORED AS {format}")?
3281 }
3282 Some(HiveIOFormat::Using { format }) => write!(f, " USING {format}")?,
3283 _ => (),
3284 }
3285 if let Some(serde_properties) = serde_properties.as_ref() {
3286 write!(
3287 f,
3288 " WITH SERDEPROPERTIES ({})",
3289 display_comma_separated(serde_properties)
3290 )?;
3291 }
3292 if !self.external {
3293 if let Some(loc) = location {
3294 write!(f, " LOCATION '{loc}'")?;
3295 }
3296 }
3297 }
3298 if self.external {
3299 if let Some(file_format) = self.file_format {
3300 write!(f, " STORED AS {file_format}")?;
3301 }
3302 if let Some(location) = &self.location {
3303 write!(f, " LOCATION '{location}'")?;
3304 }
3305 }
3306
3307 match &self.table_options {
3308 options @ CreateTableOptions::With(_)
3309 | options @ CreateTableOptions::Plain(_)
3310 | options @ CreateTableOptions::TableProperties(_) => write!(f, " {options}")?,
3311 _ => (),
3312 }
3313
3314 if let Some(primary_key) = &self.primary_key {
3315 write!(f, " PRIMARY KEY {primary_key}")?;
3316 }
3317 if let Some(order_by) = &self.order_by {
3318 write!(f, " ORDER BY {order_by}")?;
3319 }
3320 if let Some(inherits) = &self.inherits {
3321 write!(f, " INHERITS ({})", display_comma_separated(inherits))?;
3322 }
3323 if let Some(partition_by) = self.partition_by.as_ref() {
3324 write!(f, " PARTITION BY {partition_by}")?;
3325 }
3326 if let Some(cluster_by) = self.cluster_by.as_ref() {
3327 write!(f, " CLUSTER BY {cluster_by}")?;
3328 }
3329 if let Some(with_connection) = &self.with_connection {
3330 write!(f, " WITH CONNECTION {with_connection}")?;
3331 }
3332 if let options @ CreateTableOptions::Options(_) = &self.table_options {
3333 write!(f, " {options}")?;
3334 }
3335 if let Some(external_volume) = self.external_volume.as_ref() {
3336 write!(f, " EXTERNAL_VOLUME='{external_volume}'")?;
3337 }
3338
3339 if let Some(catalog) = self.catalog.as_ref() {
3340 write!(f, " CATALOG='{catalog}'")?;
3341 }
3342
3343 if self.iceberg {
3344 if let Some(base_location) = self.base_location.as_ref() {
3345 write!(f, " BASE_LOCATION='{base_location}'")?;
3346 }
3347 }
3348
3349 if let Some(catalog_sync) = self.catalog_sync.as_ref() {
3350 write!(f, " CATALOG_SYNC='{catalog_sync}'")?;
3351 }
3352
3353 if let Some(storage_serialization_policy) = self.storage_serialization_policy.as_ref() {
3354 write!(
3355 f,
3356 " STORAGE_SERIALIZATION_POLICY={storage_serialization_policy}"
3357 )?;
3358 }
3359
3360 if self.copy_grants {
3361 write!(f, " COPY GRANTS")?;
3362 }
3363
3364 if let Some(is_enabled) = self.enable_schema_evolution {
3365 write!(
3366 f,
3367 " ENABLE_SCHEMA_EVOLUTION={}",
3368 if is_enabled { "TRUE" } else { "FALSE" }
3369 )?;
3370 }
3371
3372 if let Some(is_enabled) = self.change_tracking {
3373 write!(
3374 f,
3375 " CHANGE_TRACKING={}",
3376 if is_enabled { "TRUE" } else { "FALSE" }
3377 )?;
3378 }
3379
3380 if let Some(data_retention_time_in_days) = self.data_retention_time_in_days {
3381 write!(
3382 f,
3383 " DATA_RETENTION_TIME_IN_DAYS={data_retention_time_in_days}",
3384 )?;
3385 }
3386
3387 if let Some(max_data_extension_time_in_days) = self.max_data_extension_time_in_days {
3388 write!(
3389 f,
3390 " MAX_DATA_EXTENSION_TIME_IN_DAYS={max_data_extension_time_in_days}",
3391 )?;
3392 }
3393
3394 if let Some(default_ddl_collation) = &self.default_ddl_collation {
3395 write!(f, " DEFAULT_DDL_COLLATION='{default_ddl_collation}'",)?;
3396 }
3397
3398 if let Some(with_aggregation_policy) = &self.with_aggregation_policy {
3399 write!(f, " WITH AGGREGATION POLICY {with_aggregation_policy}",)?;
3400 }
3401
3402 if let Some(row_access_policy) = &self.with_row_access_policy {
3403 write!(f, " {row_access_policy}",)?;
3404 }
3405
3406 if let Some(storage_lifecycle_policy) = &self.with_storage_lifecycle_policy {
3407 write!(f, " {storage_lifecycle_policy}",)?;
3408 }
3409
3410 if let Some(tag) = &self.with_tags {
3411 write!(f, " WITH TAG ({})", display_comma_separated(tag.as_slice()))?;
3412 }
3413
3414 if let Some(target_lag) = &self.target_lag {
3415 write!(f, " TARGET_LAG='{target_lag}'")?;
3416 }
3417
3418 if let Some(warehouse) = &self.warehouse {
3419 write!(f, " WAREHOUSE={warehouse}")?;
3420 }
3421
3422 if let Some(refresh_mode) = &self.refresh_mode {
3423 write!(f, " REFRESH_MODE={refresh_mode}")?;
3424 }
3425
3426 if let Some(initialize) = &self.initialize {
3427 write!(f, " INITIALIZE={initialize}")?;
3428 }
3429
3430 if self.require_user {
3431 write!(f, " REQUIRE USER")?;
3432 }
3433
3434 if self.on_commit.is_some() {
3435 let on_commit = match self.on_commit {
3436 Some(OnCommit::DeleteRows) => "ON COMMIT DELETE ROWS",
3437 Some(OnCommit::PreserveRows) => "ON COMMIT PRESERVE ROWS",
3438 Some(OnCommit::Drop) => "ON COMMIT DROP",
3439 None => "",
3440 };
3441 write!(f, " {on_commit}")?;
3442 }
3443 if self.strict {
3444 write!(f, " STRICT")?;
3445 }
3446 if let Some(backup) = self.backup {
3447 write!(f, " BACKUP {}", if backup { "YES" } else { "NO" })?;
3448 }
3449 if let Some(diststyle) = &self.diststyle {
3450 write!(f, " DISTSTYLE {diststyle}")?;
3451 }
3452 if let Some(distkey) = &self.distkey {
3453 write!(f, " DISTKEY({distkey})")?;
3454 }
3455 if let Some(sortkey) = &self.sortkey {
3456 write!(f, " SORTKEY({})", display_comma_separated(sortkey))?;
3457 }
3458 if let Some(query) = &self.query {
3459 write!(f, " AS {query}")?;
3460 }
3461 if let Some(with_data) = &self.with_data {
3462 write!(f, " {with_data}")?;
3463 }
3464 Ok(())
3465 }
3466}
3467
3468#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
3472#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3473#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3474pub struct WithData {
3475 pub data: bool,
3477 pub statistics: Option<bool>,
3480}
3481
3482impl fmt::Display for WithData {
3483 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3484 f.write_str("WITH ")?;
3485 if !self.data {
3486 f.write_str("NO ")?;
3487 }
3488 f.write_str("DATA")?;
3489 if let Some(stats) = self.statistics {
3490 f.write_str(" AND ")?;
3491 if !stats {
3492 f.write_str("NO ")?;
3493 }
3494 f.write_str("STATISTICS")?;
3495 }
3496 Ok(())
3497 }
3498}
3499
3500#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3506#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3507#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3508pub enum ForValues {
3509 In(Vec<Expr>),
3511 From {
3513 from: Vec<PartitionBoundValue>,
3515 to: Vec<PartitionBoundValue>,
3517 },
3518 With {
3520 modulus: u64,
3522 remainder: u64,
3524 },
3525 Default,
3527}
3528
3529impl fmt::Display for ForValues {
3530 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3531 match self {
3532 ForValues::In(values) => {
3533 write!(f, "FOR VALUES IN ({})", display_comma_separated(values))
3534 }
3535 ForValues::From { from, to } => {
3536 write!(
3537 f,
3538 "FOR VALUES FROM ({}) TO ({})",
3539 display_comma_separated(from),
3540 display_comma_separated(to)
3541 )
3542 }
3543 ForValues::With { modulus, remainder } => {
3544 write!(
3545 f,
3546 "FOR VALUES WITH (MODULUS {modulus}, REMAINDER {remainder})"
3547 )
3548 }
3549 ForValues::Default => write!(f, "DEFAULT"),
3550 }
3551 }
3552}
3553
3554#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3559#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3560#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3561pub enum PartitionBoundValue {
3562 Expr(Expr),
3564 MinValue,
3566 MaxValue,
3568}
3569
3570impl fmt::Display for PartitionBoundValue {
3571 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3572 match self {
3573 PartitionBoundValue::Expr(expr) => write!(f, "{expr}"),
3574 PartitionBoundValue::MinValue => write!(f, "MINVALUE"),
3575 PartitionBoundValue::MaxValue => write!(f, "MAXVALUE"),
3576 }
3577 }
3578}
3579
3580#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3584#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3585#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3586pub enum DistStyle {
3587 Auto,
3589 Even,
3591 Key,
3593 All,
3595}
3596
3597impl fmt::Display for DistStyle {
3598 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3599 match self {
3600 DistStyle::Auto => write!(f, "AUTO"),
3601 DistStyle::Even => write!(f, "EVEN"),
3602 DistStyle::Key => write!(f, "KEY"),
3603 DistStyle::All => write!(f, "ALL"),
3604 }
3605 }
3606}
3607
3608#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3609#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3610#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3611pub struct CreateDomain {
3624 pub name: ObjectName,
3626 pub data_type: DataType,
3628 pub collation: Option<Ident>,
3630 pub default: Option<Expr>,
3632 pub constraints: Vec<TableConstraint>,
3634}
3635
3636impl fmt::Display for CreateDomain {
3637 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3638 write!(
3639 f,
3640 "CREATE DOMAIN {name} AS {data_type}",
3641 name = self.name,
3642 data_type = self.data_type
3643 )?;
3644 if let Some(collation) = &self.collation {
3645 write!(f, " COLLATE {collation}")?;
3646 }
3647 if let Some(default) = &self.default {
3648 write!(f, " DEFAULT {default}")?;
3649 }
3650 if !self.constraints.is_empty() {
3651 write!(f, " {}", display_separated(&self.constraints, " "))?;
3652 }
3653 Ok(())
3654 }
3655}
3656
3657#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3659#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3660#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3661pub enum FunctionReturnType {
3662 DataType(DataType),
3664 SetOf(DataType),
3668}
3669
3670impl fmt::Display for FunctionReturnType {
3671 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3672 match self {
3673 FunctionReturnType::DataType(data_type) => write!(f, "{data_type}"),
3674 FunctionReturnType::SetOf(data_type) => write!(f, "SETOF {data_type}"),
3675 }
3676 }
3677}
3678
3679#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3680#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3681#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3682pub struct CreateFunction {
3684 pub or_alter: bool,
3688 pub or_replace: bool,
3690 pub temporary: bool,
3692 pub if_not_exists: bool,
3694 pub name: ObjectName,
3696 pub args: Option<Vec<OperateFunctionArg>>,
3698 pub return_type: Option<FunctionReturnType>,
3700 pub function_body: Option<CreateFunctionBody>,
3708 pub behavior: Option<FunctionBehavior>,
3714 pub called_on_null: Option<FunctionCalledOnNull>,
3718 pub parallel: Option<FunctionParallel>,
3722 pub security: Option<FunctionSecurity>,
3726 pub set_params: Vec<FunctionDefinitionSetParam>,
3730 pub using: Option<CreateFunctionUsing>,
3732 pub language: Option<Ident>,
3740 pub determinism_specifier: Option<FunctionDeterminismSpecifier>,
3744 pub options: Option<Vec<SqlOption>>,
3748 pub remote_connection: Option<ObjectName>,
3758}
3759
3760impl fmt::Display for CreateFunction {
3761 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3762 write!(
3763 f,
3764 "CREATE {or_alter}{or_replace}{temp}FUNCTION {if_not_exists}{name}",
3765 name = self.name,
3766 temp = if self.temporary { "TEMPORARY " } else { "" },
3767 or_alter = if self.or_alter { "OR ALTER " } else { "" },
3768 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3769 if_not_exists = if self.if_not_exists {
3770 "IF NOT EXISTS "
3771 } else {
3772 ""
3773 },
3774 )?;
3775 if let Some(args) = &self.args {
3776 write!(f, "({})", display_comma_separated(args))?;
3777 }
3778 if let Some(return_type) = &self.return_type {
3779 write!(f, " RETURNS {return_type}")?;
3780 }
3781 if let Some(determinism_specifier) = &self.determinism_specifier {
3782 write!(f, " {determinism_specifier}")?;
3783 }
3784 if let Some(language) = &self.language {
3785 write!(f, " LANGUAGE {language}")?;
3786 }
3787 if let Some(behavior) = &self.behavior {
3788 write!(f, " {behavior}")?;
3789 }
3790 if let Some(called_on_null) = &self.called_on_null {
3791 write!(f, " {called_on_null}")?;
3792 }
3793 if let Some(parallel) = &self.parallel {
3794 write!(f, " {parallel}")?;
3795 }
3796 if let Some(security) = &self.security {
3797 write!(f, " {security}")?;
3798 }
3799 for set_param in &self.set_params {
3800 write!(f, " {set_param}")?;
3801 }
3802 if let Some(remote_connection) = &self.remote_connection {
3803 write!(f, " REMOTE WITH CONNECTION {remote_connection}")?;
3804 }
3805 if let Some(CreateFunctionBody::AsBeforeOptions { body, link_symbol }) = &self.function_body
3806 {
3807 write!(f, " AS {body}")?;
3808 if let Some(link_symbol) = link_symbol {
3809 write!(f, ", {link_symbol}")?;
3810 }
3811 }
3812 if let Some(CreateFunctionBody::Return(function_body)) = &self.function_body {
3813 write!(f, " RETURN {function_body}")?;
3814 }
3815 if let Some(CreateFunctionBody::AsReturnExpr(function_body)) = &self.function_body {
3816 write!(f, " AS RETURN {function_body}")?;
3817 }
3818 if let Some(CreateFunctionBody::AsReturnSelect(function_body)) = &self.function_body {
3819 write!(f, " AS RETURN {function_body}")?;
3820 }
3821 if let Some(using) = &self.using {
3822 write!(f, " {using}")?;
3823 }
3824 if let Some(options) = &self.options {
3825 write!(
3826 f,
3827 " OPTIONS({})",
3828 display_comma_separated(options.as_slice())
3829 )?;
3830 }
3831 if let Some(CreateFunctionBody::AsAfterOptions(function_body)) = &self.function_body {
3832 write!(f, " AS {function_body}")?;
3833 }
3834 if let Some(CreateFunctionBody::AsBeginEnd(bes)) = &self.function_body {
3835 write!(f, " AS {bes}")?;
3836 }
3837 Ok(())
3838 }
3839}
3840
3841#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3851#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3852#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3853pub struct CreateConnector {
3854 pub name: Ident,
3856 pub if_not_exists: bool,
3858 pub connector_type: Option<String>,
3860 pub url: Option<String>,
3862 pub comment: Option<CommentDef>,
3864 pub with_dcproperties: Option<Vec<SqlOption>>,
3866}
3867
3868impl fmt::Display for CreateConnector {
3869 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3870 write!(
3871 f,
3872 "CREATE CONNECTOR {if_not_exists}{name}",
3873 if_not_exists = if self.if_not_exists {
3874 "IF NOT EXISTS "
3875 } else {
3876 ""
3877 },
3878 name = self.name,
3879 )?;
3880
3881 if let Some(connector_type) = &self.connector_type {
3882 write!(f, " TYPE '{connector_type}'")?;
3883 }
3884
3885 if let Some(url) = &self.url {
3886 write!(f, " URL '{url}'")?;
3887 }
3888
3889 if let Some(comment) = &self.comment {
3890 write!(f, " COMMENT = '{comment}'")?;
3891 }
3892
3893 if let Some(with_dcproperties) = &self.with_dcproperties {
3894 write!(
3895 f,
3896 " WITH DCPROPERTIES({})",
3897 display_comma_separated(with_dcproperties)
3898 )?;
3899 }
3900
3901 Ok(())
3902 }
3903}
3904
3905#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3910#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3911#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3912pub enum AlterSchemaOperation {
3913 SetDefaultCollate {
3915 collate: Expr,
3917 },
3918 AddReplica {
3920 replica: Ident,
3922 options: Option<Vec<SqlOption>>,
3924 },
3925 DropReplica {
3927 replica: Ident,
3929 },
3930 SetOptionsParens {
3932 options: Vec<SqlOption>,
3934 },
3935 Rename {
3937 name: ObjectName,
3939 },
3940 OwnerTo {
3942 owner: Owner,
3944 },
3945}
3946
3947impl fmt::Display for AlterSchemaOperation {
3948 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3949 match self {
3950 AlterSchemaOperation::SetDefaultCollate { collate } => {
3951 write!(f, "SET DEFAULT COLLATE {collate}")
3952 }
3953 AlterSchemaOperation::AddReplica { replica, options } => {
3954 write!(f, "ADD REPLICA {replica}")?;
3955 if let Some(options) = options {
3956 write!(f, " OPTIONS ({})", display_comma_separated(options))?;
3957 }
3958 Ok(())
3959 }
3960 AlterSchemaOperation::DropReplica { replica } => write!(f, "DROP REPLICA {replica}"),
3961 AlterSchemaOperation::SetOptionsParens { options } => {
3962 write!(f, "SET OPTIONS ({})", display_comma_separated(options))
3963 }
3964 AlterSchemaOperation::Rename { name } => write!(f, "RENAME TO {name}"),
3965 AlterSchemaOperation::OwnerTo { owner } => write!(f, "OWNER TO {owner}"),
3966 }
3967 }
3968}
3969#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3975#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3976#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3977pub enum RenameTableNameKind {
3978 As(ObjectName),
3980 To(ObjectName),
3982}
3983
3984impl fmt::Display for RenameTableNameKind {
3985 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3986 match self {
3987 RenameTableNameKind::As(name) => write!(f, "AS {name}"),
3988 RenameTableNameKind::To(name) => write!(f, "TO {name}"),
3989 }
3990 }
3991}
3992
3993#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3994#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3995#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3996pub struct AlterSchema {
3998 pub name: ObjectName,
4000 pub if_exists: bool,
4002 pub operations: Vec<AlterSchemaOperation>,
4004}
4005
4006impl fmt::Display for AlterSchema {
4007 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4008 write!(f, "ALTER SCHEMA ")?;
4009 if self.if_exists {
4010 write!(f, "IF EXISTS ")?;
4011 }
4012 write!(f, "{}", self.name)?;
4013 for operation in &self.operations {
4014 write!(f, " {operation}")?;
4015 }
4016
4017 Ok(())
4018 }
4019}
4020
4021impl Spanned for RenameTableNameKind {
4022 fn span(&self) -> Span {
4023 match self {
4024 RenameTableNameKind::As(name) => name.span(),
4025 RenameTableNameKind::To(name) => name.span(),
4026 }
4027 }
4028}
4029
4030#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
4031#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4032#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4033pub enum TriggerObjectKind {
4035 For(TriggerObject),
4037 ForEach(TriggerObject),
4039}
4040
4041impl Display for TriggerObjectKind {
4042 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4043 match self {
4044 TriggerObjectKind::For(obj) => write!(f, "FOR {obj}"),
4045 TriggerObjectKind::ForEach(obj) => write!(f, "FOR EACH {obj}"),
4046 }
4047 }
4048}
4049
4050#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4051#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4052#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4053pub struct CreateTrigger {
4067 pub or_alter: bool,
4071 pub temporary: bool,
4088 pub or_replace: bool,
4098 pub is_constraint: bool,
4100 pub name: ObjectName,
4102 pub period: Option<TriggerPeriod>,
4131 pub period_before_table: bool,
4142 pub events: Vec<TriggerEvent>,
4144 pub table_name: ObjectName,
4146 pub referenced_table_name: Option<ObjectName>,
4149 pub referencing: Vec<TriggerReferencing>,
4151 pub trigger_object: Option<TriggerObjectKind>,
4156 pub condition: Option<Expr>,
4158 pub exec_body: Option<TriggerExecBody>,
4160 pub statements_as: bool,
4162 pub statements: Option<ConditionalStatements>,
4164 pub characteristics: Option<ConstraintCharacteristics>,
4166}
4167
4168impl Display for CreateTrigger {
4169 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4170 let CreateTrigger {
4171 or_alter,
4172 temporary,
4173 or_replace,
4174 is_constraint,
4175 name,
4176 period_before_table,
4177 period,
4178 events,
4179 table_name,
4180 referenced_table_name,
4181 referencing,
4182 trigger_object,
4183 condition,
4184 exec_body,
4185 statements_as,
4186 statements,
4187 characteristics,
4188 } = self;
4189 write!(
4190 f,
4191 "CREATE {temporary}{or_alter}{or_replace}{is_constraint}TRIGGER {name} ",
4192 temporary = if *temporary { "TEMPORARY " } else { "" },
4193 or_alter = if *or_alter { "OR ALTER " } else { "" },
4194 or_replace = if *or_replace { "OR REPLACE " } else { "" },
4195 is_constraint = if *is_constraint { "CONSTRAINT " } else { "" },
4196 )?;
4197
4198 if *period_before_table {
4199 if let Some(p) = period {
4200 write!(f, "{p} ")?;
4201 }
4202 if !events.is_empty() {
4203 write!(f, "{} ", display_separated(events, " OR "))?;
4204 }
4205 write!(f, "ON {table_name}")?;
4206 } else {
4207 write!(f, "ON {table_name} ")?;
4208 if let Some(p) = period {
4209 write!(f, "{p}")?;
4210 }
4211 if !events.is_empty() {
4212 write!(f, " {}", display_separated(events, ", "))?;
4213 }
4214 }
4215
4216 if let Some(referenced_table_name) = referenced_table_name {
4217 write!(f, " FROM {referenced_table_name}")?;
4218 }
4219
4220 if let Some(characteristics) = characteristics {
4221 write!(f, " {characteristics}")?;
4222 }
4223
4224 if !referencing.is_empty() {
4225 write!(f, " REFERENCING {}", display_separated(referencing, " "))?;
4226 }
4227
4228 if let Some(trigger_object) = trigger_object {
4229 write!(f, " {trigger_object}")?;
4230 }
4231 if let Some(condition) = condition {
4232 write!(f, " WHEN {condition}")?;
4233 }
4234 if let Some(exec_body) = exec_body {
4235 write!(f, " EXECUTE {exec_body}")?;
4236 }
4237 if let Some(statements) = statements {
4238 if *statements_as {
4239 write!(f, " AS")?;
4240 }
4241 write!(f, " {statements}")?;
4242 }
4243 Ok(())
4244 }
4245}
4246
4247#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4248#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4249#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4250pub struct DropTrigger {
4257 pub if_exists: bool,
4259 pub trigger_name: ObjectName,
4261 pub table_name: Option<ObjectName>,
4263 pub option: Option<ReferentialAction>,
4265}
4266
4267impl fmt::Display for DropTrigger {
4268 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4269 let DropTrigger {
4270 if_exists,
4271 trigger_name,
4272 table_name,
4273 option,
4274 } = self;
4275 write!(f, "DROP TRIGGER")?;
4276 if *if_exists {
4277 write!(f, " IF EXISTS")?;
4278 }
4279 match &table_name {
4280 Some(table_name) => write!(f, " {trigger_name} ON {table_name}")?,
4281 None => write!(f, " {trigger_name}")?,
4282 };
4283 if let Some(option) = option {
4284 write!(f, " {option}")?;
4285 }
4286 Ok(())
4287 }
4288}
4289
4290#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4296#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4297#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4298pub struct Truncate {
4299 pub table_names: Vec<super::TruncateTableTarget>,
4301 pub partitions: Option<Vec<Expr>>,
4303 pub table: bool,
4305 pub if_exists: bool,
4307 pub identity: Option<super::TruncateIdentityOption>,
4309 pub cascade: Option<super::CascadeOption>,
4311 pub on_cluster: Option<Ident>,
4314}
4315
4316impl fmt::Display for Truncate {
4317 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4318 let table = if self.table { "TABLE " } else { "" };
4319 let if_exists = if self.if_exists { "IF EXISTS " } else { "" };
4320
4321 write!(
4322 f,
4323 "TRUNCATE {table}{if_exists}{table_names}",
4324 table_names = display_comma_separated(&self.table_names)
4325 )?;
4326
4327 if let Some(identity) = &self.identity {
4328 match identity {
4329 super::TruncateIdentityOption::Restart => write!(f, " RESTART IDENTITY")?,
4330 super::TruncateIdentityOption::Continue => write!(f, " CONTINUE IDENTITY")?,
4331 }
4332 }
4333 if let Some(cascade) = &self.cascade {
4334 match cascade {
4335 super::CascadeOption::Cascade => write!(f, " CASCADE")?,
4336 super::CascadeOption::Restrict => write!(f, " RESTRICT")?,
4337 }
4338 }
4339
4340 if let Some(ref parts) = &self.partitions {
4341 if !parts.is_empty() {
4342 write!(f, " PARTITION ({})", display_comma_separated(parts))?;
4343 }
4344 }
4345 if let Some(on_cluster) = &self.on_cluster {
4346 write!(f, " ON CLUSTER {on_cluster}")?;
4347 }
4348 Ok(())
4349 }
4350}
4351
4352impl Spanned for Truncate {
4353 fn span(&self) -> Span {
4354 Span::union_iter(
4355 self.table_names.iter().map(|i| i.name.span()).chain(
4356 self.partitions
4357 .iter()
4358 .flat_map(|i| i.iter().map(|k| k.span())),
4359 ),
4360 )
4361 }
4362}
4363
4364#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4371#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4372#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4373pub struct Msck {
4374 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4376 pub table_name: ObjectName,
4377 pub repair: bool,
4379 pub partition_action: Option<super::AddDropSync>,
4381}
4382
4383impl fmt::Display for Msck {
4384 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4385 write!(
4386 f,
4387 "MSCK {repair}TABLE {table}",
4388 repair = if self.repair { "REPAIR " } else { "" },
4389 table = self.table_name
4390 )?;
4391 if let Some(pa) = &self.partition_action {
4392 write!(f, " {pa}")?;
4393 }
4394 Ok(())
4395 }
4396}
4397
4398impl Spanned for Msck {
4399 fn span(&self) -> Span {
4400 self.table_name.span()
4401 }
4402}
4403
4404#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4406#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4407#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4408pub struct CreateView {
4409 pub or_alter: bool,
4413 pub or_replace: bool,
4415 pub materialized: bool,
4417 pub secure: bool,
4420 pub name: ObjectName,
4422 pub name_before_not_exists: bool,
4433 pub columns: Vec<ViewColumnDef>,
4435 pub query: Box<Query>,
4437 pub options: CreateTableOptions,
4439 pub cluster_by: Vec<Ident>,
4441 pub comment: Option<String>,
4444 pub with_no_schema_binding: bool,
4446 pub if_not_exists: bool,
4448 pub temporary: bool,
4450 pub copy_grants: bool,
4453 pub to: Option<ObjectName>,
4456 pub params: Option<CreateViewParams>,
4458}
4459
4460impl fmt::Display for CreateView {
4461 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4462 write!(
4463 f,
4464 "CREATE {or_alter}{or_replace}",
4465 or_alter = if self.or_alter { "OR ALTER " } else { "" },
4466 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
4467 )?;
4468 if let Some(ref params) = self.params {
4469 params.fmt(f)?;
4470 }
4471 write!(
4472 f,
4473 "{secure}{materialized}{temporary}VIEW {if_not_and_name}{to}",
4474 if_not_and_name = if self.if_not_exists {
4475 if self.name_before_not_exists {
4476 format!("{} IF NOT EXISTS", self.name)
4477 } else {
4478 format!("IF NOT EXISTS {}", self.name)
4479 }
4480 } else {
4481 format!("{}", self.name)
4482 },
4483 secure = if self.secure { "SECURE " } else { "" },
4484 materialized = if self.materialized {
4485 "MATERIALIZED "
4486 } else {
4487 ""
4488 },
4489 temporary = if self.temporary { "TEMPORARY " } else { "" },
4490 to = self
4491 .to
4492 .as_ref()
4493 .map(|to| format!(" TO {to}"))
4494 .unwrap_or_default()
4495 )?;
4496 if self.copy_grants {
4497 write!(f, " COPY GRANTS")?;
4498 }
4499 if !self.columns.is_empty() {
4500 write!(f, " ({})", display_comma_separated(&self.columns))?;
4501 }
4502 if matches!(self.options, CreateTableOptions::With(_)) {
4503 write!(f, " {}", self.options)?;
4504 }
4505 if let Some(ref comment) = self.comment {
4506 write!(f, " COMMENT = '{}'", escape_single_quote_string(comment))?;
4507 }
4508 if !self.cluster_by.is_empty() {
4509 write!(
4510 f,
4511 " CLUSTER BY ({})",
4512 display_comma_separated(&self.cluster_by)
4513 )?;
4514 }
4515 if matches!(self.options, CreateTableOptions::Options(_)) {
4516 write!(f, " {}", self.options)?;
4517 }
4518 f.write_str(" AS")?;
4519 SpaceOrNewline.fmt(f)?;
4520 self.query.fmt(f)?;
4521 if self.with_no_schema_binding {
4522 write!(f, " WITH NO SCHEMA BINDING")?;
4523 }
4524 Ok(())
4525 }
4526}
4527
4528#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4531#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4532#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4533pub struct CreateExtension {
4534 pub name: Ident,
4536 pub if_not_exists: bool,
4538 pub cascade: bool,
4540 pub schema: Option<Ident>,
4542 pub version: Option<Ident>,
4544}
4545
4546impl fmt::Display for CreateExtension {
4547 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4548 write!(
4549 f,
4550 "CREATE EXTENSION {if_not_exists}{name}",
4551 if_not_exists = if self.if_not_exists {
4552 "IF NOT EXISTS "
4553 } else {
4554 ""
4555 },
4556 name = self.name
4557 )?;
4558 if self.cascade || self.schema.is_some() || self.version.is_some() {
4559 write!(f, " WITH")?;
4560
4561 if let Some(name) = &self.schema {
4562 write!(f, " SCHEMA {name}")?;
4563 }
4564 if let Some(version) = &self.version {
4565 write!(f, " VERSION {version}")?;
4566 }
4567 if self.cascade {
4568 write!(f, " CASCADE")?;
4569 }
4570 }
4571
4572 Ok(())
4573 }
4574}
4575
4576impl Spanned for CreateExtension {
4577 fn span(&self) -> Span {
4578 Span::empty()
4579 }
4580}
4581
4582#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4590#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4591#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4592pub struct DropExtension {
4593 pub names: Vec<Ident>,
4595 pub if_exists: bool,
4597 pub cascade_or_restrict: Option<ReferentialAction>,
4599}
4600
4601impl fmt::Display for DropExtension {
4602 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4603 write!(f, "DROP EXTENSION")?;
4604 if self.if_exists {
4605 write!(f, " IF EXISTS")?;
4606 }
4607 write!(f, " {}", display_comma_separated(&self.names))?;
4608 if let Some(cascade_or_restrict) = &self.cascade_or_restrict {
4609 write!(f, " {cascade_or_restrict}")?;
4610 }
4611 Ok(())
4612 }
4613}
4614
4615impl Spanned for DropExtension {
4616 fn span(&self) -> Span {
4617 Span::empty()
4618 }
4619}
4620
4621#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4624#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4625#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4626pub struct CreateCollation {
4627 pub if_not_exists: bool,
4629 pub name: ObjectName,
4631 pub definition: CreateCollationDefinition,
4633}
4634
4635#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4637#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4638#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4639pub enum CreateCollationDefinition {
4640 From(ObjectName),
4646 Options(Vec<SqlOption>),
4652}
4653
4654impl fmt::Display for CreateCollation {
4655 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4656 write!(
4657 f,
4658 "CREATE COLLATION {if_not_exists}{name}",
4659 if_not_exists = if self.if_not_exists {
4660 "IF NOT EXISTS "
4661 } else {
4662 ""
4663 },
4664 name = self.name
4665 )?;
4666 match &self.definition {
4667 CreateCollationDefinition::From(existing_collation) => {
4668 write!(f, " FROM {existing_collation}")
4669 }
4670 CreateCollationDefinition::Options(options) => {
4671 write!(f, " ({})", display_comma_separated(options))
4672 }
4673 }
4674 }
4675}
4676
4677impl Spanned for CreateCollation {
4678 fn span(&self) -> Span {
4679 Span::empty()
4680 }
4681}
4682
4683#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4686#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4687#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4688pub struct AlterCollation {
4689 pub name: ObjectName,
4691 pub operation: AlterCollationOperation,
4693}
4694
4695#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4697#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4698#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4699pub enum AlterCollationOperation {
4700 RenameTo {
4706 new_name: Ident,
4708 },
4709 OwnerTo(Owner),
4715 SetSchema {
4721 schema_name: ObjectName,
4723 },
4724 RefreshVersion,
4730}
4731
4732impl fmt::Display for AlterCollationOperation {
4733 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4734 match self {
4735 AlterCollationOperation::RenameTo { new_name } => write!(f, "RENAME TO {new_name}"),
4736 AlterCollationOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
4737 AlterCollationOperation::SetSchema { schema_name } => {
4738 write!(f, "SET SCHEMA {schema_name}")
4739 }
4740 AlterCollationOperation::RefreshVersion => write!(f, "REFRESH VERSION"),
4741 }
4742 }
4743}
4744
4745impl fmt::Display for AlterCollation {
4746 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4747 write!(f, "ALTER COLLATION {} {}", self.name, self.operation)
4748 }
4749}
4750
4751impl Spanned for AlterCollation {
4752 fn span(&self) -> Span {
4753 Span::empty()
4754 }
4755}
4756
4757#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4760#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4761#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4762pub enum AlterTableType {
4763 Iceberg,
4766 Dynamic,
4769 External,
4772}
4773
4774#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4776#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4777#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4778pub struct AlterTable {
4779 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4781 pub name: ObjectName,
4782 pub if_exists: bool,
4784 pub only: bool,
4786 pub operations: Vec<AlterTableOperation>,
4788 pub location: Option<HiveSetLocation>,
4790 pub on_cluster: Option<Ident>,
4794 pub table_type: Option<AlterTableType>,
4796 pub end_token: AttachedToken,
4798}
4799
4800impl fmt::Display for AlterTable {
4801 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4802 match &self.table_type {
4803 Some(AlterTableType::Iceberg) => write!(f, "ALTER ICEBERG TABLE ")?,
4804 Some(AlterTableType::Dynamic) => write!(f, "ALTER DYNAMIC TABLE ")?,
4805 Some(AlterTableType::External) => write!(f, "ALTER EXTERNAL TABLE ")?,
4806 None => write!(f, "ALTER TABLE ")?,
4807 }
4808
4809 if self.if_exists {
4810 write!(f, "IF EXISTS ")?;
4811 }
4812 if self.only {
4813 write!(f, "ONLY ")?;
4814 }
4815 write!(f, "{} ", &self.name)?;
4816 if let Some(cluster) = &self.on_cluster {
4817 write!(f, "ON CLUSTER {cluster} ")?;
4818 }
4819 write!(f, "{}", display_comma_separated(&self.operations))?;
4820 if let Some(loc) = &self.location {
4821 write!(f, " {loc}")?
4822 }
4823 Ok(())
4824 }
4825}
4826
4827#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4829#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4830#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4831pub struct DropFunction {
4832 pub if_exists: bool,
4834 pub func_desc: Vec<FunctionDesc>,
4836 pub drop_behavior: Option<DropBehavior>,
4838}
4839
4840impl fmt::Display for DropFunction {
4841 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4842 write!(
4843 f,
4844 "DROP FUNCTION{} {}",
4845 if self.if_exists { " IF EXISTS" } else { "" },
4846 display_comma_separated(&self.func_desc),
4847 )?;
4848 if let Some(op) = &self.drop_behavior {
4849 write!(f, " {op}")?;
4850 }
4851 Ok(())
4852 }
4853}
4854
4855impl Spanned for DropFunction {
4856 fn span(&self) -> Span {
4857 Span::empty()
4858 }
4859}
4860
4861#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4864#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4865#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4866pub struct CreateOperator {
4867 pub name: ObjectName,
4869 pub function: ObjectName,
4871 pub is_procedure: bool,
4873 pub left_arg: Option<DataType>,
4875 pub right_arg: Option<DataType>,
4877 pub options: Vec<OperatorOption>,
4879}
4880
4881#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4884#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4885#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4886pub struct CreateOperatorFamily {
4887 pub name: ObjectName,
4889 pub using: Ident,
4891}
4892
4893#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4896#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4897#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4898pub struct CreateOperatorClass {
4899 pub name: ObjectName,
4901 pub default: bool,
4903 pub for_type: DataType,
4905 pub using: Ident,
4907 pub family: Option<ObjectName>,
4909 pub items: Vec<OperatorClassItem>,
4911}
4912
4913impl fmt::Display for CreateOperator {
4914 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4915 write!(f, "CREATE OPERATOR {} (", self.name)?;
4916
4917 let function_keyword = if self.is_procedure {
4918 "PROCEDURE"
4919 } else {
4920 "FUNCTION"
4921 };
4922 let mut params = vec![format!("{} = {}", function_keyword, self.function)];
4923
4924 if let Some(left_arg) = &self.left_arg {
4925 params.push(format!("LEFTARG = {}", left_arg));
4926 }
4927 if let Some(right_arg) = &self.right_arg {
4928 params.push(format!("RIGHTARG = {}", right_arg));
4929 }
4930
4931 for option in &self.options {
4932 params.push(option.to_string());
4933 }
4934
4935 write!(f, "{}", params.join(", "))?;
4936 write!(f, ")")
4937 }
4938}
4939
4940impl fmt::Display for CreateOperatorFamily {
4941 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4942 write!(
4943 f,
4944 "CREATE OPERATOR FAMILY {} USING {}",
4945 self.name, self.using
4946 )
4947 }
4948}
4949
4950impl fmt::Display for CreateOperatorClass {
4951 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4952 write!(f, "CREATE OPERATOR CLASS {}", self.name)?;
4953 if self.default {
4954 write!(f, " DEFAULT")?;
4955 }
4956 write!(f, " FOR TYPE {} USING {}", self.for_type, self.using)?;
4957 if let Some(family) = &self.family {
4958 write!(f, " FAMILY {}", family)?;
4959 }
4960 write!(f, " AS {}", display_comma_separated(&self.items))
4961 }
4962}
4963
4964#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4966#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4967#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4968pub struct OperatorArgTypes {
4969 pub left: DataType,
4971 pub right: DataType,
4973}
4974
4975impl fmt::Display for OperatorArgTypes {
4976 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4977 write!(f, "{}, {}", self.left, self.right)
4978 }
4979}
4980
4981#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4983#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4984#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4985pub enum OperatorClassItem {
4986 Operator {
4988 strategy_number: u64,
4990 operator_name: ObjectName,
4992 op_types: Option<OperatorArgTypes>,
4994 purpose: Option<OperatorPurpose>,
4996 },
4997 Function {
4999 support_number: u64,
5001 op_types: Option<Vec<DataType>>,
5003 function_name: ObjectName,
5005 argument_types: Vec<DataType>,
5007 },
5008 Storage {
5010 storage_type: DataType,
5012 },
5013}
5014
5015#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5017#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5018#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5019pub enum OperatorPurpose {
5020 ForSearch,
5022 ForOrderBy {
5024 sort_family: ObjectName,
5026 },
5027}
5028
5029impl fmt::Display for OperatorClassItem {
5030 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5031 match self {
5032 OperatorClassItem::Operator {
5033 strategy_number,
5034 operator_name,
5035 op_types,
5036 purpose,
5037 } => {
5038 write!(f, "OPERATOR {strategy_number} {operator_name}")?;
5039 if let Some(types) = op_types {
5040 write!(f, " ({types})")?;
5041 }
5042 if let Some(purpose) = purpose {
5043 write!(f, " {purpose}")?;
5044 }
5045 Ok(())
5046 }
5047 OperatorClassItem::Function {
5048 support_number,
5049 op_types,
5050 function_name,
5051 argument_types,
5052 } => {
5053 write!(f, "FUNCTION {support_number}")?;
5054 if let Some(types) = op_types {
5055 write!(f, " ({})", display_comma_separated(types))?;
5056 }
5057 write!(f, " {function_name}")?;
5058 if !argument_types.is_empty() {
5059 write!(f, "({})", display_comma_separated(argument_types))?;
5060 }
5061 Ok(())
5062 }
5063 OperatorClassItem::Storage { storage_type } => {
5064 write!(f, "STORAGE {storage_type}")
5065 }
5066 }
5067 }
5068}
5069
5070impl fmt::Display for OperatorPurpose {
5071 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5072 match self {
5073 OperatorPurpose::ForSearch => write!(f, "FOR SEARCH"),
5074 OperatorPurpose::ForOrderBy { sort_family } => {
5075 write!(f, "FOR ORDER BY {sort_family}")
5076 }
5077 }
5078 }
5079}
5080
5081#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5084#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5085#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5086pub struct DropOperator {
5087 pub if_exists: bool,
5089 pub operators: Vec<DropOperatorSignature>,
5091 pub drop_behavior: Option<DropBehavior>,
5093}
5094
5095#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5097#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5098#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5099pub struct DropOperatorSignature {
5100 pub name: ObjectName,
5102 pub left_type: Option<DataType>,
5104 pub right_type: DataType,
5106}
5107
5108impl fmt::Display for DropOperatorSignature {
5109 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5110 write!(f, "{} (", self.name)?;
5111 if let Some(left_type) = &self.left_type {
5112 write!(f, "{}", left_type)?;
5113 } else {
5114 write!(f, "NONE")?;
5115 }
5116 write!(f, ", {})", self.right_type)
5117 }
5118}
5119
5120impl fmt::Display for DropOperator {
5121 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5122 write!(f, "DROP OPERATOR")?;
5123 if self.if_exists {
5124 write!(f, " IF EXISTS")?;
5125 }
5126 write!(f, " {}", display_comma_separated(&self.operators))?;
5127 if let Some(drop_behavior) = &self.drop_behavior {
5128 write!(f, " {}", drop_behavior)?;
5129 }
5130 Ok(())
5131 }
5132}
5133
5134impl Spanned for DropOperator {
5135 fn span(&self) -> Span {
5136 Span::empty()
5137 }
5138}
5139
5140#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5143#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5144#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5145pub struct DropOperatorFamily {
5146 pub if_exists: bool,
5148 pub names: Vec<ObjectName>,
5150 pub using: Ident,
5152 pub drop_behavior: Option<DropBehavior>,
5154}
5155
5156impl fmt::Display for DropOperatorFamily {
5157 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5158 write!(f, "DROP OPERATOR FAMILY")?;
5159 if self.if_exists {
5160 write!(f, " IF EXISTS")?;
5161 }
5162 write!(f, " {}", display_comma_separated(&self.names))?;
5163 write!(f, " USING {}", self.using)?;
5164 if let Some(drop_behavior) = &self.drop_behavior {
5165 write!(f, " {}", drop_behavior)?;
5166 }
5167 Ok(())
5168 }
5169}
5170
5171impl Spanned for DropOperatorFamily {
5172 fn span(&self) -> Span {
5173 Span::empty()
5174 }
5175}
5176
5177#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5180#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5181#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5182pub struct DropOperatorClass {
5183 pub if_exists: bool,
5185 pub names: Vec<ObjectName>,
5187 pub using: Ident,
5189 pub drop_behavior: Option<DropBehavior>,
5191}
5192
5193impl fmt::Display for DropOperatorClass {
5194 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5195 write!(f, "DROP OPERATOR CLASS")?;
5196 if self.if_exists {
5197 write!(f, " IF EXISTS")?;
5198 }
5199 write!(f, " {}", display_comma_separated(&self.names))?;
5200 write!(f, " USING {}", self.using)?;
5201 if let Some(drop_behavior) = &self.drop_behavior {
5202 write!(f, " {}", drop_behavior)?;
5203 }
5204 Ok(())
5205 }
5206}
5207
5208impl Spanned for DropOperatorClass {
5209 fn span(&self) -> Span {
5210 Span::empty()
5211 }
5212}
5213
5214#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5216#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5217#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5218pub enum OperatorFamilyItem {
5219 Operator {
5221 strategy_number: u64,
5223 operator_name: ObjectName,
5225 op_types: Vec<DataType>,
5227 purpose: Option<OperatorPurpose>,
5229 },
5230 Function {
5232 support_number: u64,
5234 op_types: Option<Vec<DataType>>,
5236 function_name: ObjectName,
5238 argument_types: Vec<DataType>,
5240 },
5241}
5242
5243#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5245#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5246#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5247pub enum OperatorFamilyDropItem {
5248 Operator {
5250 strategy_number: u64,
5252 op_types: Vec<DataType>,
5254 },
5255 Function {
5257 support_number: u64,
5259 op_types: Vec<DataType>,
5261 },
5262}
5263
5264impl fmt::Display for OperatorFamilyItem {
5265 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5266 match self {
5267 OperatorFamilyItem::Operator {
5268 strategy_number,
5269 operator_name,
5270 op_types,
5271 purpose,
5272 } => {
5273 write!(
5274 f,
5275 "OPERATOR {strategy_number} {operator_name} ({})",
5276 display_comma_separated(op_types)
5277 )?;
5278 if let Some(purpose) = purpose {
5279 write!(f, " {purpose}")?;
5280 }
5281 Ok(())
5282 }
5283 OperatorFamilyItem::Function {
5284 support_number,
5285 op_types,
5286 function_name,
5287 argument_types,
5288 } => {
5289 write!(f, "FUNCTION {support_number}")?;
5290 if let Some(types) = op_types {
5291 write!(f, " ({})", display_comma_separated(types))?;
5292 }
5293 write!(f, " {function_name}")?;
5294 if !argument_types.is_empty() {
5295 write!(f, "({})", display_comma_separated(argument_types))?;
5296 }
5297 Ok(())
5298 }
5299 }
5300 }
5301}
5302
5303impl fmt::Display for OperatorFamilyDropItem {
5304 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5305 match self {
5306 OperatorFamilyDropItem::Operator {
5307 strategy_number,
5308 op_types,
5309 } => {
5310 write!(
5311 f,
5312 "OPERATOR {strategy_number} ({})",
5313 display_comma_separated(op_types)
5314 )
5315 }
5316 OperatorFamilyDropItem::Function {
5317 support_number,
5318 op_types,
5319 } => {
5320 write!(
5321 f,
5322 "FUNCTION {support_number} ({})",
5323 display_comma_separated(op_types)
5324 )
5325 }
5326 }
5327 }
5328}
5329
5330#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5333#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5334#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5335pub struct AlterOperatorFamily {
5336 pub name: ObjectName,
5338 pub using: Ident,
5340 pub operation: AlterOperatorFamilyOperation,
5342}
5343
5344#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5346#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5347#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5348pub enum AlterOperatorFamilyOperation {
5349 Add {
5351 items: Vec<OperatorFamilyItem>,
5353 },
5354 Drop {
5356 items: Vec<OperatorFamilyDropItem>,
5358 },
5359 RenameTo {
5361 new_name: ObjectName,
5363 },
5364 OwnerTo(Owner),
5366 SetSchema {
5368 schema_name: ObjectName,
5370 },
5371}
5372
5373impl fmt::Display for AlterOperatorFamily {
5374 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5375 write!(
5376 f,
5377 "ALTER OPERATOR FAMILY {} USING {}",
5378 self.name, self.using
5379 )?;
5380 write!(f, " {}", self.operation)
5381 }
5382}
5383
5384impl fmt::Display for AlterOperatorFamilyOperation {
5385 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5386 match self {
5387 AlterOperatorFamilyOperation::Add { items } => {
5388 write!(f, "ADD {}", display_comma_separated(items))
5389 }
5390 AlterOperatorFamilyOperation::Drop { items } => {
5391 write!(f, "DROP {}", display_comma_separated(items))
5392 }
5393 AlterOperatorFamilyOperation::RenameTo { new_name } => {
5394 write!(f, "RENAME TO {new_name}")
5395 }
5396 AlterOperatorFamilyOperation::OwnerTo(owner) => {
5397 write!(f, "OWNER TO {owner}")
5398 }
5399 AlterOperatorFamilyOperation::SetSchema { schema_name } => {
5400 write!(f, "SET SCHEMA {schema_name}")
5401 }
5402 }
5403 }
5404}
5405
5406impl Spanned for AlterOperatorFamily {
5407 fn span(&self) -> Span {
5408 Span::empty()
5409 }
5410}
5411
5412#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5415#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5416#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5417pub struct AlterOperatorClass {
5418 pub name: ObjectName,
5420 pub using: Ident,
5422 pub operation: AlterOperatorClassOperation,
5424}
5425
5426#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5428#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5429#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5430pub enum AlterOperatorClassOperation {
5431 RenameTo {
5434 new_name: ObjectName,
5436 },
5437 OwnerTo(Owner),
5439 SetSchema {
5442 schema_name: ObjectName,
5444 },
5445}
5446
5447impl fmt::Display for AlterOperatorClass {
5448 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5449 write!(f, "ALTER OPERATOR CLASS {} USING {}", self.name, self.using)?;
5450 write!(f, " {}", self.operation)
5451 }
5452}
5453
5454impl fmt::Display for AlterOperatorClassOperation {
5455 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5456 match self {
5457 AlterOperatorClassOperation::RenameTo { new_name } => {
5458 write!(f, "RENAME TO {new_name}")
5459 }
5460 AlterOperatorClassOperation::OwnerTo(owner) => {
5461 write!(f, "OWNER TO {owner}")
5462 }
5463 AlterOperatorClassOperation::SetSchema { schema_name } => {
5464 write!(f, "SET SCHEMA {schema_name}")
5465 }
5466 }
5467 }
5468}
5469
5470impl Spanned for AlterOperatorClass {
5471 fn span(&self) -> Span {
5472 Span::empty()
5473 }
5474}
5475
5476#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5478#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5479#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5480pub struct AlterFunction {
5481 pub kind: AlterFunctionKind,
5483 pub function: FunctionDesc,
5485 pub aggregate_order_by: Option<Vec<OperateFunctionArg>>,
5489 pub aggregate_star: bool,
5493 pub operation: AlterFunctionOperation,
5495}
5496
5497#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5499#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5500#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5501pub enum AlterFunctionKind {
5502 Function,
5504 Aggregate,
5506}
5507
5508impl fmt::Display for AlterFunctionKind {
5509 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5510 match self {
5511 Self::Function => write!(f, "FUNCTION"),
5512 Self::Aggregate => write!(f, "AGGREGATE"),
5513 }
5514 }
5515}
5516
5517#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5519#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5520#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5521pub enum AlterFunctionOperation {
5522 RenameTo {
5524 new_name: Ident,
5526 },
5527 OwnerTo(Owner),
5529 SetSchema {
5531 schema_name: ObjectName,
5533 },
5534 DependsOnExtension {
5536 no: bool,
5538 extension_name: ObjectName,
5540 },
5541 Actions {
5543 actions: Vec<AlterFunctionAction>,
5545 restrict: bool,
5547 },
5548}
5549
5550#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5552#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5553#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5554pub enum AlterFunctionAction {
5555 CalledOnNull(FunctionCalledOnNull),
5557 Behavior(FunctionBehavior),
5559 Leakproof(bool),
5561 Security {
5563 external: bool,
5565 security: FunctionSecurity,
5567 },
5568 Parallel(FunctionParallel),
5570 Cost(Expr),
5572 Rows(Expr),
5574 Support(ObjectName),
5576 Set(FunctionDefinitionSetParam),
5579 Reset(ResetConfig),
5581}
5582
5583impl fmt::Display for AlterFunction {
5584 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5585 write!(f, "ALTER {} ", self.kind)?;
5586 match self.kind {
5587 AlterFunctionKind::Function => {
5588 write!(f, "{} ", self.function)?;
5589 }
5590 AlterFunctionKind::Aggregate => {
5591 write!(f, "{}(", self.function.name)?;
5592 if self.aggregate_star {
5593 write!(f, "*")?;
5594 } else {
5595 if let Some(args) = &self.function.args {
5596 write!(f, "{}", display_comma_separated(args))?;
5597 }
5598 if let Some(order_by_args) = &self.aggregate_order_by {
5599 if self
5600 .function
5601 .args
5602 .as_ref()
5603 .is_some_and(|args| !args.is_empty())
5604 {
5605 write!(f, " ")?;
5606 }
5607 write!(f, "ORDER BY {}", display_comma_separated(order_by_args))?;
5608 }
5609 }
5610 write!(f, ") ")?;
5611 }
5612 }
5613 write!(f, "{}", self.operation)
5614 }
5615}
5616
5617impl fmt::Display for AlterFunctionOperation {
5618 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5619 match self {
5620 AlterFunctionOperation::RenameTo { new_name } => {
5621 write!(f, "RENAME TO {new_name}")
5622 }
5623 AlterFunctionOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
5624 AlterFunctionOperation::SetSchema { schema_name } => {
5625 write!(f, "SET SCHEMA {schema_name}")
5626 }
5627 AlterFunctionOperation::DependsOnExtension { no, extension_name } => {
5628 if *no {
5629 write!(f, "NO DEPENDS ON EXTENSION {extension_name}")
5630 } else {
5631 write!(f, "DEPENDS ON EXTENSION {extension_name}")
5632 }
5633 }
5634 AlterFunctionOperation::Actions { actions, restrict } => {
5635 write!(f, "{}", display_separated(actions, " "))?;
5636 if *restrict {
5637 write!(f, " RESTRICT")?;
5638 }
5639 Ok(())
5640 }
5641 }
5642 }
5643}
5644
5645impl fmt::Display for AlterFunctionAction {
5646 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5647 match self {
5648 AlterFunctionAction::CalledOnNull(called_on_null) => write!(f, "{called_on_null}"),
5649 AlterFunctionAction::Behavior(behavior) => write!(f, "{behavior}"),
5650 AlterFunctionAction::Leakproof(leakproof) => {
5651 if *leakproof {
5652 write!(f, "LEAKPROOF")
5653 } else {
5654 write!(f, "NOT LEAKPROOF")
5655 }
5656 }
5657 AlterFunctionAction::Security { external, security } => {
5658 if *external {
5659 write!(f, "EXTERNAL ")?;
5660 }
5661 write!(f, "{security}")
5662 }
5663 AlterFunctionAction::Parallel(parallel) => write!(f, "{parallel}"),
5664 AlterFunctionAction::Cost(execution_cost) => write!(f, "COST {execution_cost}"),
5665 AlterFunctionAction::Rows(result_rows) => write!(f, "ROWS {result_rows}"),
5666 AlterFunctionAction::Support(support_function) => {
5667 write!(f, "SUPPORT {support_function}")
5668 }
5669 AlterFunctionAction::Set(set_param) => write!(f, "{set_param}"),
5670 AlterFunctionAction::Reset(reset_config) => match reset_config {
5671 ResetConfig::ALL => write!(f, "RESET ALL"),
5672 ResetConfig::ConfigName(name) => write!(f, "RESET {name}"),
5673 },
5674 }
5675 }
5676}
5677
5678impl Spanned for AlterFunction {
5679 fn span(&self) -> Span {
5680 Span::empty()
5681 }
5682}
5683
5684#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5688#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5689#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5690pub enum TextSearchObjectType {
5691 Dictionary,
5693 Configuration,
5695 Template,
5697 Parser,
5699}
5700
5701impl fmt::Display for TextSearchObjectType {
5702 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5703 match self {
5704 TextSearchObjectType::Dictionary => write!(f, "DICTIONARY"),
5705 TextSearchObjectType::Configuration => write!(f, "CONFIGURATION"),
5706 TextSearchObjectType::Template => write!(f, "TEMPLATE"),
5707 TextSearchObjectType::Parser => write!(f, "PARSER"),
5708 }
5709 }
5710}
5711
5712#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5716#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5717#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5718pub struct CreateTextSearch {
5719 pub object_type: TextSearchObjectType,
5721 pub name: ObjectName,
5723 pub options: Vec<SqlOption>,
5725}
5726
5727impl fmt::Display for CreateTextSearch {
5728 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5729 write!(
5730 f,
5731 "CREATE TEXT SEARCH {} {} ({})",
5732 self.object_type,
5733 self.name,
5734 display_comma_separated(&self.options)
5735 )
5736 }
5737}
5738
5739impl Spanned for CreateTextSearch {
5740 fn span(&self) -> Span {
5741 Span::empty()
5742 }
5743}
5744
5745#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5749#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5750#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5751pub struct AlterTextSearchOption {
5752 pub key: Ident,
5754 pub value: Option<Expr>,
5756}
5757
5758impl fmt::Display for AlterTextSearchOption {
5759 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5760 match &self.value {
5761 Some(value) => write!(f, "{} = {}", self.key, value),
5762 None => write!(f, "{}", self.key),
5763 }
5764 }
5765}
5766
5767#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5771#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5772#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5773pub enum AlterTextSearchOperation {
5774 RenameTo {
5776 new_name: Ident,
5778 },
5779 OwnerTo(Owner),
5781 SetSchema {
5783 schema_name: ObjectName,
5785 },
5786 SetOptions {
5788 options: Vec<AlterTextSearchOption>,
5790 },
5791}
5792
5793impl fmt::Display for AlterTextSearchOperation {
5794 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5795 match self {
5796 AlterTextSearchOperation::RenameTo { new_name } => write!(f, "RENAME TO {new_name}"),
5797 AlterTextSearchOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
5798 AlterTextSearchOperation::SetSchema { schema_name } => {
5799 write!(f, "SET SCHEMA {schema_name}")
5800 }
5801 AlterTextSearchOperation::SetOptions { options } => {
5802 write!(f, "({})", display_comma_separated(options))
5803 }
5804 }
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 AlterTextSearch {
5815 pub object_type: TextSearchObjectType,
5817 pub name: ObjectName,
5819 pub operation: AlterTextSearchOperation,
5821}
5822
5823impl fmt::Display for AlterTextSearch {
5824 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5825 write!(
5826 f,
5827 "ALTER TEXT SEARCH {} {} {}",
5828 self.object_type, self.name, self.operation
5829 )
5830 }
5831}
5832
5833impl Spanned for AlterTextSearch {
5834 fn span(&self) -> Span {
5835 Span::empty()
5836 }
5837}
5838
5839#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5843#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5844#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5845pub struct CreatePolicy {
5846 pub name: Ident,
5848 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5850 pub table_name: ObjectName,
5851 pub policy_type: Option<CreatePolicyType>,
5853 pub command: Option<CreatePolicyCommand>,
5855 pub to: Option<Vec<Owner>>,
5857 pub using: Option<Expr>,
5859 pub with_check: Option<Expr>,
5861}
5862
5863impl fmt::Display for CreatePolicy {
5864 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5865 write!(
5866 f,
5867 "CREATE POLICY {name} ON {table_name}",
5868 name = self.name,
5869 table_name = self.table_name,
5870 )?;
5871 if let Some(ref policy_type) = self.policy_type {
5872 write!(f, " AS {policy_type}")?;
5873 }
5874 if let Some(ref command) = self.command {
5875 write!(f, " FOR {command}")?;
5876 }
5877 if let Some(ref to) = self.to {
5878 write!(f, " TO {}", display_comma_separated(to))?;
5879 }
5880 if let Some(ref using) = self.using {
5881 write!(f, " USING ({using})")?;
5882 }
5883 if let Some(ref with_check) = self.with_check {
5884 write!(f, " WITH CHECK ({with_check})")?;
5885 }
5886 Ok(())
5887 }
5888}
5889
5890#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5896#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5897#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5898pub enum CreatePolicyType {
5899 Permissive,
5901 Restrictive,
5903}
5904
5905impl fmt::Display for CreatePolicyType {
5906 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5907 match self {
5908 CreatePolicyType::Permissive => write!(f, "PERMISSIVE"),
5909 CreatePolicyType::Restrictive => write!(f, "RESTRICTIVE"),
5910 }
5911 }
5912}
5913
5914#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5920#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5921#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5922pub enum CreatePolicyCommand {
5923 All,
5925 Select,
5927 Insert,
5929 Update,
5931 Delete,
5933}
5934
5935impl fmt::Display for CreatePolicyCommand {
5936 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5937 match self {
5938 CreatePolicyCommand::All => write!(f, "ALL"),
5939 CreatePolicyCommand::Select => write!(f, "SELECT"),
5940 CreatePolicyCommand::Insert => write!(f, "INSERT"),
5941 CreatePolicyCommand::Update => write!(f, "UPDATE"),
5942 CreatePolicyCommand::Delete => write!(f, "DELETE"),
5943 }
5944 }
5945}
5946
5947#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5951#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5952#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5953pub struct DropPolicy {
5954 pub if_exists: bool,
5956 pub name: Ident,
5958 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5960 pub table_name: ObjectName,
5961 pub drop_behavior: Option<DropBehavior>,
5963}
5964
5965impl fmt::Display for DropPolicy {
5966 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5967 write!(
5968 f,
5969 "DROP POLICY {if_exists}{name} ON {table_name}",
5970 if_exists = if self.if_exists { "IF EXISTS " } else { "" },
5971 name = self.name,
5972 table_name = self.table_name
5973 )?;
5974 if let Some(ref behavior) = self.drop_behavior {
5975 write!(f, " {behavior}")?;
5976 }
5977 Ok(())
5978 }
5979}
5980
5981impl From<CreatePolicy> for crate::ast::Statement {
5982 fn from(v: CreatePolicy) -> Self {
5983 crate::ast::Statement::CreatePolicy(v)
5984 }
5985}
5986
5987impl From<DropPolicy> for crate::ast::Statement {
5988 fn from(v: DropPolicy) -> Self {
5989 crate::ast::Statement::DropPolicy(v)
5990 }
5991}
5992
5993#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6000#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6001#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6002pub struct AlterPolicy {
6003 pub name: Ident,
6005 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6007 pub table_name: ObjectName,
6008 pub operation: AlterPolicyOperation,
6010}
6011
6012impl fmt::Display for AlterPolicy {
6013 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6014 write!(
6015 f,
6016 "ALTER POLICY {name} ON {table_name}{operation}",
6017 name = self.name,
6018 table_name = self.table_name,
6019 operation = self.operation
6020 )
6021 }
6022}
6023
6024impl From<AlterPolicy> for crate::ast::Statement {
6025 fn from(v: AlterPolicy) -> Self {
6026 crate::ast::Statement::AlterPolicy(v)
6027 }
6028}