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 WithParser(Ident),
1479 Visible,
1481 Invisible,
1483}
1484
1485impl fmt::Display for IndexOption {
1486 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1487 match self {
1488 Self::Using(index_type) => write!(f, "USING {index_type}"),
1489 Self::Comment(s) => write!(f, "COMMENT '{s}'"),
1490 Self::WithParser(name) => write!(f, "WITH PARSER {name}"),
1491 Self::Visible => write!(f, "VISIBLE"),
1492 Self::Invisible => write!(f, "INVISIBLE"),
1493 }
1494 }
1495}
1496
1497#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1501#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1502#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1503pub enum NullsDistinctOption {
1504 None,
1506 Distinct,
1508 NotDistinct,
1510}
1511
1512impl fmt::Display for NullsDistinctOption {
1513 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1514 match self {
1515 Self::None => Ok(()),
1516 Self::Distinct => write!(f, " NULLS DISTINCT"),
1517 Self::NotDistinct => write!(f, " NULLS NOT DISTINCT"),
1518 }
1519 }
1520}
1521
1522#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1523#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1524#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1525pub struct ProcedureParam {
1527 pub name: Ident,
1529 pub data_type: DataType,
1531 pub mode: Option<ArgMode>,
1533 pub default: Option<Expr>,
1535}
1536
1537impl fmt::Display for ProcedureParam {
1538 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1539 if let Some(mode) = &self.mode {
1540 if let Some(default) = &self.default {
1541 write!(f, "{mode} {} {} = {}", self.name, self.data_type, default)
1542 } else {
1543 write!(f, "{mode} {} {}", self.name, self.data_type)
1544 }
1545 } else if let Some(default) = &self.default {
1546 write!(f, "{} {} = {}", self.name, self.data_type, default)
1547 } else {
1548 write!(f, "{} {}", self.name, self.data_type)
1549 }
1550 }
1551}
1552
1553#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1555#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1556#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1557pub struct ColumnDef {
1558 pub name: Ident,
1560 pub data_type: DataType,
1562 pub options: Vec<ColumnOptionDef>,
1564}
1565
1566impl fmt::Display for ColumnDef {
1567 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1568 if self.data_type == DataType::Unspecified {
1569 write!(f, "{}", self.name)?;
1570 } else {
1571 write!(f, "{} {}", self.name, self.data_type)?;
1572 }
1573 for option in &self.options {
1574 write!(f, " {option}")?;
1575 }
1576 Ok(())
1577 }
1578}
1579
1580#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1597#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1598#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1599pub struct ViewColumnDef {
1600 pub name: Ident,
1602 pub data_type: Option<DataType>,
1604 pub options: Option<ColumnOptions>,
1606}
1607
1608#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1609#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1610#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1611pub enum ColumnOptions {
1613 CommaSeparated(Vec<ColumnOption>),
1615 SpaceSeparated(Vec<ColumnOption>),
1617}
1618
1619impl ColumnOptions {
1620 pub fn as_slice(&self) -> &[ColumnOption] {
1622 match self {
1623 ColumnOptions::CommaSeparated(options) => options.as_slice(),
1624 ColumnOptions::SpaceSeparated(options) => options.as_slice(),
1625 }
1626 }
1627}
1628
1629impl fmt::Display for ViewColumnDef {
1630 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1631 write!(f, "{}", self.name)?;
1632 if let Some(data_type) = self.data_type.as_ref() {
1633 write!(f, " {data_type}")?;
1634 }
1635 if let Some(options) = self.options.as_ref() {
1636 match options {
1637 ColumnOptions::CommaSeparated(column_options) => {
1638 write!(f, " {}", display_comma_separated(column_options.as_slice()))?;
1639 }
1640 ColumnOptions::SpaceSeparated(column_options) => {
1641 write!(f, " {}", display_separated(column_options.as_slice(), " "))?
1642 }
1643 }
1644 }
1645 Ok(())
1646 }
1647}
1648
1649#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1666#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1667#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1668pub struct ColumnOptionDef {
1669 pub name: Option<Ident>,
1671 pub option: ColumnOption,
1673}
1674
1675impl fmt::Display for ColumnOptionDef {
1676 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1677 write!(f, "{}{}", display_constraint_name(&self.name), self.option)
1678 }
1679}
1680
1681#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1689#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1690#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1691pub enum IdentityPropertyKind {
1692 Autoincrement(IdentityProperty),
1700 Identity(IdentityProperty),
1713}
1714
1715impl fmt::Display for IdentityPropertyKind {
1716 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1717 let (command, property) = match self {
1718 IdentityPropertyKind::Identity(property) => ("IDENTITY", property),
1719 IdentityPropertyKind::Autoincrement(property) => ("AUTOINCREMENT", property),
1720 };
1721 write!(f, "{command}")?;
1722 if let Some(parameters) = &property.parameters {
1723 write!(f, "{parameters}")?;
1724 }
1725 if let Some(order) = &property.order {
1726 write!(f, "{order}")?;
1727 }
1728 Ok(())
1729 }
1730}
1731
1732#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1734#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1735#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1736pub struct IdentityProperty {
1737 pub parameters: Option<IdentityPropertyFormatKind>,
1739 pub order: Option<IdentityPropertyOrder>,
1741}
1742
1743#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1758#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1759#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1760pub enum IdentityPropertyFormatKind {
1761 FunctionCall(IdentityParameters),
1769 StartAndIncrement(IdentityParameters),
1776}
1777
1778impl fmt::Display for IdentityPropertyFormatKind {
1779 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1780 match self {
1781 IdentityPropertyFormatKind::FunctionCall(parameters) => {
1782 write!(f, "({}, {})", parameters.seed, parameters.increment)
1783 }
1784 IdentityPropertyFormatKind::StartAndIncrement(parameters) => {
1785 write!(
1786 f,
1787 " START {} INCREMENT {}",
1788 parameters.seed, parameters.increment
1789 )
1790 }
1791 }
1792 }
1793}
1794#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1796#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1797#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1798pub struct IdentityParameters {
1799 pub seed: Expr,
1801 pub increment: Expr,
1803}
1804
1805#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1812#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1813#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1814pub enum IdentityPropertyOrder {
1815 Order,
1817 NoOrder,
1819}
1820
1821impl fmt::Display for IdentityPropertyOrder {
1822 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1823 match self {
1824 IdentityPropertyOrder::Order => write!(f, " ORDER"),
1825 IdentityPropertyOrder::NoOrder => write!(f, " NOORDER"),
1826 }
1827 }
1828}
1829
1830#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1838#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1839#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1840pub enum ColumnPolicy {
1841 MaskingPolicy(ColumnPolicyProperty),
1843 ProjectionPolicy(ColumnPolicyProperty),
1845}
1846
1847impl fmt::Display for ColumnPolicy {
1848 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1849 let (command, property) = match self {
1850 ColumnPolicy::MaskingPolicy(property) => ("MASKING POLICY", property),
1851 ColumnPolicy::ProjectionPolicy(property) => ("PROJECTION POLICY", property),
1852 };
1853 if property.with {
1854 write!(f, "WITH ")?;
1855 }
1856 write!(f, "{command} {}", property.policy_name)?;
1857 if let Some(using_columns) = &property.using_columns {
1858 write!(f, " USING ({})", display_comma_separated(using_columns))?;
1859 }
1860 Ok(())
1861 }
1862}
1863
1864#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1865#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1866#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1867pub struct ColumnPolicyProperty {
1869 pub with: bool,
1876 pub policy_name: ObjectName,
1878 pub using_columns: Option<Vec<Ident>>,
1880}
1881
1882#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1889#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1890#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1891pub struct TagsColumnOption {
1892 pub with: bool,
1899 pub tags: Vec<Tag>,
1901}
1902
1903impl fmt::Display for TagsColumnOption {
1904 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1905 if self.with {
1906 write!(f, "WITH ")?;
1907 }
1908 write!(f, "TAG ({})", display_comma_separated(&self.tags))?;
1909 Ok(())
1910 }
1911}
1912
1913#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1916#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1917#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1918pub enum ColumnOption {
1919 Null,
1921 NotNull,
1923 Default(Expr),
1925
1926 Materialized(Expr),
1931 Ephemeral(Option<Expr>),
1935 Alias(Expr),
1939
1940 PrimaryKey(PrimaryKeyConstraint),
1942 Unique(UniqueConstraint),
1944 ForeignKey(ForeignKeyConstraint),
1952 Check(CheckConstraint),
1954 DialectSpecific(Vec<Token>),
1958 CharacterSet(ObjectName),
1960 Collation(ObjectName),
1962 Comment(String),
1964 OnUpdate(Expr),
1966 Generated {
1969 generated_as: GeneratedAs,
1971 sequence_options: Option<Vec<SequenceOptions>>,
1973 generation_expr: Option<Expr>,
1975 generation_expr_mode: Option<GeneratedExpressionMode>,
1977 generated_keyword: bool,
1979 },
1980 Options(Vec<SqlOption>),
1988 Identity(IdentityPropertyKind),
1996 OnConflict(Keyword),
1999 Policy(ColumnPolicy),
2007 Tags(TagsColumnOption),
2014 Srid(Box<Expr>),
2021 Invisible,
2028}
2029
2030impl From<UniqueConstraint> for ColumnOption {
2031 fn from(c: UniqueConstraint) -> Self {
2032 ColumnOption::Unique(c)
2033 }
2034}
2035
2036impl From<PrimaryKeyConstraint> for ColumnOption {
2037 fn from(c: PrimaryKeyConstraint) -> Self {
2038 ColumnOption::PrimaryKey(c)
2039 }
2040}
2041
2042impl From<CheckConstraint> for ColumnOption {
2043 fn from(c: CheckConstraint) -> Self {
2044 ColumnOption::Check(c)
2045 }
2046}
2047impl From<ForeignKeyConstraint> for ColumnOption {
2048 fn from(fk: ForeignKeyConstraint) -> Self {
2049 ColumnOption::ForeignKey(fk)
2050 }
2051}
2052
2053impl fmt::Display for ColumnOption {
2054 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2055 use ColumnOption::*;
2056 match self {
2057 Null => write!(f, "NULL"),
2058 NotNull => write!(f, "NOT NULL"),
2059 Default(expr) => write!(f, "DEFAULT {expr}"),
2060 Materialized(expr) => write!(f, "MATERIALIZED {expr}"),
2061 Ephemeral(expr) => {
2062 if let Some(e) = expr {
2063 write!(f, "EPHEMERAL {e}")
2064 } else {
2065 write!(f, "EPHEMERAL")
2066 }
2067 }
2068 Alias(expr) => write!(f, "ALIAS {expr}"),
2069 PrimaryKey(constraint) => {
2070 write!(f, "PRIMARY KEY")?;
2071 if let Some(characteristics) = &constraint.characteristics {
2072 write!(f, " {characteristics}")?;
2073 }
2074 Ok(())
2075 }
2076 Unique(constraint) => {
2077 write!(f, "UNIQUE{:>}", constraint.index_type_display)?;
2078 if let Some(characteristics) = &constraint.characteristics {
2079 write!(f, " {characteristics}")?;
2080 }
2081 Ok(())
2082 }
2083 ForeignKey(constraint) => {
2084 write!(f, "REFERENCES {}", constraint.foreign_table)?;
2085 if !constraint.referred_columns.is_empty() {
2086 write!(
2087 f,
2088 " ({})",
2089 display_comma_separated(&constraint.referred_columns)
2090 )?;
2091 }
2092 if let Some(match_kind) = &constraint.match_kind {
2093 write!(f, " {match_kind}")?;
2094 }
2095 if let Some(action) = &constraint.on_delete {
2096 write!(f, " ON DELETE {action}")?;
2097 }
2098 if let Some(action) = &constraint.on_update {
2099 write!(f, " ON UPDATE {action}")?;
2100 }
2101 if let Some(characteristics) = &constraint.characteristics {
2102 write!(f, " {characteristics}")?;
2103 }
2104 Ok(())
2105 }
2106 Check(constraint) => write!(f, "{constraint}"),
2107 DialectSpecific(val) => write!(f, "{}", display_separated(val, " ")),
2108 CharacterSet(n) => write!(f, "CHARACTER SET {n}"),
2109 Collation(n) => write!(f, "COLLATE {n}"),
2110 Comment(v) => write!(f, "COMMENT '{}'", escape_single_quote_string(v)),
2111 OnUpdate(expr) => write!(f, "ON UPDATE {expr}"),
2112 Generated {
2113 generated_as,
2114 sequence_options,
2115 generation_expr,
2116 generation_expr_mode,
2117 generated_keyword,
2118 } => {
2119 if let Some(expr) = generation_expr {
2120 let modifier = match generation_expr_mode {
2121 None => "",
2122 Some(GeneratedExpressionMode::Virtual) => " VIRTUAL",
2123 Some(GeneratedExpressionMode::Stored) => " STORED",
2124 };
2125 if *generated_keyword {
2126 write!(f, "GENERATED ALWAYS AS ({expr}){modifier}")?;
2127 } else {
2128 write!(f, "AS ({expr}){modifier}")?;
2129 }
2130 Ok(())
2131 } else {
2132 let when = match generated_as {
2134 GeneratedAs::Always => "ALWAYS",
2135 GeneratedAs::ByDefault => "BY DEFAULT",
2136 GeneratedAs::ExpStored => "",
2138 };
2139 write!(f, "GENERATED {when} AS IDENTITY")?;
2140 if let Some(so) = sequence_options {
2141 if !so.is_empty() {
2142 write!(f, " (")?;
2143 }
2144 for sequence_option in so {
2145 write!(f, "{sequence_option}")?;
2146 }
2147 if !so.is_empty() {
2148 write!(f, " )")?;
2149 }
2150 }
2151 Ok(())
2152 }
2153 }
2154 Options(options) => {
2155 write!(f, "OPTIONS({})", display_comma_separated(options))
2156 }
2157 Identity(parameters) => {
2158 write!(f, "{parameters}")
2159 }
2160 OnConflict(keyword) => {
2161 write!(f, "ON CONFLICT {keyword:?}")?;
2162 Ok(())
2163 }
2164 Policy(parameters) => {
2165 write!(f, "{parameters}")
2166 }
2167 Tags(tags) => {
2168 write!(f, "{tags}")
2169 }
2170 Srid(srid) => {
2171 write!(f, "SRID {srid}")
2172 }
2173 Invisible => {
2174 write!(f, "INVISIBLE")
2175 }
2176 }
2177 }
2178}
2179
2180#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2183#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2184#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2185pub enum GeneratedAs {
2186 Always,
2188 ByDefault,
2190 ExpStored,
2192}
2193
2194#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
2197#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2198#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2199pub enum GeneratedExpressionMode {
2200 Virtual,
2202 Stored,
2204}
2205
2206#[must_use]
2207pub(crate) fn display_constraint_name(name: &'_ Option<Ident>) -> impl fmt::Display + '_ {
2208 struct ConstraintName<'a>(&'a Option<Ident>);
2209 impl fmt::Display for ConstraintName<'_> {
2210 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2211 if let Some(name) = self.0 {
2212 write!(f, "CONSTRAINT {name} ")?;
2213 }
2214 Ok(())
2215 }
2216 }
2217 ConstraintName(name)
2218}
2219
2220#[must_use]
2224pub(crate) fn display_option<'a, T: fmt::Display>(
2225 prefix: &'a str,
2226 postfix: &'a str,
2227 option: &'a Option<T>,
2228) -> impl fmt::Display + 'a {
2229 struct OptionDisplay<'a, T>(&'a str, &'a str, &'a Option<T>);
2230 impl<T: fmt::Display> fmt::Display for OptionDisplay<'_, T> {
2231 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2232 if let Some(inner) = self.2 {
2233 let (prefix, postfix) = (self.0, self.1);
2234 write!(f, "{prefix}{inner}{postfix}")?;
2235 }
2236 Ok(())
2237 }
2238 }
2239 OptionDisplay(prefix, postfix, option)
2240}
2241
2242#[must_use]
2246pub(crate) fn display_option_spaced<T: fmt::Display>(option: &Option<T>) -> impl fmt::Display + '_ {
2247 display_option(" ", "", option)
2248}
2249
2250#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Default, Eq, Ord, Hash)]
2254#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2255#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2256pub struct ConstraintCharacteristics {
2257 pub deferrable: Option<bool>,
2259 pub initially: Option<DeferrableInitial>,
2261 pub enforced: Option<bool>,
2263}
2264
2265#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2267#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2268#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2269pub enum DeferrableInitial {
2270 Immediate,
2272 Deferred,
2274}
2275
2276impl ConstraintCharacteristics {
2277 fn deferrable_text(&self) -> Option<&'static str> {
2278 self.deferrable.map(|deferrable| {
2279 if deferrable {
2280 "DEFERRABLE"
2281 } else {
2282 "NOT DEFERRABLE"
2283 }
2284 })
2285 }
2286
2287 fn initially_immediate_text(&self) -> Option<&'static str> {
2288 self.initially
2289 .map(|initially_immediate| match initially_immediate {
2290 DeferrableInitial::Immediate => "INITIALLY IMMEDIATE",
2291 DeferrableInitial::Deferred => "INITIALLY DEFERRED",
2292 })
2293 }
2294
2295 fn enforced_text(&self) -> Option<&'static str> {
2296 self.enforced.map(
2297 |enforced| {
2298 if enforced {
2299 "ENFORCED"
2300 } else {
2301 "NOT ENFORCED"
2302 }
2303 },
2304 )
2305 }
2306}
2307
2308impl fmt::Display for ConstraintCharacteristics {
2309 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2310 let deferrable = self.deferrable_text();
2311 let initially_immediate = self.initially_immediate_text();
2312 let enforced = self.enforced_text();
2313
2314 match (deferrable, initially_immediate, enforced) {
2315 (None, None, None) => Ok(()),
2316 (None, None, Some(enforced)) => write!(f, "{enforced}"),
2317 (None, Some(initial), None) => write!(f, "{initial}"),
2318 (None, Some(initial), Some(enforced)) => write!(f, "{initial} {enforced}"),
2319 (Some(deferrable), None, None) => write!(f, "{deferrable}"),
2320 (Some(deferrable), None, Some(enforced)) => write!(f, "{deferrable} {enforced}"),
2321 (Some(deferrable), Some(initial), None) => write!(f, "{deferrable} {initial}"),
2322 (Some(deferrable), Some(initial), Some(enforced)) => {
2323 write!(f, "{deferrable} {initial} {enforced}")
2324 }
2325 }
2326 }
2327}
2328
2329#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2334#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2335#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2336pub enum ReferentialAction {
2337 Restrict,
2339 Cascade,
2341 SetNull,
2343 NoAction,
2345 SetDefault,
2347}
2348
2349impl fmt::Display for ReferentialAction {
2350 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2351 f.write_str(match self {
2352 ReferentialAction::Restrict => "RESTRICT",
2353 ReferentialAction::Cascade => "CASCADE",
2354 ReferentialAction::SetNull => "SET NULL",
2355 ReferentialAction::NoAction => "NO ACTION",
2356 ReferentialAction::SetDefault => "SET DEFAULT",
2357 })
2358 }
2359}
2360
2361#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2365#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2366#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2367pub enum DropBehavior {
2368 Restrict,
2370 Cascade,
2372}
2373
2374impl fmt::Display for DropBehavior {
2375 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2376 f.write_str(match self {
2377 DropBehavior::Restrict => "RESTRICT",
2378 DropBehavior::Cascade => "CASCADE",
2379 })
2380 }
2381}
2382
2383#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2385#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2386#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2387pub enum UserDefinedTypeRepresentation {
2388 Composite {
2390 attributes: Vec<UserDefinedTypeCompositeAttributeDef>,
2392 },
2393 Enum {
2398 labels: Vec<Ident>,
2400 },
2401 Range {
2405 options: Vec<UserDefinedTypeRangeOption>,
2407 },
2408 SqlDefinition {
2414 options: Vec<UserDefinedTypeSqlDefinitionOption>,
2416 },
2417}
2418
2419impl fmt::Display for UserDefinedTypeRepresentation {
2420 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2421 match self {
2422 Self::Composite { attributes } => {
2423 write!(f, "AS ({})", display_comma_separated(attributes))
2424 }
2425 Self::Enum { labels } => {
2426 write!(f, "AS ENUM ({})", display_comma_separated(labels))
2427 }
2428 Self::Range { options } => {
2429 write!(f, "AS RANGE ({})", display_comma_separated(options))
2430 }
2431 Self::SqlDefinition { options } => {
2432 write!(f, "({})", display_comma_separated(options))
2433 }
2434 }
2435 }
2436}
2437
2438#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2440#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2441#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2442pub struct UserDefinedTypeCompositeAttributeDef {
2443 pub name: Ident,
2445 pub data_type: DataType,
2447 pub collation: Option<ObjectName>,
2449}
2450
2451impl fmt::Display for UserDefinedTypeCompositeAttributeDef {
2452 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2453 write!(f, "{} {}", self.name, self.data_type)?;
2454 if let Some(collation) = &self.collation {
2455 write!(f, " COLLATE {collation}")?;
2456 }
2457 Ok(())
2458 }
2459}
2460
2461#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2484#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2485#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2486pub enum UserDefinedTypeInternalLength {
2487 Fixed(u64),
2489 Variable,
2491}
2492
2493impl fmt::Display for UserDefinedTypeInternalLength {
2494 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2495 match self {
2496 UserDefinedTypeInternalLength::Fixed(n) => write!(f, "{}", n),
2497 UserDefinedTypeInternalLength::Variable => write!(f, "VARIABLE"),
2498 }
2499 }
2500}
2501
2502#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2521#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2522#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2523pub enum Alignment {
2524 Char,
2526 Int2,
2528 Int4,
2530 Double,
2532}
2533
2534impl fmt::Display for Alignment {
2535 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2536 match self {
2537 Alignment::Char => write!(f, "char"),
2538 Alignment::Int2 => write!(f, "int2"),
2539 Alignment::Int4 => write!(f, "int4"),
2540 Alignment::Double => write!(f, "double"),
2541 }
2542 }
2543}
2544
2545#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2565#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2566#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2567pub enum UserDefinedTypeStorage {
2568 Plain,
2570 External,
2572 Extended,
2574 Main,
2576}
2577
2578impl fmt::Display for UserDefinedTypeStorage {
2579 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2580 match self {
2581 UserDefinedTypeStorage::Plain => write!(f, "plain"),
2582 UserDefinedTypeStorage::External => write!(f, "external"),
2583 UserDefinedTypeStorage::Extended => write!(f, "extended"),
2584 UserDefinedTypeStorage::Main => write!(f, "main"),
2585 }
2586 }
2587}
2588
2589#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2607#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2608#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2609pub enum UserDefinedTypeRangeOption {
2610 Subtype(DataType),
2612 SubtypeOpClass(ObjectName),
2614 Collation(ObjectName),
2616 Canonical(ObjectName),
2618 SubtypeDiff(ObjectName),
2620 MultirangeTypeName(ObjectName),
2622}
2623
2624impl fmt::Display for UserDefinedTypeRangeOption {
2625 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2626 match self {
2627 UserDefinedTypeRangeOption::Subtype(dt) => write!(f, "SUBTYPE = {}", dt),
2628 UserDefinedTypeRangeOption::SubtypeOpClass(name) => {
2629 write!(f, "SUBTYPE_OPCLASS = {}", name)
2630 }
2631 UserDefinedTypeRangeOption::Collation(name) => write!(f, "COLLATION = {}", name),
2632 UserDefinedTypeRangeOption::Canonical(name) => write!(f, "CANONICAL = {}", name),
2633 UserDefinedTypeRangeOption::SubtypeDiff(name) => write!(f, "SUBTYPE_DIFF = {}", name),
2634 UserDefinedTypeRangeOption::MultirangeTypeName(name) => {
2635 write!(f, "MULTIRANGE_TYPE_NAME = {}", name)
2636 }
2637 }
2638 }
2639}
2640
2641#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2662#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2663#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2664pub enum UserDefinedTypeSqlDefinitionOption {
2665 Input(ObjectName),
2667 Output(ObjectName),
2669 Receive(ObjectName),
2671 Send(ObjectName),
2673 TypmodIn(ObjectName),
2675 TypmodOut(ObjectName),
2677 Analyze(ObjectName),
2679 Subscript(ObjectName),
2681 InternalLength(UserDefinedTypeInternalLength),
2683 PassedByValue,
2685 Alignment(Alignment),
2687 Storage(UserDefinedTypeStorage),
2689 Like(ObjectName),
2691 Category(char),
2693 Preferred(bool),
2695 Default(Expr),
2697 Element(DataType),
2699 Delimiter(String),
2701 Collatable(bool),
2703}
2704
2705impl fmt::Display for UserDefinedTypeSqlDefinitionOption {
2706 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2707 match self {
2708 UserDefinedTypeSqlDefinitionOption::Input(name) => write!(f, "INPUT = {}", name),
2709 UserDefinedTypeSqlDefinitionOption::Output(name) => write!(f, "OUTPUT = {}", name),
2710 UserDefinedTypeSqlDefinitionOption::Receive(name) => write!(f, "RECEIVE = {}", name),
2711 UserDefinedTypeSqlDefinitionOption::Send(name) => write!(f, "SEND = {}", name),
2712 UserDefinedTypeSqlDefinitionOption::TypmodIn(name) => write!(f, "TYPMOD_IN = {}", name),
2713 UserDefinedTypeSqlDefinitionOption::TypmodOut(name) => {
2714 write!(f, "TYPMOD_OUT = {}", name)
2715 }
2716 UserDefinedTypeSqlDefinitionOption::Analyze(name) => write!(f, "ANALYZE = {}", name),
2717 UserDefinedTypeSqlDefinitionOption::Subscript(name) => {
2718 write!(f, "SUBSCRIPT = {}", name)
2719 }
2720 UserDefinedTypeSqlDefinitionOption::InternalLength(len) => {
2721 write!(f, "INTERNALLENGTH = {}", len)
2722 }
2723 UserDefinedTypeSqlDefinitionOption::PassedByValue => write!(f, "PASSEDBYVALUE"),
2724 UserDefinedTypeSqlDefinitionOption::Alignment(align) => {
2725 write!(f, "ALIGNMENT = {}", align)
2726 }
2727 UserDefinedTypeSqlDefinitionOption::Storage(storage) => {
2728 write!(f, "STORAGE = {}", storage)
2729 }
2730 UserDefinedTypeSqlDefinitionOption::Like(name) => write!(f, "LIKE = {}", name),
2731 UserDefinedTypeSqlDefinitionOption::Category(c) => write!(f, "CATEGORY = '{}'", c),
2732 UserDefinedTypeSqlDefinitionOption::Preferred(b) => write!(f, "PREFERRED = {}", b),
2733 UserDefinedTypeSqlDefinitionOption::Default(expr) => write!(f, "DEFAULT = {}", expr),
2734 UserDefinedTypeSqlDefinitionOption::Element(dt) => write!(f, "ELEMENT = {}", dt),
2735 UserDefinedTypeSqlDefinitionOption::Delimiter(s) => {
2736 write!(f, "DELIMITER = '{}'", escape_single_quote_string(s))
2737 }
2738 UserDefinedTypeSqlDefinitionOption::Collatable(b) => write!(f, "COLLATABLE = {}", b),
2739 }
2740 }
2741}
2742
2743#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2747#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2748#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2749pub enum Partition {
2750 Identifier(Ident),
2752 Expr(Expr),
2754 Part(Expr),
2757 Partitions(Vec<Expr>),
2759}
2760
2761impl fmt::Display for Partition {
2762 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2763 match self {
2764 Partition::Identifier(id) => write!(f, "PARTITION ID {id}"),
2765 Partition::Expr(expr) => write!(f, "PARTITION {expr}"),
2766 Partition::Part(expr) => write!(f, "PART {expr}"),
2767 Partition::Partitions(partitions) => {
2768 write!(f, "PARTITION ({})", display_comma_separated(partitions))
2769 }
2770 }
2771 }
2772}
2773
2774#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2777#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2778#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2779pub enum Deduplicate {
2780 All,
2782 ByExpression(Expr),
2784}
2785
2786impl fmt::Display for Deduplicate {
2787 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2788 match self {
2789 Deduplicate::All => write!(f, "DEDUPLICATE"),
2790 Deduplicate::ByExpression(expr) => write!(f, "DEDUPLICATE BY {expr}"),
2791 }
2792 }
2793}
2794
2795#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2800#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2801#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2802pub struct ClusteredBy {
2803 pub columns: Vec<Ident>,
2805 pub sorted_by: Option<Vec<OrderByExpr>>,
2807 pub num_buckets: Value,
2809}
2810
2811impl fmt::Display for ClusteredBy {
2812 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2813 write!(
2814 f,
2815 "CLUSTERED BY ({})",
2816 display_comma_separated(&self.columns)
2817 )?;
2818 if let Some(ref sorted_by) = self.sorted_by {
2819 write!(f, " SORTED BY ({})", display_comma_separated(sorted_by))?;
2820 }
2821 write!(f, " INTO {} BUCKETS", self.num_buckets)
2822 }
2823}
2824
2825#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2827#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2828#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2829pub struct CreateIndex {
2830 pub name: Option<ObjectName>,
2832 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2833 pub table_name: ObjectName,
2835 pub using: Option<IndexType>,
2838 pub columns: Vec<IndexColumn>,
2840 pub unique: bool,
2842 pub concurrently: bool,
2844 pub r#async: bool,
2848 pub if_not_exists: bool,
2850 pub include: Vec<Ident>,
2852 pub nulls_distinct: Option<bool>,
2854 pub with: Vec<Expr>,
2856 pub predicate: Option<Expr>,
2858 pub index_options: Vec<IndexOption>,
2860 pub alter_options: Vec<AlterTableOperation>,
2867 pub fulltext_or_spatial: Option<FullTextOrSpatialKind>,
2873}
2874
2875#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Copy)]
2879#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2880#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2881pub enum FullTextOrSpatialKind {
2882 Fulltext,
2884 Spatial,
2886}
2887
2888impl fmt::Display for FullTextOrSpatialKind {
2889 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2890 match self {
2891 FullTextOrSpatialKind::Fulltext => f.write_str("FULLTEXT"),
2892 FullTextOrSpatialKind::Spatial => f.write_str("SPATIAL"),
2893 }
2894 }
2895}
2896
2897impl fmt::Display for CreateIndex {
2898 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2899 let kind_prefix = match self.fulltext_or_spatial {
2900 Some(kind) => format!("{kind} "),
2901 None => String::new(),
2902 };
2903 write!(
2904 f,
2905 "CREATE {kind_prefix}{unique}INDEX {concurrently}{async_}{if_not_exists}",
2906 unique = if self.unique { "UNIQUE " } else { "" },
2907 concurrently = if self.concurrently {
2908 "CONCURRENTLY "
2909 } else {
2910 ""
2911 },
2912 async_ = if self.r#async { "ASYNC " } else { "" },
2913 if_not_exists = if self.if_not_exists {
2914 "IF NOT EXISTS "
2915 } else {
2916 ""
2917 },
2918 )?;
2919 if let Some(value) = &self.name {
2920 write!(f, "{value} ")?;
2921 }
2922 write!(f, "ON {}", self.table_name)?;
2923 if let Some(value) = &self.using {
2924 write!(f, " USING {value} ")?;
2925 }
2926 write!(f, "({})", display_comma_separated(&self.columns))?;
2927 if !self.include.is_empty() {
2928 write!(f, " INCLUDE ({})", display_comma_separated(&self.include))?;
2929 }
2930 if let Some(value) = self.nulls_distinct {
2931 if value {
2932 write!(f, " NULLS DISTINCT")?;
2933 } else {
2934 write!(f, " NULLS NOT DISTINCT")?;
2935 }
2936 }
2937 if !self.with.is_empty() {
2938 write!(f, " WITH ({})", display_comma_separated(&self.with))?;
2939 }
2940 if let Some(predicate) = &self.predicate {
2941 write!(f, " WHERE {predicate}")?;
2942 }
2943 if !self.index_options.is_empty() {
2944 write!(f, " {}", display_separated(&self.index_options, " "))?;
2945 }
2946 if !self.alter_options.is_empty() {
2947 write!(f, " {}", display_separated(&self.alter_options, " "))?;
2948 }
2949 Ok(())
2950 }
2951}
2952
2953#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2955#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2956#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2957pub struct CreateTable {
2958 pub or_replace: bool,
2960 pub temporary: bool,
2962 pub unlogged: bool,
2964 pub external: bool,
2966 pub dynamic: bool,
2968 pub global: Option<bool>,
2970 pub if_not_exists: bool,
2972 pub transient: bool,
2974 pub volatile: bool,
2976 pub iceberg: bool,
2978 pub snapshot: bool,
2981 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2983 pub name: ObjectName,
2984 pub columns: Vec<ColumnDef>,
2986 pub constraints: Vec<TableConstraint>,
2988 pub hive_distribution: HiveDistributionStyle,
2990 pub hive_formats: Option<HiveFormat>,
2992 pub table_options: CreateTableOptions,
2994 pub file_format: Option<FileFormat>,
2996 pub location: Option<String>,
2998 pub query: Option<Box<Query>>,
3000 pub without_rowid: bool,
3002 pub like: Option<CreateTableLikeKind>,
3004 pub clone: Option<ObjectName>,
3006 pub version: Option<TableVersion>,
3008 pub comment: Option<CommentDef>,
3012 pub on_commit: Option<OnCommit>,
3015 pub on_cluster: Option<Ident>,
3018 pub primary_key: Option<Box<Expr>>,
3021 pub order_by: Option<OneOrManyWithParens<Expr>>,
3025 pub partition_by: Option<Box<Expr>>,
3028 pub cluster_by: Option<WrappedCollection<Vec<Expr>>>,
3033 pub clustered_by: Option<ClusteredBy>,
3036 pub inherits: Option<Vec<ObjectName>>,
3041 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3045 pub partition_of: Option<ObjectName>,
3046 pub for_values: Option<ForValues>,
3049 pub strict: bool,
3053 pub copy_grants: bool,
3056 pub enable_schema_evolution: Option<bool>,
3059 pub change_tracking: Option<bool>,
3062 pub data_retention_time_in_days: Option<u64>,
3065 pub max_data_extension_time_in_days: Option<u64>,
3068 pub default_ddl_collation: Option<String>,
3071 pub with_aggregation_policy: Option<ObjectName>,
3074 pub with_row_access_policy: Option<RowAccessPolicy>,
3077 pub with_storage_lifecycle_policy: Option<StorageLifecyclePolicy>,
3080 pub with_tags: Option<Vec<Tag>>,
3083 pub external_volume: Option<String>,
3086 pub with_connection: Option<ObjectName>,
3089 pub base_location: Option<String>,
3092 pub catalog: Option<String>,
3095 pub catalog_sync: Option<String>,
3098 pub storage_serialization_policy: Option<StorageSerializationPolicy>,
3101 pub target_lag: Option<String>,
3104 pub warehouse: Option<Ident>,
3107 pub refresh_mode: Option<RefreshModeKind>,
3110 pub initialize: Option<InitializeKind>,
3113 pub require_user: bool,
3116 pub diststyle: Option<DistStyle>,
3119 pub distkey: Option<Expr>,
3122 pub sortkey: Option<Vec<Expr>>,
3125 pub backup: Option<bool>,
3128 pub multiset: Option<bool>,
3133 pub fallback: Option<bool>,
3138 pub with_data: Option<WithData>,
3142}
3143
3144impl fmt::Display for CreateTable {
3145 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3146 write!(
3154 f,
3155 "CREATE {or_replace}{external}{global}{multiset}{temporary}{unlogged}{transient}{volatile}{dynamic}{iceberg}{snapshot}TABLE {if_not_exists}{name}",
3156 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3157 external = if self.external { "EXTERNAL " } else { "" },
3158 snapshot = if self.snapshot { "SNAPSHOT " } else { "" },
3159 global = self.global
3160 .map(|global| {
3161 if global {
3162 "GLOBAL "
3163 } else {
3164 "LOCAL "
3165 }
3166 })
3167 .unwrap_or(""),
3168 if_not_exists = if self.if_not_exists { "IF NOT EXISTS " } else { "" },
3169 multiset = self
3170 .multiset
3171 .map(|m| if m { "MULTISET " } else { "SET " })
3172 .unwrap_or(""),
3173 temporary = if self.temporary { "TEMPORARY " } else { "" },
3174 unlogged = if self.unlogged { "UNLOGGED " } else { "" },
3175 transient = if self.transient { "TRANSIENT " } else { "" },
3176 volatile = if self.volatile { "VOLATILE " } else { "" },
3177 iceberg = if self.iceberg { "ICEBERG " } else { "" },
3178 dynamic = if self.dynamic { "DYNAMIC " } else { "" },
3179 name = self.name,
3180 )?;
3181 if let Some(fallback) = self.fallback {
3182 write!(f, ", {}", if fallback { "FALLBACK" } else { "NO FALLBACK" })?;
3183 }
3184 if let Some(partition_of) = &self.partition_of {
3185 write!(f, " PARTITION OF {partition_of}")?;
3186 }
3187 if let Some(on_cluster) = &self.on_cluster {
3188 write!(f, " ON CLUSTER {on_cluster}")?;
3189 }
3190 if !self.columns.is_empty() || !self.constraints.is_empty() {
3191 f.write_str(" (")?;
3192 NewLine.fmt(f)?;
3193 Indent(DisplayCommaSeparated(&self.columns)).fmt(f)?;
3194 if !self.columns.is_empty() && !self.constraints.is_empty() {
3195 f.write_str(",")?;
3196 SpaceOrNewline.fmt(f)?;
3197 }
3198 Indent(DisplayCommaSeparated(&self.constraints)).fmt(f)?;
3199 NewLine.fmt(f)?;
3200 f.write_str(")")?;
3201 } else if self.query.is_none()
3202 && self.like.is_none()
3203 && self.clone.is_none()
3204 && self.partition_of.is_none()
3205 {
3206 f.write_str(" ()")?;
3208 } else if let Some(CreateTableLikeKind::Parenthesized(like_in_columns_list)) = &self.like {
3209 write!(f, " ({like_in_columns_list})")?;
3210 }
3211 if let Some(for_values) = &self.for_values {
3212 write!(f, " {for_values}")?;
3213 }
3214
3215 if let Some(comment) = &self.comment {
3218 write!(f, " COMMENT '{comment}'")?;
3219 }
3220
3221 if self.without_rowid {
3223 write!(f, " WITHOUT ROWID")?;
3224 }
3225
3226 if let Some(CreateTableLikeKind::Plain(like)) = &self.like {
3227 write!(f, " {like}")?;
3228 }
3229
3230 if let Some(c) = &self.clone {
3231 write!(f, " CLONE {c}")?;
3232 }
3233
3234 if let Some(version) = &self.version {
3235 write!(f, " {version}")?;
3236 }
3237
3238 match &self.hive_distribution {
3239 HiveDistributionStyle::PARTITIONED { columns } => {
3240 write!(f, " PARTITIONED BY ({})", display_comma_separated(columns))?;
3241 }
3242 HiveDistributionStyle::SKEWED {
3243 columns,
3244 on,
3245 stored_as_directories,
3246 } => {
3247 write!(
3248 f,
3249 " SKEWED BY ({})) ON ({})",
3250 display_comma_separated(columns),
3251 display_comma_separated(on)
3252 )?;
3253 if *stored_as_directories {
3254 write!(f, " STORED AS DIRECTORIES")?;
3255 }
3256 }
3257 _ => (),
3258 }
3259
3260 if let Some(clustered_by) = &self.clustered_by {
3261 write!(f, " {clustered_by}")?;
3262 }
3263
3264 if let Some(HiveFormat {
3265 row_format,
3266 serde_properties,
3267 storage,
3268 location,
3269 }) = &self.hive_formats
3270 {
3271 match row_format {
3272 Some(HiveRowFormat::SERDE { class }) => write!(f, " ROW FORMAT SERDE '{class}'")?,
3273 Some(HiveRowFormat::DELIMITED { delimiters }) => {
3274 write!(f, " ROW FORMAT DELIMITED")?;
3275 if !delimiters.is_empty() {
3276 write!(f, " {}", display_separated(delimiters, " "))?;
3277 }
3278 }
3279 None => (),
3280 }
3281 match storage {
3282 Some(HiveIOFormat::IOF {
3283 input_format,
3284 output_format,
3285 }) => write!(
3286 f,
3287 " STORED AS INPUTFORMAT {input_format} OUTPUTFORMAT {output_format}"
3288 )?,
3289 Some(HiveIOFormat::FileFormat { format }) if !self.external => {
3290 write!(f, " STORED AS {format}")?
3291 }
3292 Some(HiveIOFormat::Using { format }) => write!(f, " USING {format}")?,
3293 _ => (),
3294 }
3295 if let Some(serde_properties) = serde_properties.as_ref() {
3296 write!(
3297 f,
3298 " WITH SERDEPROPERTIES ({})",
3299 display_comma_separated(serde_properties)
3300 )?;
3301 }
3302 if !self.external {
3303 if let Some(loc) = location {
3304 write!(f, " LOCATION '{loc}'")?;
3305 }
3306 }
3307 }
3308 if self.external {
3309 if let Some(file_format) = self.file_format {
3310 write!(f, " STORED AS {file_format}")?;
3311 }
3312 if let Some(location) = &self.location {
3313 write!(f, " LOCATION '{location}'")?;
3314 }
3315 }
3316
3317 match &self.table_options {
3318 options @ CreateTableOptions::With(_)
3319 | options @ CreateTableOptions::Plain(_)
3320 | options @ CreateTableOptions::TableProperties(_) => write!(f, " {options}")?,
3321 _ => (),
3322 }
3323
3324 if let Some(primary_key) = &self.primary_key {
3325 write!(f, " PRIMARY KEY {primary_key}")?;
3326 }
3327 if let Some(order_by) = &self.order_by {
3328 write!(f, " ORDER BY {order_by}")?;
3329 }
3330 if let Some(inherits) = &self.inherits {
3331 write!(f, " INHERITS ({})", display_comma_separated(inherits))?;
3332 }
3333 if let Some(partition_by) = self.partition_by.as_ref() {
3334 write!(f, " PARTITION BY {partition_by}")?;
3335 }
3336 if let Some(cluster_by) = self.cluster_by.as_ref() {
3337 write!(f, " CLUSTER BY {cluster_by}")?;
3338 }
3339 if let Some(with_connection) = &self.with_connection {
3340 write!(f, " WITH CONNECTION {with_connection}")?;
3341 }
3342 if let options @ CreateTableOptions::Options(_) = &self.table_options {
3343 write!(f, " {options}")?;
3344 }
3345 if let Some(external_volume) = self.external_volume.as_ref() {
3346 write!(f, " EXTERNAL_VOLUME='{external_volume}'")?;
3347 }
3348
3349 if let Some(catalog) = self.catalog.as_ref() {
3350 write!(f, " CATALOG='{catalog}'")?;
3351 }
3352
3353 if self.iceberg {
3354 if let Some(base_location) = self.base_location.as_ref() {
3355 write!(f, " BASE_LOCATION='{base_location}'")?;
3356 }
3357 }
3358
3359 if let Some(catalog_sync) = self.catalog_sync.as_ref() {
3360 write!(f, " CATALOG_SYNC='{catalog_sync}'")?;
3361 }
3362
3363 if let Some(storage_serialization_policy) = self.storage_serialization_policy.as_ref() {
3364 write!(
3365 f,
3366 " STORAGE_SERIALIZATION_POLICY={storage_serialization_policy}"
3367 )?;
3368 }
3369
3370 if self.copy_grants {
3371 write!(f, " COPY GRANTS")?;
3372 }
3373
3374 if let Some(is_enabled) = self.enable_schema_evolution {
3375 write!(
3376 f,
3377 " ENABLE_SCHEMA_EVOLUTION={}",
3378 if is_enabled { "TRUE" } else { "FALSE" }
3379 )?;
3380 }
3381
3382 if let Some(is_enabled) = self.change_tracking {
3383 write!(
3384 f,
3385 " CHANGE_TRACKING={}",
3386 if is_enabled { "TRUE" } else { "FALSE" }
3387 )?;
3388 }
3389
3390 if let Some(data_retention_time_in_days) = self.data_retention_time_in_days {
3391 write!(
3392 f,
3393 " DATA_RETENTION_TIME_IN_DAYS={data_retention_time_in_days}",
3394 )?;
3395 }
3396
3397 if let Some(max_data_extension_time_in_days) = self.max_data_extension_time_in_days {
3398 write!(
3399 f,
3400 " MAX_DATA_EXTENSION_TIME_IN_DAYS={max_data_extension_time_in_days}",
3401 )?;
3402 }
3403
3404 if let Some(default_ddl_collation) = &self.default_ddl_collation {
3405 write!(f, " DEFAULT_DDL_COLLATION='{default_ddl_collation}'",)?;
3406 }
3407
3408 if let Some(with_aggregation_policy) = &self.with_aggregation_policy {
3409 write!(f, " WITH AGGREGATION POLICY {with_aggregation_policy}",)?;
3410 }
3411
3412 if let Some(row_access_policy) = &self.with_row_access_policy {
3413 write!(f, " {row_access_policy}",)?;
3414 }
3415
3416 if let Some(storage_lifecycle_policy) = &self.with_storage_lifecycle_policy {
3417 write!(f, " {storage_lifecycle_policy}",)?;
3418 }
3419
3420 if let Some(tag) = &self.with_tags {
3421 write!(f, " WITH TAG ({})", display_comma_separated(tag.as_slice()))?;
3422 }
3423
3424 if let Some(target_lag) = &self.target_lag {
3425 write!(f, " TARGET_LAG='{target_lag}'")?;
3426 }
3427
3428 if let Some(warehouse) = &self.warehouse {
3429 write!(f, " WAREHOUSE={warehouse}")?;
3430 }
3431
3432 if let Some(refresh_mode) = &self.refresh_mode {
3433 write!(f, " REFRESH_MODE={refresh_mode}")?;
3434 }
3435
3436 if let Some(initialize) = &self.initialize {
3437 write!(f, " INITIALIZE={initialize}")?;
3438 }
3439
3440 if self.require_user {
3441 write!(f, " REQUIRE USER")?;
3442 }
3443
3444 if self.on_commit.is_some() {
3445 let on_commit = match self.on_commit {
3446 Some(OnCommit::DeleteRows) => "ON COMMIT DELETE ROWS",
3447 Some(OnCommit::PreserveRows) => "ON COMMIT PRESERVE ROWS",
3448 Some(OnCommit::Drop) => "ON COMMIT DROP",
3449 None => "",
3450 };
3451 write!(f, " {on_commit}")?;
3452 }
3453 if self.strict {
3454 write!(f, " STRICT")?;
3455 }
3456 if let Some(backup) = self.backup {
3457 write!(f, " BACKUP {}", if backup { "YES" } else { "NO" })?;
3458 }
3459 if let Some(diststyle) = &self.diststyle {
3460 write!(f, " DISTSTYLE {diststyle}")?;
3461 }
3462 if let Some(distkey) = &self.distkey {
3463 write!(f, " DISTKEY({distkey})")?;
3464 }
3465 if let Some(sortkey) = &self.sortkey {
3466 write!(f, " SORTKEY({})", display_comma_separated(sortkey))?;
3467 }
3468 if let Some(query) = &self.query {
3469 write!(f, " AS {query}")?;
3470 }
3471 if let Some(with_data) = &self.with_data {
3472 write!(f, " {with_data}")?;
3473 }
3474 Ok(())
3475 }
3476}
3477
3478#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
3482#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3483#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3484pub struct WithData {
3485 pub data: bool,
3487 pub statistics: Option<bool>,
3490}
3491
3492impl fmt::Display for WithData {
3493 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3494 f.write_str("WITH ")?;
3495 if !self.data {
3496 f.write_str("NO ")?;
3497 }
3498 f.write_str("DATA")?;
3499 if let Some(stats) = self.statistics {
3500 f.write_str(" AND ")?;
3501 if !stats {
3502 f.write_str("NO ")?;
3503 }
3504 f.write_str("STATISTICS")?;
3505 }
3506 Ok(())
3507 }
3508}
3509
3510#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3516#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3517#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3518pub enum ForValues {
3519 In(Vec<Expr>),
3521 From {
3523 from: Vec<PartitionBoundValue>,
3525 to: Vec<PartitionBoundValue>,
3527 },
3528 With {
3530 modulus: u64,
3532 remainder: u64,
3534 },
3535 Default,
3537}
3538
3539impl fmt::Display for ForValues {
3540 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3541 match self {
3542 ForValues::In(values) => {
3543 write!(f, "FOR VALUES IN ({})", display_comma_separated(values))
3544 }
3545 ForValues::From { from, to } => {
3546 write!(
3547 f,
3548 "FOR VALUES FROM ({}) TO ({})",
3549 display_comma_separated(from),
3550 display_comma_separated(to)
3551 )
3552 }
3553 ForValues::With { modulus, remainder } => {
3554 write!(
3555 f,
3556 "FOR VALUES WITH (MODULUS {modulus}, REMAINDER {remainder})"
3557 )
3558 }
3559 ForValues::Default => write!(f, "DEFAULT"),
3560 }
3561 }
3562}
3563
3564#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3569#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3570#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3571pub enum PartitionBoundValue {
3572 Expr(Expr),
3574 MinValue,
3576 MaxValue,
3578}
3579
3580impl fmt::Display for PartitionBoundValue {
3581 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3582 match self {
3583 PartitionBoundValue::Expr(expr) => write!(f, "{expr}"),
3584 PartitionBoundValue::MinValue => write!(f, "MINVALUE"),
3585 PartitionBoundValue::MaxValue => write!(f, "MAXVALUE"),
3586 }
3587 }
3588}
3589
3590#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3594#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3595#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3596pub enum DistStyle {
3597 Auto,
3599 Even,
3601 Key,
3603 All,
3605}
3606
3607impl fmt::Display for DistStyle {
3608 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3609 match self {
3610 DistStyle::Auto => write!(f, "AUTO"),
3611 DistStyle::Even => write!(f, "EVEN"),
3612 DistStyle::Key => write!(f, "KEY"),
3613 DistStyle::All => write!(f, "ALL"),
3614 }
3615 }
3616}
3617
3618#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3619#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3620#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3621pub struct CreateDomain {
3634 pub name: ObjectName,
3636 pub data_type: DataType,
3638 pub collation: Option<Ident>,
3640 pub default: Option<Expr>,
3642 pub constraints: Vec<TableConstraint>,
3644}
3645
3646impl fmt::Display for CreateDomain {
3647 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3648 write!(
3649 f,
3650 "CREATE DOMAIN {name} AS {data_type}",
3651 name = self.name,
3652 data_type = self.data_type
3653 )?;
3654 if let Some(collation) = &self.collation {
3655 write!(f, " COLLATE {collation}")?;
3656 }
3657 if let Some(default) = &self.default {
3658 write!(f, " DEFAULT {default}")?;
3659 }
3660 if !self.constraints.is_empty() {
3661 write!(f, " {}", display_separated(&self.constraints, " "))?;
3662 }
3663 Ok(())
3664 }
3665}
3666
3667#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3669#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3670#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3671pub enum FunctionReturnType {
3672 DataType(DataType),
3674 SetOf(DataType),
3678}
3679
3680impl fmt::Display for FunctionReturnType {
3681 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3682 match self {
3683 FunctionReturnType::DataType(data_type) => write!(f, "{data_type}"),
3684 FunctionReturnType::SetOf(data_type) => write!(f, "SETOF {data_type}"),
3685 }
3686 }
3687}
3688
3689#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3690#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3691#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3692pub struct CreateFunction {
3694 pub or_alter: bool,
3698 pub or_replace: bool,
3700 pub temporary: bool,
3702 pub if_not_exists: bool,
3704 pub name: ObjectName,
3706 pub args: Option<Vec<OperateFunctionArg>>,
3708 pub return_type: Option<FunctionReturnType>,
3710 pub function_body: Option<CreateFunctionBody>,
3718 pub behavior: Option<FunctionBehavior>,
3724 pub called_on_null: Option<FunctionCalledOnNull>,
3728 pub parallel: Option<FunctionParallel>,
3732 pub security: Option<FunctionSecurity>,
3736 pub set_params: Vec<FunctionDefinitionSetParam>,
3740 pub using: Option<CreateFunctionUsing>,
3742 pub language: Option<Ident>,
3750 pub determinism_specifier: Option<FunctionDeterminismSpecifier>,
3754 pub options: Option<Vec<SqlOption>>,
3758 pub remote_connection: Option<ObjectName>,
3768}
3769
3770impl fmt::Display for CreateFunction {
3771 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3772 write!(
3773 f,
3774 "CREATE {or_alter}{or_replace}{temp}FUNCTION {if_not_exists}{name}",
3775 name = self.name,
3776 temp = if self.temporary { "TEMPORARY " } else { "" },
3777 or_alter = if self.or_alter { "OR ALTER " } else { "" },
3778 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3779 if_not_exists = if self.if_not_exists {
3780 "IF NOT EXISTS "
3781 } else {
3782 ""
3783 },
3784 )?;
3785 if let Some(args) = &self.args {
3786 write!(f, "({})", display_comma_separated(args))?;
3787 }
3788 if let Some(return_type) = &self.return_type {
3789 write!(f, " RETURNS {return_type}")?;
3790 }
3791 if let Some(determinism_specifier) = &self.determinism_specifier {
3792 write!(f, " {determinism_specifier}")?;
3793 }
3794 if let Some(language) = &self.language {
3795 write!(f, " LANGUAGE {language}")?;
3796 }
3797 if let Some(behavior) = &self.behavior {
3798 write!(f, " {behavior}")?;
3799 }
3800 if let Some(called_on_null) = &self.called_on_null {
3801 write!(f, " {called_on_null}")?;
3802 }
3803 if let Some(parallel) = &self.parallel {
3804 write!(f, " {parallel}")?;
3805 }
3806 if let Some(security) = &self.security {
3807 write!(f, " {security}")?;
3808 }
3809 for set_param in &self.set_params {
3810 write!(f, " {set_param}")?;
3811 }
3812 if let Some(remote_connection) = &self.remote_connection {
3813 write!(f, " REMOTE WITH CONNECTION {remote_connection}")?;
3814 }
3815 if let Some(CreateFunctionBody::AsBeforeOptions { body, link_symbol }) = &self.function_body
3816 {
3817 write!(f, " AS {body}")?;
3818 if let Some(link_symbol) = link_symbol {
3819 write!(f, ", {link_symbol}")?;
3820 }
3821 }
3822 if let Some(CreateFunctionBody::Return(function_body)) = &self.function_body {
3823 write!(f, " RETURN {function_body}")?;
3824 }
3825 if let Some(CreateFunctionBody::AsReturnExpr(function_body)) = &self.function_body {
3826 write!(f, " AS RETURN {function_body}")?;
3827 }
3828 if let Some(CreateFunctionBody::AsReturnSelect(function_body)) = &self.function_body {
3829 write!(f, " AS RETURN {function_body}")?;
3830 }
3831 if let Some(using) = &self.using {
3832 write!(f, " {using}")?;
3833 }
3834 if let Some(options) = &self.options {
3835 write!(
3836 f,
3837 " OPTIONS({})",
3838 display_comma_separated(options.as_slice())
3839 )?;
3840 }
3841 if let Some(CreateFunctionBody::AsAfterOptions(function_body)) = &self.function_body {
3842 write!(f, " AS {function_body}")?;
3843 }
3844 if let Some(CreateFunctionBody::AsBeginEnd(bes)) = &self.function_body {
3845 write!(f, " AS {bes}")?;
3846 }
3847 Ok(())
3848 }
3849}
3850
3851#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3861#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3862#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3863pub struct CreateConnector {
3864 pub name: Ident,
3866 pub if_not_exists: bool,
3868 pub connector_type: Option<String>,
3870 pub url: Option<String>,
3872 pub comment: Option<CommentDef>,
3874 pub with_dcproperties: Option<Vec<SqlOption>>,
3876}
3877
3878impl fmt::Display for CreateConnector {
3879 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3880 write!(
3881 f,
3882 "CREATE CONNECTOR {if_not_exists}{name}",
3883 if_not_exists = if self.if_not_exists {
3884 "IF NOT EXISTS "
3885 } else {
3886 ""
3887 },
3888 name = self.name,
3889 )?;
3890
3891 if let Some(connector_type) = &self.connector_type {
3892 write!(f, " TYPE '{connector_type}'")?;
3893 }
3894
3895 if let Some(url) = &self.url {
3896 write!(f, " URL '{url}'")?;
3897 }
3898
3899 if let Some(comment) = &self.comment {
3900 write!(f, " COMMENT = '{comment}'")?;
3901 }
3902
3903 if let Some(with_dcproperties) = &self.with_dcproperties {
3904 write!(
3905 f,
3906 " WITH DCPROPERTIES({})",
3907 display_comma_separated(with_dcproperties)
3908 )?;
3909 }
3910
3911 Ok(())
3912 }
3913}
3914
3915#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3920#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3921#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3922pub enum AlterSchemaOperation {
3923 SetDefaultCollate {
3925 collate: Expr,
3927 },
3928 AddReplica {
3930 replica: Ident,
3932 options: Option<Vec<SqlOption>>,
3934 },
3935 DropReplica {
3937 replica: Ident,
3939 },
3940 SetOptionsParens {
3942 options: Vec<SqlOption>,
3944 },
3945 Rename {
3947 name: ObjectName,
3949 },
3950 OwnerTo {
3952 owner: Owner,
3954 },
3955}
3956
3957impl fmt::Display for AlterSchemaOperation {
3958 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3959 match self {
3960 AlterSchemaOperation::SetDefaultCollate { collate } => {
3961 write!(f, "SET DEFAULT COLLATE {collate}")
3962 }
3963 AlterSchemaOperation::AddReplica { replica, options } => {
3964 write!(f, "ADD REPLICA {replica}")?;
3965 if let Some(options) = options {
3966 write!(f, " OPTIONS ({})", display_comma_separated(options))?;
3967 }
3968 Ok(())
3969 }
3970 AlterSchemaOperation::DropReplica { replica } => write!(f, "DROP REPLICA {replica}"),
3971 AlterSchemaOperation::SetOptionsParens { options } => {
3972 write!(f, "SET OPTIONS ({})", display_comma_separated(options))
3973 }
3974 AlterSchemaOperation::Rename { name } => write!(f, "RENAME TO {name}"),
3975 AlterSchemaOperation::OwnerTo { owner } => write!(f, "OWNER TO {owner}"),
3976 }
3977 }
3978}
3979#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3985#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3986#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3987pub enum RenameTableNameKind {
3988 As(ObjectName),
3990 To(ObjectName),
3992}
3993
3994impl fmt::Display for RenameTableNameKind {
3995 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3996 match self {
3997 RenameTableNameKind::As(name) => write!(f, "AS {name}"),
3998 RenameTableNameKind::To(name) => write!(f, "TO {name}"),
3999 }
4000 }
4001}
4002
4003#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4004#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4005#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4006pub struct AlterSchema {
4008 pub name: ObjectName,
4010 pub if_exists: bool,
4012 pub operations: Vec<AlterSchemaOperation>,
4014}
4015
4016impl fmt::Display for AlterSchema {
4017 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4018 write!(f, "ALTER SCHEMA ")?;
4019 if self.if_exists {
4020 write!(f, "IF EXISTS ")?;
4021 }
4022 write!(f, "{}", self.name)?;
4023 for operation in &self.operations {
4024 write!(f, " {operation}")?;
4025 }
4026
4027 Ok(())
4028 }
4029}
4030
4031impl Spanned for RenameTableNameKind {
4032 fn span(&self) -> Span {
4033 match self {
4034 RenameTableNameKind::As(name) => name.span(),
4035 RenameTableNameKind::To(name) => name.span(),
4036 }
4037 }
4038}
4039
4040#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
4041#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4042#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4043pub enum TriggerObjectKind {
4045 For(TriggerObject),
4047 ForEach(TriggerObject),
4049}
4050
4051impl Display for TriggerObjectKind {
4052 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4053 match self {
4054 TriggerObjectKind::For(obj) => write!(f, "FOR {obj}"),
4055 TriggerObjectKind::ForEach(obj) => write!(f, "FOR EACH {obj}"),
4056 }
4057 }
4058}
4059
4060#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4061#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4062#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4063pub struct CreateTrigger {
4077 pub or_alter: bool,
4081 pub temporary: bool,
4098 pub or_replace: bool,
4108 pub is_constraint: bool,
4110 pub name: ObjectName,
4112 pub period: Option<TriggerPeriod>,
4141 pub period_before_table: bool,
4152 pub events: Vec<TriggerEvent>,
4154 pub table_name: ObjectName,
4156 pub referenced_table_name: Option<ObjectName>,
4159 pub referencing: Vec<TriggerReferencing>,
4161 pub trigger_object: Option<TriggerObjectKind>,
4166 pub condition: Option<Expr>,
4168 pub exec_body: Option<TriggerExecBody>,
4170 pub statements_as: bool,
4172 pub statements: Option<ConditionalStatements>,
4174 pub characteristics: Option<ConstraintCharacteristics>,
4176}
4177
4178impl Display for CreateTrigger {
4179 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4180 let CreateTrigger {
4181 or_alter,
4182 temporary,
4183 or_replace,
4184 is_constraint,
4185 name,
4186 period_before_table,
4187 period,
4188 events,
4189 table_name,
4190 referenced_table_name,
4191 referencing,
4192 trigger_object,
4193 condition,
4194 exec_body,
4195 statements_as,
4196 statements,
4197 characteristics,
4198 } = self;
4199 write!(
4200 f,
4201 "CREATE {temporary}{or_alter}{or_replace}{is_constraint}TRIGGER {name} ",
4202 temporary = if *temporary { "TEMPORARY " } else { "" },
4203 or_alter = if *or_alter { "OR ALTER " } else { "" },
4204 or_replace = if *or_replace { "OR REPLACE " } else { "" },
4205 is_constraint = if *is_constraint { "CONSTRAINT " } else { "" },
4206 )?;
4207
4208 if *period_before_table {
4209 if let Some(p) = period {
4210 write!(f, "{p} ")?;
4211 }
4212 if !events.is_empty() {
4213 write!(f, "{} ", display_separated(events, " OR "))?;
4214 }
4215 write!(f, "ON {table_name}")?;
4216 } else {
4217 write!(f, "ON {table_name} ")?;
4218 if let Some(p) = period {
4219 write!(f, "{p}")?;
4220 }
4221 if !events.is_empty() {
4222 write!(f, " {}", display_separated(events, ", "))?;
4223 }
4224 }
4225
4226 if let Some(referenced_table_name) = referenced_table_name {
4227 write!(f, " FROM {referenced_table_name}")?;
4228 }
4229
4230 if let Some(characteristics) = characteristics {
4231 write!(f, " {characteristics}")?;
4232 }
4233
4234 if !referencing.is_empty() {
4235 write!(f, " REFERENCING {}", display_separated(referencing, " "))?;
4236 }
4237
4238 if let Some(trigger_object) = trigger_object {
4239 write!(f, " {trigger_object}")?;
4240 }
4241 if let Some(condition) = condition {
4242 write!(f, " WHEN {condition}")?;
4243 }
4244 if let Some(exec_body) = exec_body {
4245 write!(f, " EXECUTE {exec_body}")?;
4246 }
4247 if let Some(statements) = statements {
4248 if *statements_as {
4249 write!(f, " AS")?;
4250 }
4251 write!(f, " {statements}")?;
4252 }
4253 Ok(())
4254 }
4255}
4256
4257#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4258#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4259#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4260pub struct DropTrigger {
4267 pub if_exists: bool,
4269 pub trigger_name: ObjectName,
4271 pub table_name: Option<ObjectName>,
4273 pub option: Option<ReferentialAction>,
4275}
4276
4277impl fmt::Display for DropTrigger {
4278 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4279 let DropTrigger {
4280 if_exists,
4281 trigger_name,
4282 table_name,
4283 option,
4284 } = self;
4285 write!(f, "DROP TRIGGER")?;
4286 if *if_exists {
4287 write!(f, " IF EXISTS")?;
4288 }
4289 match &table_name {
4290 Some(table_name) => write!(f, " {trigger_name} ON {table_name}")?,
4291 None => write!(f, " {trigger_name}")?,
4292 };
4293 if let Some(option) = option {
4294 write!(f, " {option}")?;
4295 }
4296 Ok(())
4297 }
4298}
4299
4300#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4306#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4307#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4308pub struct Truncate {
4309 pub table_names: Vec<super::TruncateTableTarget>,
4311 pub partitions: Option<Vec<Expr>>,
4313 pub table: bool,
4315 pub if_exists: bool,
4317 pub identity: Option<super::TruncateIdentityOption>,
4319 pub cascade: Option<super::CascadeOption>,
4321 pub on_cluster: Option<Ident>,
4324}
4325
4326impl fmt::Display for Truncate {
4327 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4328 let table = if self.table { "TABLE " } else { "" };
4329 let if_exists = if self.if_exists { "IF EXISTS " } else { "" };
4330
4331 write!(
4332 f,
4333 "TRUNCATE {table}{if_exists}{table_names}",
4334 table_names = display_comma_separated(&self.table_names)
4335 )?;
4336
4337 if let Some(identity) = &self.identity {
4338 match identity {
4339 super::TruncateIdentityOption::Restart => write!(f, " RESTART IDENTITY")?,
4340 super::TruncateIdentityOption::Continue => write!(f, " CONTINUE IDENTITY")?,
4341 }
4342 }
4343 if let Some(cascade) = &self.cascade {
4344 match cascade {
4345 super::CascadeOption::Cascade => write!(f, " CASCADE")?,
4346 super::CascadeOption::Restrict => write!(f, " RESTRICT")?,
4347 }
4348 }
4349
4350 if let Some(ref parts) = &self.partitions {
4351 if !parts.is_empty() {
4352 write!(f, " PARTITION ({})", display_comma_separated(parts))?;
4353 }
4354 }
4355 if let Some(on_cluster) = &self.on_cluster {
4356 write!(f, " ON CLUSTER {on_cluster}")?;
4357 }
4358 Ok(())
4359 }
4360}
4361
4362impl Spanned for Truncate {
4363 fn span(&self) -> Span {
4364 Span::union_iter(
4365 self.table_names.iter().map(|i| i.name.span()).chain(
4366 self.partitions
4367 .iter()
4368 .flat_map(|i| i.iter().map(|k| k.span())),
4369 ),
4370 )
4371 }
4372}
4373
4374#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4381#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4382#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4383pub struct Msck {
4384 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4386 pub table_name: ObjectName,
4387 pub repair: bool,
4389 pub partition_action: Option<super::AddDropSync>,
4391}
4392
4393impl fmt::Display for Msck {
4394 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4395 write!(
4396 f,
4397 "MSCK {repair}TABLE {table}",
4398 repair = if self.repair { "REPAIR " } else { "" },
4399 table = self.table_name
4400 )?;
4401 if let Some(pa) = &self.partition_action {
4402 write!(f, " {pa}")?;
4403 }
4404 Ok(())
4405 }
4406}
4407
4408impl Spanned for Msck {
4409 fn span(&self) -> Span {
4410 self.table_name.span()
4411 }
4412}
4413
4414#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4416#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4417#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4418pub struct CreateView {
4419 pub or_alter: bool,
4423 pub or_replace: bool,
4425 pub materialized: bool,
4427 pub secure: bool,
4430 pub name: ObjectName,
4432 pub name_before_not_exists: bool,
4443 pub columns: Vec<ViewColumnDef>,
4445 pub query: Box<Query>,
4447 pub options: CreateTableOptions,
4449 pub cluster_by: Vec<Ident>,
4451 pub comment: Option<String>,
4454 pub with_no_schema_binding: bool,
4456 pub if_not_exists: bool,
4458 pub temporary: bool,
4460 pub copy_grants: bool,
4463 pub to: Option<ObjectName>,
4466 pub params: Option<CreateViewParams>,
4468}
4469
4470impl fmt::Display for CreateView {
4471 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4472 write!(
4473 f,
4474 "CREATE {or_alter}{or_replace}",
4475 or_alter = if self.or_alter { "OR ALTER " } else { "" },
4476 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
4477 )?;
4478 if let Some(ref params) = self.params {
4479 params.fmt(f)?;
4480 }
4481 write!(
4482 f,
4483 "{secure}{materialized}{temporary}VIEW {if_not_and_name}{to}",
4484 if_not_and_name = if self.if_not_exists {
4485 if self.name_before_not_exists {
4486 format!("{} IF NOT EXISTS", self.name)
4487 } else {
4488 format!("IF NOT EXISTS {}", self.name)
4489 }
4490 } else {
4491 format!("{}", self.name)
4492 },
4493 secure = if self.secure { "SECURE " } else { "" },
4494 materialized = if self.materialized {
4495 "MATERIALIZED "
4496 } else {
4497 ""
4498 },
4499 temporary = if self.temporary { "TEMPORARY " } else { "" },
4500 to = self
4501 .to
4502 .as_ref()
4503 .map(|to| format!(" TO {to}"))
4504 .unwrap_or_default()
4505 )?;
4506 if self.copy_grants {
4507 write!(f, " COPY GRANTS")?;
4508 }
4509 if !self.columns.is_empty() {
4510 write!(f, " ({})", display_comma_separated(&self.columns))?;
4511 }
4512 if matches!(self.options, CreateTableOptions::With(_)) {
4513 write!(f, " {}", self.options)?;
4514 }
4515 if let Some(ref comment) = self.comment {
4516 write!(f, " COMMENT = '{}'", escape_single_quote_string(comment))?;
4517 }
4518 if !self.cluster_by.is_empty() {
4519 write!(
4520 f,
4521 " CLUSTER BY ({})",
4522 display_comma_separated(&self.cluster_by)
4523 )?;
4524 }
4525 if matches!(self.options, CreateTableOptions::Options(_)) {
4526 write!(f, " {}", self.options)?;
4527 }
4528 f.write_str(" AS")?;
4529 SpaceOrNewline.fmt(f)?;
4530 self.query.fmt(f)?;
4531 if self.with_no_schema_binding {
4532 write!(f, " WITH NO SCHEMA BINDING")?;
4533 }
4534 Ok(())
4535 }
4536}
4537
4538#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4541#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4542#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4543pub struct CreateExtension {
4544 pub name: Ident,
4546 pub if_not_exists: bool,
4548 pub cascade: bool,
4550 pub schema: Option<Ident>,
4552 pub version: Option<Ident>,
4554}
4555
4556impl fmt::Display for CreateExtension {
4557 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4558 write!(
4559 f,
4560 "CREATE EXTENSION {if_not_exists}{name}",
4561 if_not_exists = if self.if_not_exists {
4562 "IF NOT EXISTS "
4563 } else {
4564 ""
4565 },
4566 name = self.name
4567 )?;
4568 if self.cascade || self.schema.is_some() || self.version.is_some() {
4569 write!(f, " WITH")?;
4570
4571 if let Some(name) = &self.schema {
4572 write!(f, " SCHEMA {name}")?;
4573 }
4574 if let Some(version) = &self.version {
4575 write!(f, " VERSION {version}")?;
4576 }
4577 if self.cascade {
4578 write!(f, " CASCADE")?;
4579 }
4580 }
4581
4582 Ok(())
4583 }
4584}
4585
4586impl Spanned for CreateExtension {
4587 fn span(&self) -> Span {
4588 Span::empty()
4589 }
4590}
4591
4592#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4600#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4601#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4602pub struct DropExtension {
4603 pub names: Vec<Ident>,
4605 pub if_exists: bool,
4607 pub cascade_or_restrict: Option<ReferentialAction>,
4609}
4610
4611impl fmt::Display for DropExtension {
4612 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4613 write!(f, "DROP EXTENSION")?;
4614 if self.if_exists {
4615 write!(f, " IF EXISTS")?;
4616 }
4617 write!(f, " {}", display_comma_separated(&self.names))?;
4618 if let Some(cascade_or_restrict) = &self.cascade_or_restrict {
4619 write!(f, " {cascade_or_restrict}")?;
4620 }
4621 Ok(())
4622 }
4623}
4624
4625impl Spanned for DropExtension {
4626 fn span(&self) -> Span {
4627 Span::empty()
4628 }
4629}
4630
4631#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4634#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4635#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4636pub struct CreateCollation {
4637 pub if_not_exists: bool,
4639 pub name: ObjectName,
4641 pub definition: CreateCollationDefinition,
4643}
4644
4645#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4647#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4648#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4649pub enum CreateCollationDefinition {
4650 From(ObjectName),
4656 Options(Vec<SqlOption>),
4662}
4663
4664impl fmt::Display for CreateCollation {
4665 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4666 write!(
4667 f,
4668 "CREATE COLLATION {if_not_exists}{name}",
4669 if_not_exists = if self.if_not_exists {
4670 "IF NOT EXISTS "
4671 } else {
4672 ""
4673 },
4674 name = self.name
4675 )?;
4676 match &self.definition {
4677 CreateCollationDefinition::From(existing_collation) => {
4678 write!(f, " FROM {existing_collation}")
4679 }
4680 CreateCollationDefinition::Options(options) => {
4681 write!(f, " ({})", display_comma_separated(options))
4682 }
4683 }
4684 }
4685}
4686
4687impl Spanned for CreateCollation {
4688 fn span(&self) -> Span {
4689 Span::empty()
4690 }
4691}
4692
4693#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4696#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4697#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4698pub struct AlterCollation {
4699 pub name: ObjectName,
4701 pub operation: AlterCollationOperation,
4703}
4704
4705#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4707#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4708#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4709pub enum AlterCollationOperation {
4710 RenameTo {
4716 new_name: Ident,
4718 },
4719 OwnerTo(Owner),
4725 SetSchema {
4731 schema_name: ObjectName,
4733 },
4734 RefreshVersion,
4740}
4741
4742impl fmt::Display for AlterCollationOperation {
4743 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4744 match self {
4745 AlterCollationOperation::RenameTo { new_name } => write!(f, "RENAME TO {new_name}"),
4746 AlterCollationOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
4747 AlterCollationOperation::SetSchema { schema_name } => {
4748 write!(f, "SET SCHEMA {schema_name}")
4749 }
4750 AlterCollationOperation::RefreshVersion => write!(f, "REFRESH VERSION"),
4751 }
4752 }
4753}
4754
4755impl fmt::Display for AlterCollation {
4756 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4757 write!(f, "ALTER COLLATION {} {}", self.name, self.operation)
4758 }
4759}
4760
4761impl Spanned for AlterCollation {
4762 fn span(&self) -> Span {
4763 Span::empty()
4764 }
4765}
4766
4767#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4770#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4771#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4772pub enum AlterTableType {
4773 Iceberg,
4776 Dynamic,
4779 External,
4782}
4783
4784#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4786#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4787#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4788pub struct AlterTable {
4789 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4791 pub name: ObjectName,
4792 pub if_exists: bool,
4794 pub only: bool,
4796 pub operations: Vec<AlterTableOperation>,
4798 pub location: Option<HiveSetLocation>,
4800 pub on_cluster: Option<Ident>,
4804 pub table_type: Option<AlterTableType>,
4806 pub end_token: AttachedToken,
4808}
4809
4810impl fmt::Display for AlterTable {
4811 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4812 match &self.table_type {
4813 Some(AlterTableType::Iceberg) => write!(f, "ALTER ICEBERG TABLE ")?,
4814 Some(AlterTableType::Dynamic) => write!(f, "ALTER DYNAMIC TABLE ")?,
4815 Some(AlterTableType::External) => write!(f, "ALTER EXTERNAL TABLE ")?,
4816 None => write!(f, "ALTER TABLE ")?,
4817 }
4818
4819 if self.if_exists {
4820 write!(f, "IF EXISTS ")?;
4821 }
4822 if self.only {
4823 write!(f, "ONLY ")?;
4824 }
4825 write!(f, "{} ", &self.name)?;
4826 if let Some(cluster) = &self.on_cluster {
4827 write!(f, "ON CLUSTER {cluster} ")?;
4828 }
4829 write!(f, "{}", display_comma_separated(&self.operations))?;
4830 if let Some(loc) = &self.location {
4831 write!(f, " {loc}")?
4832 }
4833 Ok(())
4834 }
4835}
4836
4837#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4839#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4840#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4841pub struct DropFunction {
4842 pub if_exists: bool,
4844 pub func_desc: Vec<FunctionDesc>,
4846 pub drop_behavior: Option<DropBehavior>,
4848}
4849
4850impl fmt::Display for DropFunction {
4851 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4852 write!(
4853 f,
4854 "DROP FUNCTION{} {}",
4855 if self.if_exists { " IF EXISTS" } else { "" },
4856 display_comma_separated(&self.func_desc),
4857 )?;
4858 if let Some(op) = &self.drop_behavior {
4859 write!(f, " {op}")?;
4860 }
4861 Ok(())
4862 }
4863}
4864
4865impl Spanned for DropFunction {
4866 fn span(&self) -> Span {
4867 Span::empty()
4868 }
4869}
4870
4871#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4874#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4875#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4876pub struct CreateOperator {
4877 pub name: ObjectName,
4879 pub function: ObjectName,
4881 pub is_procedure: bool,
4883 pub left_arg: Option<DataType>,
4885 pub right_arg: Option<DataType>,
4887 pub options: Vec<OperatorOption>,
4889}
4890
4891#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4894#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4895#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4896pub struct CreateOperatorFamily {
4897 pub name: ObjectName,
4899 pub using: Ident,
4901}
4902
4903#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4906#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4907#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4908pub struct CreateOperatorClass {
4909 pub name: ObjectName,
4911 pub default: bool,
4913 pub for_type: DataType,
4915 pub using: Ident,
4917 pub family: Option<ObjectName>,
4919 pub items: Vec<OperatorClassItem>,
4921}
4922
4923impl fmt::Display for CreateOperator {
4924 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4925 write!(f, "CREATE OPERATOR {} (", self.name)?;
4926
4927 let function_keyword = if self.is_procedure {
4928 "PROCEDURE"
4929 } else {
4930 "FUNCTION"
4931 };
4932 let mut params = vec![format!("{} = {}", function_keyword, self.function)];
4933
4934 if let Some(left_arg) = &self.left_arg {
4935 params.push(format!("LEFTARG = {}", left_arg));
4936 }
4937 if let Some(right_arg) = &self.right_arg {
4938 params.push(format!("RIGHTARG = {}", right_arg));
4939 }
4940
4941 for option in &self.options {
4942 params.push(option.to_string());
4943 }
4944
4945 write!(f, "{}", params.join(", "))?;
4946 write!(f, ")")
4947 }
4948}
4949
4950impl fmt::Display for CreateOperatorFamily {
4951 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4952 write!(
4953 f,
4954 "CREATE OPERATOR FAMILY {} USING {}",
4955 self.name, self.using
4956 )
4957 }
4958}
4959
4960impl fmt::Display for CreateOperatorClass {
4961 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4962 write!(f, "CREATE OPERATOR CLASS {}", self.name)?;
4963 if self.default {
4964 write!(f, " DEFAULT")?;
4965 }
4966 write!(f, " FOR TYPE {} USING {}", self.for_type, self.using)?;
4967 if let Some(family) = &self.family {
4968 write!(f, " FAMILY {}", family)?;
4969 }
4970 write!(f, " AS {}", display_comma_separated(&self.items))
4971 }
4972}
4973
4974#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4976#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4977#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4978pub struct OperatorArgTypes {
4979 pub left: DataType,
4981 pub right: DataType,
4983}
4984
4985impl fmt::Display for OperatorArgTypes {
4986 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4987 write!(f, "{}, {}", self.left, self.right)
4988 }
4989}
4990
4991#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4993#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4994#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4995pub enum OperatorClassItem {
4996 Operator {
4998 strategy_number: u64,
5000 operator_name: ObjectName,
5002 op_types: Option<OperatorArgTypes>,
5004 purpose: Option<OperatorPurpose>,
5006 },
5007 Function {
5009 support_number: u64,
5011 op_types: Option<Vec<DataType>>,
5013 function_name: ObjectName,
5015 argument_types: Vec<DataType>,
5017 },
5018 Storage {
5020 storage_type: DataType,
5022 },
5023}
5024
5025#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5027#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5028#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5029pub enum OperatorPurpose {
5030 ForSearch,
5032 ForOrderBy {
5034 sort_family: ObjectName,
5036 },
5037}
5038
5039impl fmt::Display for OperatorClassItem {
5040 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5041 match self {
5042 OperatorClassItem::Operator {
5043 strategy_number,
5044 operator_name,
5045 op_types,
5046 purpose,
5047 } => {
5048 write!(f, "OPERATOR {strategy_number} {operator_name}")?;
5049 if let Some(types) = op_types {
5050 write!(f, " ({types})")?;
5051 }
5052 if let Some(purpose) = purpose {
5053 write!(f, " {purpose}")?;
5054 }
5055 Ok(())
5056 }
5057 OperatorClassItem::Function {
5058 support_number,
5059 op_types,
5060 function_name,
5061 argument_types,
5062 } => {
5063 write!(f, "FUNCTION {support_number}")?;
5064 if let Some(types) = op_types {
5065 write!(f, " ({})", display_comma_separated(types))?;
5066 }
5067 write!(f, " {function_name}")?;
5068 if !argument_types.is_empty() {
5069 write!(f, "({})", display_comma_separated(argument_types))?;
5070 }
5071 Ok(())
5072 }
5073 OperatorClassItem::Storage { storage_type } => {
5074 write!(f, "STORAGE {storage_type}")
5075 }
5076 }
5077 }
5078}
5079
5080impl fmt::Display for OperatorPurpose {
5081 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5082 match self {
5083 OperatorPurpose::ForSearch => write!(f, "FOR SEARCH"),
5084 OperatorPurpose::ForOrderBy { sort_family } => {
5085 write!(f, "FOR ORDER BY {sort_family}")
5086 }
5087 }
5088 }
5089}
5090
5091#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5094#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5095#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5096pub struct DropOperator {
5097 pub if_exists: bool,
5099 pub operators: Vec<DropOperatorSignature>,
5101 pub drop_behavior: Option<DropBehavior>,
5103}
5104
5105#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5107#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5108#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5109pub struct DropOperatorSignature {
5110 pub name: ObjectName,
5112 pub left_type: Option<DataType>,
5114 pub right_type: DataType,
5116}
5117
5118impl fmt::Display for DropOperatorSignature {
5119 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5120 write!(f, "{} (", self.name)?;
5121 if let Some(left_type) = &self.left_type {
5122 write!(f, "{}", left_type)?;
5123 } else {
5124 write!(f, "NONE")?;
5125 }
5126 write!(f, ", {})", self.right_type)
5127 }
5128}
5129
5130impl fmt::Display for DropOperator {
5131 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5132 write!(f, "DROP OPERATOR")?;
5133 if self.if_exists {
5134 write!(f, " IF EXISTS")?;
5135 }
5136 write!(f, " {}", display_comma_separated(&self.operators))?;
5137 if let Some(drop_behavior) = &self.drop_behavior {
5138 write!(f, " {}", drop_behavior)?;
5139 }
5140 Ok(())
5141 }
5142}
5143
5144impl Spanned for DropOperator {
5145 fn span(&self) -> Span {
5146 Span::empty()
5147 }
5148}
5149
5150#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5153#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5154#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5155pub struct DropOperatorFamily {
5156 pub if_exists: bool,
5158 pub names: Vec<ObjectName>,
5160 pub using: Ident,
5162 pub drop_behavior: Option<DropBehavior>,
5164}
5165
5166impl fmt::Display for DropOperatorFamily {
5167 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5168 write!(f, "DROP OPERATOR FAMILY")?;
5169 if self.if_exists {
5170 write!(f, " IF EXISTS")?;
5171 }
5172 write!(f, " {}", display_comma_separated(&self.names))?;
5173 write!(f, " USING {}", self.using)?;
5174 if let Some(drop_behavior) = &self.drop_behavior {
5175 write!(f, " {}", drop_behavior)?;
5176 }
5177 Ok(())
5178 }
5179}
5180
5181impl Spanned for DropOperatorFamily {
5182 fn span(&self) -> Span {
5183 Span::empty()
5184 }
5185}
5186
5187#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5190#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5191#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5192pub struct DropOperatorClass {
5193 pub if_exists: bool,
5195 pub names: Vec<ObjectName>,
5197 pub using: Ident,
5199 pub drop_behavior: Option<DropBehavior>,
5201}
5202
5203impl fmt::Display for DropOperatorClass {
5204 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5205 write!(f, "DROP OPERATOR CLASS")?;
5206 if self.if_exists {
5207 write!(f, " IF EXISTS")?;
5208 }
5209 write!(f, " {}", display_comma_separated(&self.names))?;
5210 write!(f, " USING {}", self.using)?;
5211 if let Some(drop_behavior) = &self.drop_behavior {
5212 write!(f, " {}", drop_behavior)?;
5213 }
5214 Ok(())
5215 }
5216}
5217
5218impl Spanned for DropOperatorClass {
5219 fn span(&self) -> Span {
5220 Span::empty()
5221 }
5222}
5223
5224#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5226#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5227#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5228pub enum OperatorFamilyItem {
5229 Operator {
5231 strategy_number: u64,
5233 operator_name: ObjectName,
5235 op_types: Vec<DataType>,
5237 purpose: Option<OperatorPurpose>,
5239 },
5240 Function {
5242 support_number: u64,
5244 op_types: Option<Vec<DataType>>,
5246 function_name: ObjectName,
5248 argument_types: Vec<DataType>,
5250 },
5251}
5252
5253#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5255#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5256#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5257pub enum OperatorFamilyDropItem {
5258 Operator {
5260 strategy_number: u64,
5262 op_types: Vec<DataType>,
5264 },
5265 Function {
5267 support_number: u64,
5269 op_types: Vec<DataType>,
5271 },
5272}
5273
5274impl fmt::Display for OperatorFamilyItem {
5275 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5276 match self {
5277 OperatorFamilyItem::Operator {
5278 strategy_number,
5279 operator_name,
5280 op_types,
5281 purpose,
5282 } => {
5283 write!(
5284 f,
5285 "OPERATOR {strategy_number} {operator_name} ({})",
5286 display_comma_separated(op_types)
5287 )?;
5288 if let Some(purpose) = purpose {
5289 write!(f, " {purpose}")?;
5290 }
5291 Ok(())
5292 }
5293 OperatorFamilyItem::Function {
5294 support_number,
5295 op_types,
5296 function_name,
5297 argument_types,
5298 } => {
5299 write!(f, "FUNCTION {support_number}")?;
5300 if let Some(types) = op_types {
5301 write!(f, " ({})", display_comma_separated(types))?;
5302 }
5303 write!(f, " {function_name}")?;
5304 if !argument_types.is_empty() {
5305 write!(f, "({})", display_comma_separated(argument_types))?;
5306 }
5307 Ok(())
5308 }
5309 }
5310 }
5311}
5312
5313impl fmt::Display for OperatorFamilyDropItem {
5314 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5315 match self {
5316 OperatorFamilyDropItem::Operator {
5317 strategy_number,
5318 op_types,
5319 } => {
5320 write!(
5321 f,
5322 "OPERATOR {strategy_number} ({})",
5323 display_comma_separated(op_types)
5324 )
5325 }
5326 OperatorFamilyDropItem::Function {
5327 support_number,
5328 op_types,
5329 } => {
5330 write!(
5331 f,
5332 "FUNCTION {support_number} ({})",
5333 display_comma_separated(op_types)
5334 )
5335 }
5336 }
5337 }
5338}
5339
5340#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5343#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5344#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5345pub struct AlterOperatorFamily {
5346 pub name: ObjectName,
5348 pub using: Ident,
5350 pub operation: AlterOperatorFamilyOperation,
5352}
5353
5354#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5356#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5357#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5358pub enum AlterOperatorFamilyOperation {
5359 Add {
5361 items: Vec<OperatorFamilyItem>,
5363 },
5364 Drop {
5366 items: Vec<OperatorFamilyDropItem>,
5368 },
5369 RenameTo {
5371 new_name: ObjectName,
5373 },
5374 OwnerTo(Owner),
5376 SetSchema {
5378 schema_name: ObjectName,
5380 },
5381}
5382
5383impl fmt::Display for AlterOperatorFamily {
5384 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5385 write!(
5386 f,
5387 "ALTER OPERATOR FAMILY {} USING {}",
5388 self.name, self.using
5389 )?;
5390 write!(f, " {}", self.operation)
5391 }
5392}
5393
5394impl fmt::Display for AlterOperatorFamilyOperation {
5395 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5396 match self {
5397 AlterOperatorFamilyOperation::Add { items } => {
5398 write!(f, "ADD {}", display_comma_separated(items))
5399 }
5400 AlterOperatorFamilyOperation::Drop { items } => {
5401 write!(f, "DROP {}", display_comma_separated(items))
5402 }
5403 AlterOperatorFamilyOperation::RenameTo { new_name } => {
5404 write!(f, "RENAME TO {new_name}")
5405 }
5406 AlterOperatorFamilyOperation::OwnerTo(owner) => {
5407 write!(f, "OWNER TO {owner}")
5408 }
5409 AlterOperatorFamilyOperation::SetSchema { schema_name } => {
5410 write!(f, "SET SCHEMA {schema_name}")
5411 }
5412 }
5413 }
5414}
5415
5416impl Spanned for AlterOperatorFamily {
5417 fn span(&self) -> Span {
5418 Span::empty()
5419 }
5420}
5421
5422#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5425#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5426#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5427pub struct AlterOperatorClass {
5428 pub name: ObjectName,
5430 pub using: Ident,
5432 pub operation: AlterOperatorClassOperation,
5434}
5435
5436#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5438#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5439#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5440pub enum AlterOperatorClassOperation {
5441 RenameTo {
5444 new_name: ObjectName,
5446 },
5447 OwnerTo(Owner),
5449 SetSchema {
5452 schema_name: ObjectName,
5454 },
5455}
5456
5457impl fmt::Display for AlterOperatorClass {
5458 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5459 write!(f, "ALTER OPERATOR CLASS {} USING {}", self.name, self.using)?;
5460 write!(f, " {}", self.operation)
5461 }
5462}
5463
5464impl fmt::Display for AlterOperatorClassOperation {
5465 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5466 match self {
5467 AlterOperatorClassOperation::RenameTo { new_name } => {
5468 write!(f, "RENAME TO {new_name}")
5469 }
5470 AlterOperatorClassOperation::OwnerTo(owner) => {
5471 write!(f, "OWNER TO {owner}")
5472 }
5473 AlterOperatorClassOperation::SetSchema { schema_name } => {
5474 write!(f, "SET SCHEMA {schema_name}")
5475 }
5476 }
5477 }
5478}
5479
5480impl Spanned for AlterOperatorClass {
5481 fn span(&self) -> Span {
5482 Span::empty()
5483 }
5484}
5485
5486#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5488#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5489#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5490pub struct AlterFunction {
5491 pub kind: AlterFunctionKind,
5493 pub function: FunctionDesc,
5495 pub aggregate_order_by: Option<Vec<OperateFunctionArg>>,
5499 pub aggregate_star: bool,
5503 pub operation: AlterFunctionOperation,
5505}
5506
5507#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5509#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5510#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5511pub enum AlterFunctionKind {
5512 Function,
5514 Aggregate,
5516}
5517
5518impl fmt::Display for AlterFunctionKind {
5519 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5520 match self {
5521 Self::Function => write!(f, "FUNCTION"),
5522 Self::Aggregate => write!(f, "AGGREGATE"),
5523 }
5524 }
5525}
5526
5527#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5529#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5530#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5531pub enum AlterFunctionOperation {
5532 RenameTo {
5534 new_name: Ident,
5536 },
5537 OwnerTo(Owner),
5539 SetSchema {
5541 schema_name: ObjectName,
5543 },
5544 DependsOnExtension {
5546 no: bool,
5548 extension_name: ObjectName,
5550 },
5551 Actions {
5553 actions: Vec<AlterFunctionAction>,
5555 restrict: bool,
5557 },
5558}
5559
5560#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5562#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5563#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5564pub enum AlterFunctionAction {
5565 CalledOnNull(FunctionCalledOnNull),
5567 Behavior(FunctionBehavior),
5569 Leakproof(bool),
5571 Security {
5573 external: bool,
5575 security: FunctionSecurity,
5577 },
5578 Parallel(FunctionParallel),
5580 Cost(Expr),
5582 Rows(Expr),
5584 Support(ObjectName),
5586 Set(FunctionDefinitionSetParam),
5589 Reset(ResetConfig),
5591}
5592
5593impl fmt::Display for AlterFunction {
5594 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5595 write!(f, "ALTER {} ", self.kind)?;
5596 match self.kind {
5597 AlterFunctionKind::Function => {
5598 write!(f, "{} ", self.function)?;
5599 }
5600 AlterFunctionKind::Aggregate => {
5601 write!(f, "{}(", self.function.name)?;
5602 if self.aggregate_star {
5603 write!(f, "*")?;
5604 } else {
5605 if let Some(args) = &self.function.args {
5606 write!(f, "{}", display_comma_separated(args))?;
5607 }
5608 if let Some(order_by_args) = &self.aggregate_order_by {
5609 if self
5610 .function
5611 .args
5612 .as_ref()
5613 .is_some_and(|args| !args.is_empty())
5614 {
5615 write!(f, " ")?;
5616 }
5617 write!(f, "ORDER BY {}", display_comma_separated(order_by_args))?;
5618 }
5619 }
5620 write!(f, ") ")?;
5621 }
5622 }
5623 write!(f, "{}", self.operation)
5624 }
5625}
5626
5627impl fmt::Display for AlterFunctionOperation {
5628 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5629 match self {
5630 AlterFunctionOperation::RenameTo { new_name } => {
5631 write!(f, "RENAME TO {new_name}")
5632 }
5633 AlterFunctionOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
5634 AlterFunctionOperation::SetSchema { schema_name } => {
5635 write!(f, "SET SCHEMA {schema_name}")
5636 }
5637 AlterFunctionOperation::DependsOnExtension { no, extension_name } => {
5638 if *no {
5639 write!(f, "NO DEPENDS ON EXTENSION {extension_name}")
5640 } else {
5641 write!(f, "DEPENDS ON EXTENSION {extension_name}")
5642 }
5643 }
5644 AlterFunctionOperation::Actions { actions, restrict } => {
5645 write!(f, "{}", display_separated(actions, " "))?;
5646 if *restrict {
5647 write!(f, " RESTRICT")?;
5648 }
5649 Ok(())
5650 }
5651 }
5652 }
5653}
5654
5655impl fmt::Display for AlterFunctionAction {
5656 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5657 match self {
5658 AlterFunctionAction::CalledOnNull(called_on_null) => write!(f, "{called_on_null}"),
5659 AlterFunctionAction::Behavior(behavior) => write!(f, "{behavior}"),
5660 AlterFunctionAction::Leakproof(leakproof) => {
5661 if *leakproof {
5662 write!(f, "LEAKPROOF")
5663 } else {
5664 write!(f, "NOT LEAKPROOF")
5665 }
5666 }
5667 AlterFunctionAction::Security { external, security } => {
5668 if *external {
5669 write!(f, "EXTERNAL ")?;
5670 }
5671 write!(f, "{security}")
5672 }
5673 AlterFunctionAction::Parallel(parallel) => write!(f, "{parallel}"),
5674 AlterFunctionAction::Cost(execution_cost) => write!(f, "COST {execution_cost}"),
5675 AlterFunctionAction::Rows(result_rows) => write!(f, "ROWS {result_rows}"),
5676 AlterFunctionAction::Support(support_function) => {
5677 write!(f, "SUPPORT {support_function}")
5678 }
5679 AlterFunctionAction::Set(set_param) => write!(f, "{set_param}"),
5680 AlterFunctionAction::Reset(reset_config) => match reset_config {
5681 ResetConfig::ALL => write!(f, "RESET ALL"),
5682 ResetConfig::ConfigName(name) => write!(f, "RESET {name}"),
5683 },
5684 }
5685 }
5686}
5687
5688impl Spanned for AlterFunction {
5689 fn span(&self) -> Span {
5690 Span::empty()
5691 }
5692}
5693
5694#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5698#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5699#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5700pub enum TextSearchObjectType {
5701 Dictionary,
5703 Configuration,
5705 Template,
5707 Parser,
5709}
5710
5711impl fmt::Display for TextSearchObjectType {
5712 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5713 match self {
5714 TextSearchObjectType::Dictionary => write!(f, "DICTIONARY"),
5715 TextSearchObjectType::Configuration => write!(f, "CONFIGURATION"),
5716 TextSearchObjectType::Template => write!(f, "TEMPLATE"),
5717 TextSearchObjectType::Parser => write!(f, "PARSER"),
5718 }
5719 }
5720}
5721
5722#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5726#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5727#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5728pub struct CreateTextSearch {
5729 pub object_type: TextSearchObjectType,
5731 pub name: ObjectName,
5733 pub options: Vec<SqlOption>,
5735}
5736
5737impl fmt::Display for CreateTextSearch {
5738 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5739 write!(
5740 f,
5741 "CREATE TEXT SEARCH {} {} ({})",
5742 self.object_type,
5743 self.name,
5744 display_comma_separated(&self.options)
5745 )
5746 }
5747}
5748
5749impl Spanned for CreateTextSearch {
5750 fn span(&self) -> Span {
5751 Span::empty()
5752 }
5753}
5754
5755#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5759#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5760#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5761pub struct AlterTextSearchOption {
5762 pub key: Ident,
5764 pub value: Option<Expr>,
5766}
5767
5768impl fmt::Display for AlterTextSearchOption {
5769 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5770 match &self.value {
5771 Some(value) => write!(f, "{} = {}", self.key, value),
5772 None => write!(f, "{}", self.key),
5773 }
5774 }
5775}
5776
5777#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5781#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5782#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5783pub enum AlterTextSearchOperation {
5784 RenameTo {
5786 new_name: Ident,
5788 },
5789 OwnerTo(Owner),
5791 SetSchema {
5793 schema_name: ObjectName,
5795 },
5796 SetOptions {
5798 options: Vec<AlterTextSearchOption>,
5800 },
5801}
5802
5803impl fmt::Display for AlterTextSearchOperation {
5804 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5805 match self {
5806 AlterTextSearchOperation::RenameTo { new_name } => write!(f, "RENAME TO {new_name}"),
5807 AlterTextSearchOperation::OwnerTo(owner) => write!(f, "OWNER TO {owner}"),
5808 AlterTextSearchOperation::SetSchema { schema_name } => {
5809 write!(f, "SET SCHEMA {schema_name}")
5810 }
5811 AlterTextSearchOperation::SetOptions { options } => {
5812 write!(f, "({})", display_comma_separated(options))
5813 }
5814 }
5815 }
5816}
5817
5818#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5822#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5823#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5824pub struct AlterTextSearch {
5825 pub object_type: TextSearchObjectType,
5827 pub name: ObjectName,
5829 pub operation: AlterTextSearchOperation,
5831}
5832
5833impl fmt::Display for AlterTextSearch {
5834 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5835 write!(
5836 f,
5837 "ALTER TEXT SEARCH {} {} {}",
5838 self.object_type, self.name, self.operation
5839 )
5840 }
5841}
5842
5843impl Spanned for AlterTextSearch {
5844 fn span(&self) -> Span {
5845 Span::empty()
5846 }
5847}
5848
5849#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5853#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5854#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5855pub struct CreatePolicy {
5856 pub name: Ident,
5858 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5860 pub table_name: ObjectName,
5861 pub policy_type: Option<CreatePolicyType>,
5863 pub command: Option<CreatePolicyCommand>,
5865 pub to: Option<Vec<Owner>>,
5867 pub using: Option<Expr>,
5869 pub with_check: Option<Expr>,
5871}
5872
5873impl fmt::Display for CreatePolicy {
5874 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5875 write!(
5876 f,
5877 "CREATE POLICY {name} ON {table_name}",
5878 name = self.name,
5879 table_name = self.table_name,
5880 )?;
5881 if let Some(ref policy_type) = self.policy_type {
5882 write!(f, " AS {policy_type}")?;
5883 }
5884 if let Some(ref command) = self.command {
5885 write!(f, " FOR {command}")?;
5886 }
5887 if let Some(ref to) = self.to {
5888 write!(f, " TO {}", display_comma_separated(to))?;
5889 }
5890 if let Some(ref using) = self.using {
5891 write!(f, " USING ({using})")?;
5892 }
5893 if let Some(ref with_check) = self.with_check {
5894 write!(f, " WITH CHECK ({with_check})")?;
5895 }
5896 Ok(())
5897 }
5898}
5899
5900#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5906#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5907#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5908pub enum CreatePolicyType {
5909 Permissive,
5911 Restrictive,
5913}
5914
5915impl fmt::Display for CreatePolicyType {
5916 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5917 match self {
5918 CreatePolicyType::Permissive => write!(f, "PERMISSIVE"),
5919 CreatePolicyType::Restrictive => write!(f, "RESTRICTIVE"),
5920 }
5921 }
5922}
5923
5924#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
5930#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5931#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5932pub enum CreatePolicyCommand {
5933 All,
5935 Select,
5937 Insert,
5939 Update,
5941 Delete,
5943}
5944
5945impl fmt::Display for CreatePolicyCommand {
5946 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5947 match self {
5948 CreatePolicyCommand::All => write!(f, "ALL"),
5949 CreatePolicyCommand::Select => write!(f, "SELECT"),
5950 CreatePolicyCommand::Insert => write!(f, "INSERT"),
5951 CreatePolicyCommand::Update => write!(f, "UPDATE"),
5952 CreatePolicyCommand::Delete => write!(f, "DELETE"),
5953 }
5954 }
5955}
5956
5957#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5961#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5962#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5963pub struct DropPolicy {
5964 pub if_exists: bool,
5966 pub name: Ident,
5968 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
5970 pub table_name: ObjectName,
5971 pub drop_behavior: Option<DropBehavior>,
5973}
5974
5975impl fmt::Display for DropPolicy {
5976 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5977 write!(
5978 f,
5979 "DROP POLICY {if_exists}{name} ON {table_name}",
5980 if_exists = if self.if_exists { "IF EXISTS " } else { "" },
5981 name = self.name,
5982 table_name = self.table_name
5983 )?;
5984 if let Some(ref behavior) = self.drop_behavior {
5985 write!(f, " {behavior}")?;
5986 }
5987 Ok(())
5988 }
5989}
5990
5991impl From<CreatePolicy> for crate::ast::Statement {
5992 fn from(v: CreatePolicy) -> Self {
5993 crate::ast::Statement::CreatePolicy(v)
5994 }
5995}
5996
5997impl From<DropPolicy> for crate::ast::Statement {
5998 fn from(v: DropPolicy) -> Self {
5999 crate::ast::Statement::DropPolicy(v)
6000 }
6001}
6002
6003#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6010#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6011#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6012pub struct AlterPolicy {
6013 pub name: Ident,
6015 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6017 pub table_name: ObjectName,
6018 pub operation: AlterPolicyOperation,
6020}
6021
6022impl fmt::Display for AlterPolicy {
6023 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6024 write!(
6025 f,
6026 "ALTER POLICY {name} ON {table_name}{operation}",
6027 name = self.name,
6028 table_name = self.table_name,
6029 operation = self.operation
6030 )
6031 }
6032}
6033
6034impl From<AlterPolicy> for crate::ast::Statement {
6035 fn from(v: AlterPolicy) -> Self {
6036 crate::ast::Statement::AlterPolicy(v)
6037 }
6038}