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, RowAccessPolicy, SequenceOptions,
51 Spanned, SqlOption, StorageSerializationPolicy, TableVersion, Tag, TriggerEvent,
52 TriggerExecBody, TriggerObject, TriggerPeriod, TriggerReferencing, Value, ValueWithSpan,
53 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,
65 pub operator_class: Option<Ident>,
66}
67
68impl From<Ident> for IndexColumn {
69 fn from(c: Ident) -> Self {
70 Self {
71 column: OrderByExpr::from(c),
72 operator_class: None,
73 }
74 }
75}
76
77impl<'a> From<&'a str> for IndexColumn {
78 fn from(c: &'a str) -> Self {
79 let ident = Ident::new(c);
80 ident.into()
81 }
82}
83
84impl fmt::Display for IndexColumn {
85 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
86 write!(f, "{}", self.column)?;
87 if let Some(operator_class) = &self.operator_class {
88 write!(f, " {operator_class}")?;
89 }
90 Ok(())
91 }
92}
93
94#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
97#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
98#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
99pub enum ReplicaIdentity {
100 None,
101 Full,
102 Default,
103 Index(Ident),
104}
105
106impl fmt::Display for ReplicaIdentity {
107 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
108 match self {
109 ReplicaIdentity::None => f.write_str("NONE"),
110 ReplicaIdentity::Full => f.write_str("FULL"),
111 ReplicaIdentity::Default => f.write_str("DEFAULT"),
112 ReplicaIdentity::Index(idx) => write!(f, "USING INDEX {idx}"),
113 }
114 }
115}
116
117#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
119#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
120#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
121pub enum AlterTableOperation {
122 AddConstraint {
124 constraint: TableConstraint,
125 not_valid: bool,
126 },
127 AddColumn {
129 column_keyword: bool,
131 if_not_exists: bool,
133 column_def: ColumnDef,
135 column_position: Option<MySQLColumnPosition>,
137 },
138 AddProjection {
143 if_not_exists: bool,
144 name: Ident,
145 select: ProjectionSelect,
146 },
147 DropProjection {
152 if_exists: bool,
153 name: Ident,
154 },
155 MaterializeProjection {
160 if_exists: bool,
161 name: Ident,
162 partition: Option<Ident>,
163 },
164 ClearProjection {
169 if_exists: bool,
170 name: Ident,
171 partition: Option<Ident>,
172 },
173 DisableRowLevelSecurity,
177 DisableRule {
181 name: Ident,
182 },
183 DisableTrigger {
187 name: Ident,
188 },
189 DropConstraint {
191 if_exists: bool,
192 name: Ident,
193 drop_behavior: Option<DropBehavior>,
194 },
195 DropColumn {
197 has_column_keyword: bool,
198 column_names: Vec<Ident>,
199 if_exists: bool,
200 drop_behavior: Option<DropBehavior>,
201 },
202 AttachPartition {
206 partition: Partition,
209 },
210 DetachPartition {
214 partition: Partition,
216 },
217 FreezePartition {
221 partition: Partition,
222 with_name: Option<Ident>,
223 },
224 UnfreezePartition {
228 partition: Partition,
229 with_name: Option<Ident>,
230 },
231 DropPrimaryKey {
236 drop_behavior: Option<DropBehavior>,
237 },
238 DropForeignKey {
243 name: Ident,
244 drop_behavior: Option<DropBehavior>,
245 },
246 DropIndex {
250 name: Ident,
251 },
252 EnableAlwaysRule {
256 name: Ident,
257 },
258 EnableAlwaysTrigger {
262 name: Ident,
263 },
264 EnableReplicaRule {
268 name: Ident,
269 },
270 EnableReplicaTrigger {
274 name: Ident,
275 },
276 EnableRowLevelSecurity,
280 EnableRule {
284 name: Ident,
285 },
286 EnableTrigger {
290 name: Ident,
291 },
292 RenamePartitions {
294 old_partitions: Vec<Expr>,
295 new_partitions: Vec<Expr>,
296 },
297 ReplicaIdentity {
302 identity: ReplicaIdentity,
303 },
304 AddPartitions {
306 if_not_exists: bool,
307 new_partitions: Vec<Partition>,
308 },
309 DropPartitions {
310 partitions: Vec<Expr>,
311 if_exists: bool,
312 },
313 RenameColumn {
315 old_column_name: Ident,
316 new_column_name: Ident,
317 },
318 RenameTable {
320 table_name: RenameTableNameKind,
321 },
322 ChangeColumn {
324 old_name: Ident,
325 new_name: Ident,
326 data_type: DataType,
327 options: Vec<ColumnOption>,
328 column_position: Option<MySQLColumnPosition>,
330 },
331 ModifyColumn {
333 col_name: Ident,
334 data_type: DataType,
335 options: Vec<ColumnOption>,
336 column_position: Option<MySQLColumnPosition>,
338 },
339 RenameConstraint {
343 old_name: Ident,
344 new_name: Ident,
345 },
346 AlterColumn {
348 column_name: Ident,
349 op: AlterColumnOperation,
350 },
351 SwapWith {
355 table_name: ObjectName,
356 },
357 SetTblProperties {
359 table_properties: Vec<SqlOption>,
360 },
361 OwnerTo {
365 new_owner: Owner,
366 },
367 ClusterBy {
370 exprs: Vec<Expr>,
371 },
372 DropClusteringKey,
373 SuspendRecluster,
374 ResumeRecluster,
375 Refresh,
379 Suspend,
383 Resume,
387 Algorithm {
393 equals: bool,
394 algorithm: AlterTableAlgorithm,
395 },
396
397 Lock {
403 equals: bool,
404 lock: AlterTableLock,
405 },
406 AutoIncrement {
412 equals: bool,
413 value: ValueWithSpan,
414 },
415 ValidateConstraint {
417 name: Ident,
418 },
419 SetOptionsParens {
427 options: Vec<SqlOption>,
428 },
429}
430
431#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
435#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
436#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
437pub enum AlterPolicyOperation {
438 Rename {
439 new_name: Ident,
440 },
441 Apply {
442 to: Option<Vec<Owner>>,
443 using: Option<Expr>,
444 with_check: Option<Expr>,
445 },
446}
447
448impl fmt::Display for AlterPolicyOperation {
449 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
450 match self {
451 AlterPolicyOperation::Rename { new_name } => {
452 write!(f, " RENAME TO {new_name}")
453 }
454 AlterPolicyOperation::Apply {
455 to,
456 using,
457 with_check,
458 } => {
459 if let Some(to) = to {
460 write!(f, " TO {}", display_comma_separated(to))?;
461 }
462 if let Some(using) = using {
463 write!(f, " USING ({using})")?;
464 }
465 if let Some(with_check) = with_check {
466 write!(f, " WITH CHECK ({with_check})")?;
467 }
468 Ok(())
469 }
470 }
471 }
472}
473
474#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
478#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
479#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
480pub enum AlterTableAlgorithm {
481 Default,
482 Instant,
483 Inplace,
484 Copy,
485}
486
487impl fmt::Display for AlterTableAlgorithm {
488 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
489 f.write_str(match self {
490 Self::Default => "DEFAULT",
491 Self::Instant => "INSTANT",
492 Self::Inplace => "INPLACE",
493 Self::Copy => "COPY",
494 })
495 }
496}
497
498#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
502#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
503#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
504pub enum AlterTableLock {
505 Default,
506 None,
507 Shared,
508 Exclusive,
509}
510
511impl fmt::Display for AlterTableLock {
512 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
513 f.write_str(match self {
514 Self::Default => "DEFAULT",
515 Self::None => "NONE",
516 Self::Shared => "SHARED",
517 Self::Exclusive => "EXCLUSIVE",
518 })
519 }
520}
521
522#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
523#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
524#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
525pub enum Owner {
526 Ident(Ident),
527 CurrentRole,
528 CurrentUser,
529 SessionUser,
530}
531
532impl fmt::Display for Owner {
533 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
534 match self {
535 Owner::Ident(ident) => write!(f, "{ident}"),
536 Owner::CurrentRole => write!(f, "CURRENT_ROLE"),
537 Owner::CurrentUser => write!(f, "CURRENT_USER"),
538 Owner::SessionUser => write!(f, "SESSION_USER"),
539 }
540 }
541}
542
543#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
544#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
545#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
546pub enum AlterConnectorOwner {
547 User(Ident),
548 Role(Ident),
549}
550
551impl fmt::Display for AlterConnectorOwner {
552 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
553 match self {
554 AlterConnectorOwner::User(ident) => write!(f, "USER {ident}"),
555 AlterConnectorOwner::Role(ident) => write!(f, "ROLE {ident}"),
556 }
557 }
558}
559
560#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
561#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
562#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
563pub enum AlterIndexOperation {
564 RenameIndex { index_name: ObjectName },
565}
566
567impl fmt::Display for AlterTableOperation {
568 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
569 match self {
570 AlterTableOperation::AddPartitions {
571 if_not_exists,
572 new_partitions,
573 } => write!(
574 f,
575 "ADD{ine} {}",
576 display_separated(new_partitions, " "),
577 ine = if *if_not_exists { " IF NOT EXISTS" } else { "" }
578 ),
579 AlterTableOperation::AddConstraint {
580 not_valid,
581 constraint,
582 } => {
583 write!(f, "ADD {constraint}")?;
584 if *not_valid {
585 write!(f, " NOT VALID")?;
586 }
587 Ok(())
588 }
589 AlterTableOperation::AddColumn {
590 column_keyword,
591 if_not_exists,
592 column_def,
593 column_position,
594 } => {
595 write!(f, "ADD")?;
596 if *column_keyword {
597 write!(f, " COLUMN")?;
598 }
599 if *if_not_exists {
600 write!(f, " IF NOT EXISTS")?;
601 }
602 write!(f, " {column_def}")?;
603
604 if let Some(position) = column_position {
605 write!(f, " {position}")?;
606 }
607
608 Ok(())
609 }
610 AlterTableOperation::AddProjection {
611 if_not_exists,
612 name,
613 select: query,
614 } => {
615 write!(f, "ADD PROJECTION")?;
616 if *if_not_exists {
617 write!(f, " IF NOT EXISTS")?;
618 }
619 write!(f, " {name} ({query})")
620 }
621 AlterTableOperation::Algorithm { equals, algorithm } => {
622 write!(
623 f,
624 "ALGORITHM {}{}",
625 if *equals { "= " } else { "" },
626 algorithm
627 )
628 }
629 AlterTableOperation::DropProjection { if_exists, name } => {
630 write!(f, "DROP PROJECTION")?;
631 if *if_exists {
632 write!(f, " IF EXISTS")?;
633 }
634 write!(f, " {name}")
635 }
636 AlterTableOperation::MaterializeProjection {
637 if_exists,
638 name,
639 partition,
640 } => {
641 write!(f, "MATERIALIZE PROJECTION")?;
642 if *if_exists {
643 write!(f, " IF EXISTS")?;
644 }
645 write!(f, " {name}")?;
646 if let Some(partition) = partition {
647 write!(f, " IN PARTITION {partition}")?;
648 }
649 Ok(())
650 }
651 AlterTableOperation::ClearProjection {
652 if_exists,
653 name,
654 partition,
655 } => {
656 write!(f, "CLEAR PROJECTION")?;
657 if *if_exists {
658 write!(f, " IF EXISTS")?;
659 }
660 write!(f, " {name}")?;
661 if let Some(partition) = partition {
662 write!(f, " IN PARTITION {partition}")?;
663 }
664 Ok(())
665 }
666 AlterTableOperation::AlterColumn { column_name, op } => {
667 write!(f, "ALTER COLUMN {column_name} {op}")
668 }
669 AlterTableOperation::DisableRowLevelSecurity => {
670 write!(f, "DISABLE ROW LEVEL SECURITY")
671 }
672 AlterTableOperation::DisableRule { name } => {
673 write!(f, "DISABLE RULE {name}")
674 }
675 AlterTableOperation::DisableTrigger { name } => {
676 write!(f, "DISABLE TRIGGER {name}")
677 }
678 AlterTableOperation::DropPartitions {
679 partitions,
680 if_exists,
681 } => write!(
682 f,
683 "DROP{ie} PARTITION ({})",
684 display_comma_separated(partitions),
685 ie = if *if_exists { " IF EXISTS" } else { "" }
686 ),
687 AlterTableOperation::DropConstraint {
688 if_exists,
689 name,
690 drop_behavior,
691 } => {
692 write!(
693 f,
694 "DROP CONSTRAINT {}{}",
695 if *if_exists { "IF EXISTS " } else { "" },
696 name
697 )?;
698 if let Some(drop_behavior) = drop_behavior {
699 write!(f, " {drop_behavior}")?;
700 }
701 Ok(())
702 }
703 AlterTableOperation::DropPrimaryKey { drop_behavior } => {
704 write!(f, "DROP PRIMARY KEY")?;
705 if let Some(drop_behavior) = drop_behavior {
706 write!(f, " {drop_behavior}")?;
707 }
708 Ok(())
709 }
710 AlterTableOperation::DropForeignKey {
711 name,
712 drop_behavior,
713 } => {
714 write!(f, "DROP FOREIGN KEY {name}")?;
715 if let Some(drop_behavior) = drop_behavior {
716 write!(f, " {drop_behavior}")?;
717 }
718 Ok(())
719 }
720 AlterTableOperation::DropIndex { name } => write!(f, "DROP INDEX {name}"),
721 AlterTableOperation::DropColumn {
722 has_column_keyword,
723 column_names: column_name,
724 if_exists,
725 drop_behavior,
726 } => {
727 write!(
728 f,
729 "DROP {}{}{}",
730 if *has_column_keyword { "COLUMN " } else { "" },
731 if *if_exists { "IF EXISTS " } else { "" },
732 display_comma_separated(column_name),
733 )?;
734 if let Some(drop_behavior) = drop_behavior {
735 write!(f, " {drop_behavior}")?;
736 }
737 Ok(())
738 }
739 AlterTableOperation::AttachPartition { partition } => {
740 write!(f, "ATTACH {partition}")
741 }
742 AlterTableOperation::DetachPartition { partition } => {
743 write!(f, "DETACH {partition}")
744 }
745 AlterTableOperation::EnableAlwaysRule { name } => {
746 write!(f, "ENABLE ALWAYS RULE {name}")
747 }
748 AlterTableOperation::EnableAlwaysTrigger { name } => {
749 write!(f, "ENABLE ALWAYS TRIGGER {name}")
750 }
751 AlterTableOperation::EnableReplicaRule { name } => {
752 write!(f, "ENABLE REPLICA RULE {name}")
753 }
754 AlterTableOperation::EnableReplicaTrigger { name } => {
755 write!(f, "ENABLE REPLICA TRIGGER {name}")
756 }
757 AlterTableOperation::EnableRowLevelSecurity => {
758 write!(f, "ENABLE ROW LEVEL SECURITY")
759 }
760 AlterTableOperation::EnableRule { name } => {
761 write!(f, "ENABLE RULE {name}")
762 }
763 AlterTableOperation::EnableTrigger { name } => {
764 write!(f, "ENABLE TRIGGER {name}")
765 }
766 AlterTableOperation::RenamePartitions {
767 old_partitions,
768 new_partitions,
769 } => write!(
770 f,
771 "PARTITION ({}) RENAME TO PARTITION ({})",
772 display_comma_separated(old_partitions),
773 display_comma_separated(new_partitions)
774 ),
775 AlterTableOperation::RenameColumn {
776 old_column_name,
777 new_column_name,
778 } => write!(f, "RENAME COLUMN {old_column_name} TO {new_column_name}"),
779 AlterTableOperation::RenameTable { table_name } => {
780 write!(f, "RENAME {table_name}")
781 }
782 AlterTableOperation::ChangeColumn {
783 old_name,
784 new_name,
785 data_type,
786 options,
787 column_position,
788 } => {
789 write!(f, "CHANGE COLUMN {old_name} {new_name} {data_type}")?;
790 if !options.is_empty() {
791 write!(f, " {}", display_separated(options, " "))?;
792 }
793 if let Some(position) = column_position {
794 write!(f, " {position}")?;
795 }
796
797 Ok(())
798 }
799 AlterTableOperation::ModifyColumn {
800 col_name,
801 data_type,
802 options,
803 column_position,
804 } => {
805 write!(f, "MODIFY COLUMN {col_name} {data_type}")?;
806 if !options.is_empty() {
807 write!(f, " {}", display_separated(options, " "))?;
808 }
809 if let Some(position) = column_position {
810 write!(f, " {position}")?;
811 }
812
813 Ok(())
814 }
815 AlterTableOperation::RenameConstraint { old_name, new_name } => {
816 write!(f, "RENAME CONSTRAINT {old_name} TO {new_name}")
817 }
818 AlterTableOperation::SwapWith { table_name } => {
819 write!(f, "SWAP WITH {table_name}")
820 }
821 AlterTableOperation::OwnerTo { new_owner } => {
822 write!(f, "OWNER TO {new_owner}")
823 }
824 AlterTableOperation::SetTblProperties { table_properties } => {
825 write!(
826 f,
827 "SET TBLPROPERTIES({})",
828 display_comma_separated(table_properties)
829 )
830 }
831 AlterTableOperation::FreezePartition {
832 partition,
833 with_name,
834 } => {
835 write!(f, "FREEZE {partition}")?;
836 if let Some(name) = with_name {
837 write!(f, " WITH NAME {name}")?;
838 }
839 Ok(())
840 }
841 AlterTableOperation::UnfreezePartition {
842 partition,
843 with_name,
844 } => {
845 write!(f, "UNFREEZE {partition}")?;
846 if let Some(name) = with_name {
847 write!(f, " WITH NAME {name}")?;
848 }
849 Ok(())
850 }
851 AlterTableOperation::ClusterBy { exprs } => {
852 write!(f, "CLUSTER BY ({})", display_comma_separated(exprs))?;
853 Ok(())
854 }
855 AlterTableOperation::DropClusteringKey => {
856 write!(f, "DROP CLUSTERING KEY")?;
857 Ok(())
858 }
859 AlterTableOperation::SuspendRecluster => {
860 write!(f, "SUSPEND RECLUSTER")?;
861 Ok(())
862 }
863 AlterTableOperation::ResumeRecluster => {
864 write!(f, "RESUME RECLUSTER")?;
865 Ok(())
866 }
867 AlterTableOperation::Refresh => {
868 write!(f, "REFRESH")
869 }
870 AlterTableOperation::Suspend => {
871 write!(f, "SUSPEND")
872 }
873 AlterTableOperation::Resume => {
874 write!(f, "RESUME")
875 }
876 AlterTableOperation::AutoIncrement { equals, value } => {
877 write!(
878 f,
879 "AUTO_INCREMENT {}{}",
880 if *equals { "= " } else { "" },
881 value
882 )
883 }
884 AlterTableOperation::Lock { equals, lock } => {
885 write!(f, "LOCK {}{}", if *equals { "= " } else { "" }, lock)
886 }
887 AlterTableOperation::ReplicaIdentity { identity } => {
888 write!(f, "REPLICA IDENTITY {identity}")
889 }
890 AlterTableOperation::ValidateConstraint { name } => {
891 write!(f, "VALIDATE CONSTRAINT {name}")
892 }
893 AlterTableOperation::SetOptionsParens { options } => {
894 write!(f, "SET ({})", display_comma_separated(options))
895 }
896 }
897 }
898}
899
900impl fmt::Display for AlterIndexOperation {
901 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
902 match self {
903 AlterIndexOperation::RenameIndex { index_name } => {
904 write!(f, "RENAME TO {index_name}")
905 }
906 }
907 }
908}
909
910#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
912#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
913#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
914pub struct AlterType {
915 pub name: ObjectName,
916 pub operation: AlterTypeOperation,
917}
918
919#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
921#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
922#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
923pub enum AlterTypeOperation {
924 Rename(AlterTypeRename),
925 AddValue(AlterTypeAddValue),
926 RenameValue(AlterTypeRenameValue),
927}
928
929#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
931#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
932#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
933pub struct AlterTypeRename {
934 pub new_name: Ident,
935}
936
937#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
939#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
940#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
941pub struct AlterTypeAddValue {
942 pub if_not_exists: bool,
943 pub value: Ident,
944 pub position: Option<AlterTypeAddValuePosition>,
945}
946
947#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
949#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
950#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
951pub enum AlterTypeAddValuePosition {
952 Before(Ident),
953 After(Ident),
954}
955
956#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
958#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
959#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
960pub struct AlterTypeRenameValue {
961 pub from: Ident,
962 pub to: Ident,
963}
964
965impl fmt::Display for AlterTypeOperation {
966 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
967 match self {
968 Self::Rename(AlterTypeRename { new_name }) => {
969 write!(f, "RENAME TO {new_name}")
970 }
971 Self::AddValue(AlterTypeAddValue {
972 if_not_exists,
973 value,
974 position,
975 }) => {
976 write!(f, "ADD VALUE")?;
977 if *if_not_exists {
978 write!(f, " IF NOT EXISTS")?;
979 }
980 write!(f, " {value}")?;
981 match position {
982 Some(AlterTypeAddValuePosition::Before(neighbor_value)) => {
983 write!(f, " BEFORE {neighbor_value}")?;
984 }
985 Some(AlterTypeAddValuePosition::After(neighbor_value)) => {
986 write!(f, " AFTER {neighbor_value}")?;
987 }
988 None => {}
989 };
990 Ok(())
991 }
992 Self::RenameValue(AlterTypeRenameValue { from, to }) => {
993 write!(f, "RENAME VALUE {from} TO {to}")
994 }
995 }
996 }
997}
998
999#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1002#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1003#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1004pub struct AlterOperator {
1005 pub name: ObjectName,
1007 pub left_type: Option<DataType>,
1009 pub right_type: DataType,
1011 pub operation: AlterOperatorOperation,
1013}
1014
1015#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1017#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1018#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1019pub enum AlterOperatorOperation {
1020 OwnerTo(Owner),
1022 SetSchema { schema_name: ObjectName },
1024 Set {
1026 options: Vec<OperatorOption>,
1028 },
1029}
1030
1031#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1033#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1034#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1035pub enum OperatorOption {
1036 Restrict(Option<ObjectName>),
1038 Join(Option<ObjectName>),
1040 Commutator(ObjectName),
1042 Negator(ObjectName),
1044 Hashes,
1046 Merges,
1048}
1049
1050impl fmt::Display for AlterOperator {
1051 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1052 write!(f, "ALTER OPERATOR {} (", self.name)?;
1053 if let Some(left_type) = &self.left_type {
1054 write!(f, "{}", left_type)?;
1055 } else {
1056 write!(f, "NONE")?;
1057 }
1058 write!(f, ", {}) {}", self.right_type, self.operation)
1059 }
1060}
1061
1062impl fmt::Display for AlterOperatorOperation {
1063 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1064 match self {
1065 Self::OwnerTo(owner) => write!(f, "OWNER TO {}", owner),
1066 Self::SetSchema { schema_name } => write!(f, "SET SCHEMA {}", schema_name),
1067 Self::Set { options } => {
1068 write!(f, "SET (")?;
1069 for (i, option) in options.iter().enumerate() {
1070 if i > 0 {
1071 write!(f, ", ")?;
1072 }
1073 write!(f, "{}", option)?;
1074 }
1075 write!(f, ")")
1076 }
1077 }
1078 }
1079}
1080
1081impl fmt::Display for OperatorOption {
1082 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1083 match self {
1084 Self::Restrict(Some(proc_name)) => write!(f, "RESTRICT = {}", proc_name),
1085 Self::Restrict(None) => write!(f, "RESTRICT = NONE"),
1086 Self::Join(Some(proc_name)) => write!(f, "JOIN = {}", proc_name),
1087 Self::Join(None) => write!(f, "JOIN = NONE"),
1088 Self::Commutator(op_name) => write!(f, "COMMUTATOR = {}", op_name),
1089 Self::Negator(op_name) => write!(f, "NEGATOR = {}", op_name),
1090 Self::Hashes => write!(f, "HASHES"),
1091 Self::Merges => write!(f, "MERGES"),
1092 }
1093 }
1094}
1095
1096#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1098#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1099#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1100pub enum AlterColumnOperation {
1101 SetNotNull,
1103 DropNotNull,
1105 SetDefault { value: Expr },
1107 DropDefault,
1109 SetDataType {
1111 data_type: DataType,
1112 using: Option<Expr>,
1114 had_set: bool,
1116 },
1117
1118 AddGenerated {
1122 generated_as: Option<GeneratedAs>,
1123 sequence_options: Option<Vec<SequenceOptions>>,
1124 },
1125}
1126
1127impl fmt::Display for AlterColumnOperation {
1128 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1129 match self {
1130 AlterColumnOperation::SetNotNull => write!(f, "SET NOT NULL",),
1131 AlterColumnOperation::DropNotNull => write!(f, "DROP NOT NULL",),
1132 AlterColumnOperation::SetDefault { value } => {
1133 write!(f, "SET DEFAULT {value}")
1134 }
1135 AlterColumnOperation::DropDefault => {
1136 write!(f, "DROP DEFAULT")
1137 }
1138 AlterColumnOperation::SetDataType {
1139 data_type,
1140 using,
1141 had_set,
1142 } => {
1143 if *had_set {
1144 write!(f, "SET DATA ")?;
1145 }
1146 write!(f, "TYPE {data_type}")?;
1147 if let Some(expr) = using {
1148 write!(f, " USING {expr}")?;
1149 }
1150 Ok(())
1151 }
1152 AlterColumnOperation::AddGenerated {
1153 generated_as,
1154 sequence_options,
1155 } => {
1156 let generated_as = match generated_as {
1157 Some(GeneratedAs::Always) => " ALWAYS",
1158 Some(GeneratedAs::ByDefault) => " BY DEFAULT",
1159 _ => "",
1160 };
1161
1162 write!(f, "ADD GENERATED{generated_as} AS IDENTITY",)?;
1163 if let Some(options) = sequence_options {
1164 write!(f, " (")?;
1165
1166 for sequence_option in options {
1167 write!(f, "{sequence_option}")?;
1168 }
1169
1170 write!(f, " )")?;
1171 }
1172 Ok(())
1173 }
1174 }
1175 }
1176}
1177
1178#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1186#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1187#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1188pub enum KeyOrIndexDisplay {
1189 None,
1191 Key,
1193 Index,
1195}
1196
1197impl KeyOrIndexDisplay {
1198 pub fn is_none(self) -> bool {
1199 matches!(self, Self::None)
1200 }
1201}
1202
1203impl fmt::Display for KeyOrIndexDisplay {
1204 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1205 let left_space = matches!(f.align(), Some(fmt::Alignment::Right));
1206
1207 if left_space && !self.is_none() {
1208 f.write_char(' ')?
1209 }
1210
1211 match self {
1212 KeyOrIndexDisplay::None => {
1213 write!(f, "")
1214 }
1215 KeyOrIndexDisplay::Key => {
1216 write!(f, "KEY")
1217 }
1218 KeyOrIndexDisplay::Index => {
1219 write!(f, "INDEX")
1220 }
1221 }
1222 }
1223}
1224
1225#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1234#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1235#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1236pub enum IndexType {
1237 BTree,
1238 Hash,
1239 GIN,
1240 GiST,
1241 SPGiST,
1242 BRIN,
1243 Bloom,
1244 Custom(Ident),
1247}
1248
1249impl fmt::Display for IndexType {
1250 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1251 match self {
1252 Self::BTree => write!(f, "BTREE"),
1253 Self::Hash => write!(f, "HASH"),
1254 Self::GIN => write!(f, "GIN"),
1255 Self::GiST => write!(f, "GIST"),
1256 Self::SPGiST => write!(f, "SPGIST"),
1257 Self::BRIN => write!(f, "BRIN"),
1258 Self::Bloom => write!(f, "BLOOM"),
1259 Self::Custom(name) => write!(f, "{name}"),
1260 }
1261 }
1262}
1263
1264#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1270#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1271#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1272pub enum IndexOption {
1273 Using(IndexType),
1277 Comment(String),
1279}
1280
1281impl fmt::Display for IndexOption {
1282 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1283 match self {
1284 Self::Using(index_type) => write!(f, "USING {index_type}"),
1285 Self::Comment(s) => write!(f, "COMMENT '{s}'"),
1286 }
1287 }
1288}
1289
1290#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1294#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1295#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1296pub enum NullsDistinctOption {
1297 None,
1299 Distinct,
1301 NotDistinct,
1303}
1304
1305impl fmt::Display for NullsDistinctOption {
1306 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1307 match self {
1308 Self::None => Ok(()),
1309 Self::Distinct => write!(f, " NULLS DISTINCT"),
1310 Self::NotDistinct => write!(f, " NULLS NOT DISTINCT"),
1311 }
1312 }
1313}
1314
1315#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1316#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1317#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1318pub struct ProcedureParam {
1319 pub name: Ident,
1320 pub data_type: DataType,
1321 pub mode: Option<ArgMode>,
1322 pub default: Option<Expr>,
1323}
1324
1325impl fmt::Display for ProcedureParam {
1326 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1327 if let Some(mode) = &self.mode {
1328 if let Some(default) = &self.default {
1329 write!(f, "{mode} {} {} = {}", self.name, self.data_type, default)
1330 } else {
1331 write!(f, "{mode} {} {}", self.name, self.data_type)
1332 }
1333 } else if let Some(default) = &self.default {
1334 write!(f, "{} {} = {}", self.name, self.data_type, default)
1335 } else {
1336 write!(f, "{} {}", self.name, self.data_type)
1337 }
1338 }
1339}
1340
1341#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1343#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1344#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1345pub struct ColumnDef {
1346 pub name: Ident,
1347 pub data_type: DataType,
1348 pub options: Vec<ColumnOptionDef>,
1349}
1350
1351impl fmt::Display for ColumnDef {
1352 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1353 if self.data_type == DataType::Unspecified {
1354 write!(f, "{}", self.name)?;
1355 } else {
1356 write!(f, "{} {}", self.name, self.data_type)?;
1357 }
1358 for option in &self.options {
1359 write!(f, " {option}")?;
1360 }
1361 Ok(())
1362 }
1363}
1364
1365#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1382#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1383#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1384pub struct ViewColumnDef {
1385 pub name: Ident,
1386 pub data_type: Option<DataType>,
1387 pub options: Option<ColumnOptions>,
1388}
1389
1390#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1391#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1392#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1393pub enum ColumnOptions {
1394 CommaSeparated(Vec<ColumnOption>),
1395 SpaceSeparated(Vec<ColumnOption>),
1396}
1397
1398impl ColumnOptions {
1399 pub fn as_slice(&self) -> &[ColumnOption] {
1400 match self {
1401 ColumnOptions::CommaSeparated(options) => options.as_slice(),
1402 ColumnOptions::SpaceSeparated(options) => options.as_slice(),
1403 }
1404 }
1405}
1406
1407impl fmt::Display for ViewColumnDef {
1408 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1409 write!(f, "{}", self.name)?;
1410 if let Some(data_type) = self.data_type.as_ref() {
1411 write!(f, " {data_type}")?;
1412 }
1413 if let Some(options) = self.options.as_ref() {
1414 match options {
1415 ColumnOptions::CommaSeparated(column_options) => {
1416 write!(f, " {}", display_comma_separated(column_options.as_slice()))?;
1417 }
1418 ColumnOptions::SpaceSeparated(column_options) => {
1419 write!(f, " {}", display_separated(column_options.as_slice(), " "))?
1420 }
1421 }
1422 }
1423 Ok(())
1424 }
1425}
1426
1427#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1444#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1445#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1446pub struct ColumnOptionDef {
1447 pub name: Option<Ident>,
1448 pub option: ColumnOption,
1449}
1450
1451impl fmt::Display for ColumnOptionDef {
1452 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1453 write!(f, "{}{}", display_constraint_name(&self.name), self.option)
1454 }
1455}
1456
1457#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1465#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1466#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1467pub enum IdentityPropertyKind {
1468 Autoincrement(IdentityProperty),
1476 Identity(IdentityProperty),
1489}
1490
1491impl fmt::Display for IdentityPropertyKind {
1492 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1493 let (command, property) = match self {
1494 IdentityPropertyKind::Identity(property) => ("IDENTITY", property),
1495 IdentityPropertyKind::Autoincrement(property) => ("AUTOINCREMENT", property),
1496 };
1497 write!(f, "{command}")?;
1498 if let Some(parameters) = &property.parameters {
1499 write!(f, "{parameters}")?;
1500 }
1501 if let Some(order) = &property.order {
1502 write!(f, "{order}")?;
1503 }
1504 Ok(())
1505 }
1506}
1507
1508#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1509#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1510#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1511pub struct IdentityProperty {
1512 pub parameters: Option<IdentityPropertyFormatKind>,
1513 pub order: Option<IdentityPropertyOrder>,
1514}
1515
1516#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1531#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1532#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1533pub enum IdentityPropertyFormatKind {
1534 FunctionCall(IdentityParameters),
1542 StartAndIncrement(IdentityParameters),
1549}
1550
1551impl fmt::Display for IdentityPropertyFormatKind {
1552 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1553 match self {
1554 IdentityPropertyFormatKind::FunctionCall(parameters) => {
1555 write!(f, "({}, {})", parameters.seed, parameters.increment)
1556 }
1557 IdentityPropertyFormatKind::StartAndIncrement(parameters) => {
1558 write!(
1559 f,
1560 " START {} INCREMENT {}",
1561 parameters.seed, parameters.increment
1562 )
1563 }
1564 }
1565 }
1566}
1567#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1568#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1569#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1570pub struct IdentityParameters {
1571 pub seed: Expr,
1572 pub increment: Expr,
1573}
1574
1575#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1582#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1583#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1584pub enum IdentityPropertyOrder {
1585 Order,
1586 NoOrder,
1587}
1588
1589impl fmt::Display for IdentityPropertyOrder {
1590 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1591 match self {
1592 IdentityPropertyOrder::Order => write!(f, " ORDER"),
1593 IdentityPropertyOrder::NoOrder => write!(f, " NOORDER"),
1594 }
1595 }
1596}
1597
1598#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1606#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1607#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1608pub enum ColumnPolicy {
1609 MaskingPolicy(ColumnPolicyProperty),
1610 ProjectionPolicy(ColumnPolicyProperty),
1611}
1612
1613impl fmt::Display for ColumnPolicy {
1614 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1615 let (command, property) = match self {
1616 ColumnPolicy::MaskingPolicy(property) => ("MASKING POLICY", property),
1617 ColumnPolicy::ProjectionPolicy(property) => ("PROJECTION POLICY", property),
1618 };
1619 if property.with {
1620 write!(f, "WITH ")?;
1621 }
1622 write!(f, "{command} {}", property.policy_name)?;
1623 if let Some(using_columns) = &property.using_columns {
1624 write!(f, " USING ({})", display_comma_separated(using_columns))?;
1625 }
1626 Ok(())
1627 }
1628}
1629
1630#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1631#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1632#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1633pub struct ColumnPolicyProperty {
1634 pub with: bool,
1641 pub policy_name: ObjectName,
1642 pub using_columns: Option<Vec<Ident>>,
1643}
1644
1645#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1652#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1653#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1654pub struct TagsColumnOption {
1655 pub with: bool,
1662 pub tags: Vec<Tag>,
1663}
1664
1665impl fmt::Display for TagsColumnOption {
1666 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1667 if self.with {
1668 write!(f, "WITH ")?;
1669 }
1670 write!(f, "TAG ({})", display_comma_separated(&self.tags))?;
1671 Ok(())
1672 }
1673}
1674
1675#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1678#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1679#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1680pub enum ColumnOption {
1681 Null,
1683 NotNull,
1685 Default(Expr),
1687
1688 Materialized(Expr),
1693 Ephemeral(Option<Expr>),
1697 Alias(Expr),
1701
1702 PrimaryKey(PrimaryKeyConstraint),
1704 Unique(UniqueConstraint),
1706 ForeignKey(ForeignKeyConstraint),
1714 Check(CheckConstraint),
1716 DialectSpecific(Vec<Token>),
1720 CharacterSet(ObjectName),
1721 Collation(ObjectName),
1722 Comment(String),
1723 OnUpdate(Expr),
1724 Generated {
1727 generated_as: GeneratedAs,
1728 sequence_options: Option<Vec<SequenceOptions>>,
1729 generation_expr: Option<Expr>,
1730 generation_expr_mode: Option<GeneratedExpressionMode>,
1731 generated_keyword: bool,
1733 },
1734 Options(Vec<SqlOption>),
1742 Identity(IdentityPropertyKind),
1750 OnConflict(Keyword),
1753 Policy(ColumnPolicy),
1761 Tags(TagsColumnOption),
1768 Srid(Box<Expr>),
1775 Invisible,
1782}
1783
1784impl From<UniqueConstraint> for ColumnOption {
1785 fn from(c: UniqueConstraint) -> Self {
1786 ColumnOption::Unique(c)
1787 }
1788}
1789
1790impl From<PrimaryKeyConstraint> for ColumnOption {
1791 fn from(c: PrimaryKeyConstraint) -> Self {
1792 ColumnOption::PrimaryKey(c)
1793 }
1794}
1795
1796impl From<CheckConstraint> for ColumnOption {
1797 fn from(c: CheckConstraint) -> Self {
1798 ColumnOption::Check(c)
1799 }
1800}
1801impl From<ForeignKeyConstraint> for ColumnOption {
1802 fn from(fk: ForeignKeyConstraint) -> Self {
1803 ColumnOption::ForeignKey(fk)
1804 }
1805}
1806
1807impl fmt::Display for ColumnOption {
1808 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1809 use ColumnOption::*;
1810 match self {
1811 Null => write!(f, "NULL"),
1812 NotNull => write!(f, "NOT NULL"),
1813 Default(expr) => write!(f, "DEFAULT {expr}"),
1814 Materialized(expr) => write!(f, "MATERIALIZED {expr}"),
1815 Ephemeral(expr) => {
1816 if let Some(e) = expr {
1817 write!(f, "EPHEMERAL {e}")
1818 } else {
1819 write!(f, "EPHEMERAL")
1820 }
1821 }
1822 Alias(expr) => write!(f, "ALIAS {expr}"),
1823 PrimaryKey(constraint) => {
1824 write!(f, "PRIMARY KEY")?;
1825 if let Some(characteristics) = &constraint.characteristics {
1826 write!(f, " {characteristics}")?;
1827 }
1828 Ok(())
1829 }
1830 Unique(constraint) => {
1831 write!(f, "UNIQUE")?;
1832 if let Some(characteristics) = &constraint.characteristics {
1833 write!(f, " {characteristics}")?;
1834 }
1835 Ok(())
1836 }
1837 ForeignKey(constraint) => {
1838 write!(f, "REFERENCES {}", constraint.foreign_table)?;
1839 if !constraint.referred_columns.is_empty() {
1840 write!(
1841 f,
1842 " ({})",
1843 display_comma_separated(&constraint.referred_columns)
1844 )?;
1845 }
1846 if let Some(match_kind) = &constraint.match_kind {
1847 write!(f, " {match_kind}")?;
1848 }
1849 if let Some(action) = &constraint.on_delete {
1850 write!(f, " ON DELETE {action}")?;
1851 }
1852 if let Some(action) = &constraint.on_update {
1853 write!(f, " ON UPDATE {action}")?;
1854 }
1855 if let Some(characteristics) = &constraint.characteristics {
1856 write!(f, " {characteristics}")?;
1857 }
1858 Ok(())
1859 }
1860 Check(constraint) => write!(f, "{constraint}"),
1861 DialectSpecific(val) => write!(f, "{}", display_separated(val, " ")),
1862 CharacterSet(n) => write!(f, "CHARACTER SET {n}"),
1863 Collation(n) => write!(f, "COLLATE {n}"),
1864 Comment(v) => write!(f, "COMMENT '{}'", escape_single_quote_string(v)),
1865 OnUpdate(expr) => write!(f, "ON UPDATE {expr}"),
1866 Generated {
1867 generated_as,
1868 sequence_options,
1869 generation_expr,
1870 generation_expr_mode,
1871 generated_keyword,
1872 } => {
1873 if let Some(expr) = generation_expr {
1874 let modifier = match generation_expr_mode {
1875 None => "",
1876 Some(GeneratedExpressionMode::Virtual) => " VIRTUAL",
1877 Some(GeneratedExpressionMode::Stored) => " STORED",
1878 };
1879 if *generated_keyword {
1880 write!(f, "GENERATED ALWAYS AS ({expr}){modifier}")?;
1881 } else {
1882 write!(f, "AS ({expr}){modifier}")?;
1883 }
1884 Ok(())
1885 } else {
1886 let when = match generated_as {
1888 GeneratedAs::Always => "ALWAYS",
1889 GeneratedAs::ByDefault => "BY DEFAULT",
1890 GeneratedAs::ExpStored => "",
1892 };
1893 write!(f, "GENERATED {when} AS IDENTITY")?;
1894 if sequence_options.is_some() {
1895 let so = sequence_options.as_ref().unwrap();
1896 if !so.is_empty() {
1897 write!(f, " (")?;
1898 }
1899 for sequence_option in so {
1900 write!(f, "{sequence_option}")?;
1901 }
1902 if !so.is_empty() {
1903 write!(f, " )")?;
1904 }
1905 }
1906 Ok(())
1907 }
1908 }
1909 Options(options) => {
1910 write!(f, "OPTIONS({})", display_comma_separated(options))
1911 }
1912 Identity(parameters) => {
1913 write!(f, "{parameters}")
1914 }
1915 OnConflict(keyword) => {
1916 write!(f, "ON CONFLICT {keyword:?}")?;
1917 Ok(())
1918 }
1919 Policy(parameters) => {
1920 write!(f, "{parameters}")
1921 }
1922 Tags(tags) => {
1923 write!(f, "{tags}")
1924 }
1925 Srid(srid) => {
1926 write!(f, "SRID {srid}")
1927 }
1928 Invisible => {
1929 write!(f, "INVISIBLE")
1930 }
1931 }
1932 }
1933}
1934
1935#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1938#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1939#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1940pub enum GeneratedAs {
1941 Always,
1942 ByDefault,
1943 ExpStored,
1944}
1945
1946#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1949#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1950#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1951pub enum GeneratedExpressionMode {
1952 Virtual,
1953 Stored,
1954}
1955
1956#[must_use]
1957pub(crate) fn display_constraint_name(name: &'_ Option<Ident>) -> impl fmt::Display + '_ {
1958 struct ConstraintName<'a>(&'a Option<Ident>);
1959 impl fmt::Display for ConstraintName<'_> {
1960 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1961 if let Some(name) = self.0 {
1962 write!(f, "CONSTRAINT {name} ")?;
1963 }
1964 Ok(())
1965 }
1966 }
1967 ConstraintName(name)
1968}
1969
1970#[must_use]
1974pub(crate) fn display_option<'a, T: fmt::Display>(
1975 prefix: &'a str,
1976 postfix: &'a str,
1977 option: &'a Option<T>,
1978) -> impl fmt::Display + 'a {
1979 struct OptionDisplay<'a, T>(&'a str, &'a str, &'a Option<T>);
1980 impl<T: fmt::Display> fmt::Display for OptionDisplay<'_, T> {
1981 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1982 if let Some(inner) = self.2 {
1983 let (prefix, postfix) = (self.0, self.1);
1984 write!(f, "{prefix}{inner}{postfix}")?;
1985 }
1986 Ok(())
1987 }
1988 }
1989 OptionDisplay(prefix, postfix, option)
1990}
1991
1992#[must_use]
1996pub(crate) fn display_option_spaced<T: fmt::Display>(option: &Option<T>) -> impl fmt::Display + '_ {
1997 display_option(" ", "", option)
1998}
1999
2000#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Default, Eq, Ord, Hash)]
2004#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2005#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2006pub struct ConstraintCharacteristics {
2007 pub deferrable: Option<bool>,
2009 pub initially: Option<DeferrableInitial>,
2011 pub enforced: Option<bool>,
2013}
2014
2015#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2016#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2017#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2018pub enum DeferrableInitial {
2019 Immediate,
2021 Deferred,
2023}
2024
2025impl ConstraintCharacteristics {
2026 fn deferrable_text(&self) -> Option<&'static str> {
2027 self.deferrable.map(|deferrable| {
2028 if deferrable {
2029 "DEFERRABLE"
2030 } else {
2031 "NOT DEFERRABLE"
2032 }
2033 })
2034 }
2035
2036 fn initially_immediate_text(&self) -> Option<&'static str> {
2037 self.initially
2038 .map(|initially_immediate| match initially_immediate {
2039 DeferrableInitial::Immediate => "INITIALLY IMMEDIATE",
2040 DeferrableInitial::Deferred => "INITIALLY DEFERRED",
2041 })
2042 }
2043
2044 fn enforced_text(&self) -> Option<&'static str> {
2045 self.enforced.map(
2046 |enforced| {
2047 if enforced {
2048 "ENFORCED"
2049 } else {
2050 "NOT ENFORCED"
2051 }
2052 },
2053 )
2054 }
2055}
2056
2057impl fmt::Display for ConstraintCharacteristics {
2058 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2059 let deferrable = self.deferrable_text();
2060 let initially_immediate = self.initially_immediate_text();
2061 let enforced = self.enforced_text();
2062
2063 match (deferrable, initially_immediate, enforced) {
2064 (None, None, None) => Ok(()),
2065 (None, None, Some(enforced)) => write!(f, "{enforced}"),
2066 (None, Some(initial), None) => write!(f, "{initial}"),
2067 (None, Some(initial), Some(enforced)) => write!(f, "{initial} {enforced}"),
2068 (Some(deferrable), None, None) => write!(f, "{deferrable}"),
2069 (Some(deferrable), None, Some(enforced)) => write!(f, "{deferrable} {enforced}"),
2070 (Some(deferrable), Some(initial), None) => write!(f, "{deferrable} {initial}"),
2071 (Some(deferrable), Some(initial), Some(enforced)) => {
2072 write!(f, "{deferrable} {initial} {enforced}")
2073 }
2074 }
2075 }
2076}
2077
2078#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2083#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2084#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2085pub enum ReferentialAction {
2086 Restrict,
2087 Cascade,
2088 SetNull,
2089 NoAction,
2090 SetDefault,
2091}
2092
2093impl fmt::Display for ReferentialAction {
2094 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2095 f.write_str(match self {
2096 ReferentialAction::Restrict => "RESTRICT",
2097 ReferentialAction::Cascade => "CASCADE",
2098 ReferentialAction::SetNull => "SET NULL",
2099 ReferentialAction::NoAction => "NO ACTION",
2100 ReferentialAction::SetDefault => "SET DEFAULT",
2101 })
2102 }
2103}
2104
2105#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2109#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2110#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2111pub enum DropBehavior {
2112 Restrict,
2113 Cascade,
2114}
2115
2116impl fmt::Display for DropBehavior {
2117 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2118 f.write_str(match self {
2119 DropBehavior::Restrict => "RESTRICT",
2120 DropBehavior::Cascade => "CASCADE",
2121 })
2122 }
2123}
2124
2125#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2127#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2128#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2129pub enum UserDefinedTypeRepresentation {
2130 Composite {
2132 attributes: Vec<UserDefinedTypeCompositeAttributeDef>,
2133 },
2134 Enum { labels: Vec<Ident> },
2138 Range {
2142 options: Vec<UserDefinedTypeRangeOption>,
2143 },
2144 SqlDefinition {
2150 options: Vec<UserDefinedTypeSqlDefinitionOption>,
2151 },
2152}
2153
2154impl fmt::Display for UserDefinedTypeRepresentation {
2155 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2156 match self {
2157 Self::Composite { attributes } => {
2158 write!(f, "AS ({})", display_comma_separated(attributes))
2159 }
2160 Self::Enum { labels } => {
2161 write!(f, "AS ENUM ({})", display_comma_separated(labels))
2162 }
2163 Self::Range { options } => {
2164 write!(f, "AS RANGE ({})", display_comma_separated(options))
2165 }
2166 Self::SqlDefinition { options } => {
2167 write!(f, "({})", display_comma_separated(options))
2168 }
2169 }
2170 }
2171}
2172
2173#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2175#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2176#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2177pub struct UserDefinedTypeCompositeAttributeDef {
2178 pub name: Ident,
2179 pub data_type: DataType,
2180 pub collation: Option<ObjectName>,
2181}
2182
2183impl fmt::Display for UserDefinedTypeCompositeAttributeDef {
2184 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2185 write!(f, "{} {}", self.name, self.data_type)?;
2186 if let Some(collation) = &self.collation {
2187 write!(f, " COLLATE {collation}")?;
2188 }
2189 Ok(())
2190 }
2191}
2192
2193#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2216#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2217#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2218pub enum UserDefinedTypeInternalLength {
2219 Fixed(u64),
2221 Variable,
2223}
2224
2225impl fmt::Display for UserDefinedTypeInternalLength {
2226 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2227 match self {
2228 UserDefinedTypeInternalLength::Fixed(n) => write!(f, "{}", n),
2229 UserDefinedTypeInternalLength::Variable => write!(f, "VARIABLE"),
2230 }
2231 }
2232}
2233
2234#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2253#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2254#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2255pub enum Alignment {
2256 Char,
2258 Int2,
2260 Int4,
2262 Double,
2264}
2265
2266impl fmt::Display for Alignment {
2267 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2268 match self {
2269 Alignment::Char => write!(f, "char"),
2270 Alignment::Int2 => write!(f, "int2"),
2271 Alignment::Int4 => write!(f, "int4"),
2272 Alignment::Double => write!(f, "double"),
2273 }
2274 }
2275}
2276
2277#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2297#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2298#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2299pub enum UserDefinedTypeStorage {
2300 Plain,
2302 External,
2304 Extended,
2306 Main,
2308}
2309
2310impl fmt::Display for UserDefinedTypeStorage {
2311 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2312 match self {
2313 UserDefinedTypeStorage::Plain => write!(f, "plain"),
2314 UserDefinedTypeStorage::External => write!(f, "external"),
2315 UserDefinedTypeStorage::Extended => write!(f, "extended"),
2316 UserDefinedTypeStorage::Main => write!(f, "main"),
2317 }
2318 }
2319}
2320
2321#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2339#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2340#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2341pub enum UserDefinedTypeRangeOption {
2342 Subtype(DataType),
2344 SubtypeOpClass(ObjectName),
2346 Collation(ObjectName),
2348 Canonical(ObjectName),
2350 SubtypeDiff(ObjectName),
2352 MultirangeTypeName(ObjectName),
2354}
2355
2356impl fmt::Display for UserDefinedTypeRangeOption {
2357 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2358 match self {
2359 UserDefinedTypeRangeOption::Subtype(dt) => write!(f, "SUBTYPE = {}", dt),
2360 UserDefinedTypeRangeOption::SubtypeOpClass(name) => {
2361 write!(f, "SUBTYPE_OPCLASS = {}", name)
2362 }
2363 UserDefinedTypeRangeOption::Collation(name) => write!(f, "COLLATION = {}", name),
2364 UserDefinedTypeRangeOption::Canonical(name) => write!(f, "CANONICAL = {}", name),
2365 UserDefinedTypeRangeOption::SubtypeDiff(name) => write!(f, "SUBTYPE_DIFF = {}", name),
2366 UserDefinedTypeRangeOption::MultirangeTypeName(name) => {
2367 write!(f, "MULTIRANGE_TYPE_NAME = {}", name)
2368 }
2369 }
2370 }
2371}
2372
2373#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2394#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2395#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2396pub enum UserDefinedTypeSqlDefinitionOption {
2397 Input(ObjectName),
2399 Output(ObjectName),
2401 Receive(ObjectName),
2403 Send(ObjectName),
2405 TypmodIn(ObjectName),
2407 TypmodOut(ObjectName),
2409 Analyze(ObjectName),
2411 Subscript(ObjectName),
2413 InternalLength(UserDefinedTypeInternalLength),
2415 PassedByValue,
2417 Alignment(Alignment),
2419 Storage(UserDefinedTypeStorage),
2421 Like(ObjectName),
2423 Category(char),
2425 Preferred(bool),
2427 Default(Expr),
2429 Element(DataType),
2431 Delimiter(String),
2433 Collatable(bool),
2435}
2436
2437impl fmt::Display for UserDefinedTypeSqlDefinitionOption {
2438 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2439 match self {
2440 UserDefinedTypeSqlDefinitionOption::Input(name) => write!(f, "INPUT = {}", name),
2441 UserDefinedTypeSqlDefinitionOption::Output(name) => write!(f, "OUTPUT = {}", name),
2442 UserDefinedTypeSqlDefinitionOption::Receive(name) => write!(f, "RECEIVE = {}", name),
2443 UserDefinedTypeSqlDefinitionOption::Send(name) => write!(f, "SEND = {}", name),
2444 UserDefinedTypeSqlDefinitionOption::TypmodIn(name) => write!(f, "TYPMOD_IN = {}", name),
2445 UserDefinedTypeSqlDefinitionOption::TypmodOut(name) => {
2446 write!(f, "TYPMOD_OUT = {}", name)
2447 }
2448 UserDefinedTypeSqlDefinitionOption::Analyze(name) => write!(f, "ANALYZE = {}", name),
2449 UserDefinedTypeSqlDefinitionOption::Subscript(name) => {
2450 write!(f, "SUBSCRIPT = {}", name)
2451 }
2452 UserDefinedTypeSqlDefinitionOption::InternalLength(len) => {
2453 write!(f, "INTERNALLENGTH = {}", len)
2454 }
2455 UserDefinedTypeSqlDefinitionOption::PassedByValue => write!(f, "PASSEDBYVALUE"),
2456 UserDefinedTypeSqlDefinitionOption::Alignment(align) => {
2457 write!(f, "ALIGNMENT = {}", align)
2458 }
2459 UserDefinedTypeSqlDefinitionOption::Storage(storage) => {
2460 write!(f, "STORAGE = {}", storage)
2461 }
2462 UserDefinedTypeSqlDefinitionOption::Like(name) => write!(f, "LIKE = {}", name),
2463 UserDefinedTypeSqlDefinitionOption::Category(c) => write!(f, "CATEGORY = '{}'", c),
2464 UserDefinedTypeSqlDefinitionOption::Preferred(b) => write!(f, "PREFERRED = {}", b),
2465 UserDefinedTypeSqlDefinitionOption::Default(expr) => write!(f, "DEFAULT = {}", expr),
2466 UserDefinedTypeSqlDefinitionOption::Element(dt) => write!(f, "ELEMENT = {}", dt),
2467 UserDefinedTypeSqlDefinitionOption::Delimiter(s) => {
2468 write!(f, "DELIMITER = '{}'", escape_single_quote_string(s))
2469 }
2470 UserDefinedTypeSqlDefinitionOption::Collatable(b) => write!(f, "COLLATABLE = {}", b),
2471 }
2472 }
2473}
2474
2475#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2479#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2480#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2481pub enum Partition {
2482 Identifier(Ident),
2483 Expr(Expr),
2484 Part(Expr),
2487 Partitions(Vec<Expr>),
2488}
2489
2490impl fmt::Display for Partition {
2491 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2492 match self {
2493 Partition::Identifier(id) => write!(f, "PARTITION ID {id}"),
2494 Partition::Expr(expr) => write!(f, "PARTITION {expr}"),
2495 Partition::Part(expr) => write!(f, "PART {expr}"),
2496 Partition::Partitions(partitions) => {
2497 write!(f, "PARTITION ({})", display_comma_separated(partitions))
2498 }
2499 }
2500 }
2501}
2502
2503#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2506#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2507#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2508pub enum Deduplicate {
2509 All,
2510 ByExpression(Expr),
2511}
2512
2513impl fmt::Display for Deduplicate {
2514 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2515 match self {
2516 Deduplicate::All => write!(f, "DEDUPLICATE"),
2517 Deduplicate::ByExpression(expr) => write!(f, "DEDUPLICATE BY {expr}"),
2518 }
2519 }
2520}
2521
2522#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2527#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2528#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2529pub struct ClusteredBy {
2530 pub columns: Vec<Ident>,
2531 pub sorted_by: Option<Vec<OrderByExpr>>,
2532 pub num_buckets: Value,
2533}
2534
2535impl fmt::Display for ClusteredBy {
2536 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2537 write!(
2538 f,
2539 "CLUSTERED BY ({})",
2540 display_comma_separated(&self.columns)
2541 )?;
2542 if let Some(ref sorted_by) = self.sorted_by {
2543 write!(f, " SORTED BY ({})", display_comma_separated(sorted_by))?;
2544 }
2545 write!(f, " INTO {} BUCKETS", self.num_buckets)
2546 }
2547}
2548
2549#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2551#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2552#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2553pub struct CreateIndex {
2554 pub name: Option<ObjectName>,
2556 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2557 pub table_name: ObjectName,
2558 pub using: Option<IndexType>,
2561 pub columns: Vec<IndexColumn>,
2562 pub unique: bool,
2563 pub concurrently: bool,
2564 pub if_not_exists: bool,
2565 pub include: Vec<Ident>,
2566 pub nulls_distinct: Option<bool>,
2567 pub with: Vec<Expr>,
2569 pub predicate: Option<Expr>,
2570 pub index_options: Vec<IndexOption>,
2571 pub alter_options: Vec<AlterTableOperation>,
2578}
2579
2580impl fmt::Display for CreateIndex {
2581 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2582 write!(
2583 f,
2584 "CREATE {unique}INDEX {concurrently}{if_not_exists}",
2585 unique = if self.unique { "UNIQUE " } else { "" },
2586 concurrently = if self.concurrently {
2587 "CONCURRENTLY "
2588 } else {
2589 ""
2590 },
2591 if_not_exists = if self.if_not_exists {
2592 "IF NOT EXISTS "
2593 } else {
2594 ""
2595 },
2596 )?;
2597 if let Some(value) = &self.name {
2598 write!(f, "{value} ")?;
2599 }
2600 write!(f, "ON {}", self.table_name)?;
2601 if let Some(value) = &self.using {
2602 write!(f, " USING {value} ")?;
2603 }
2604 write!(f, "({})", display_comma_separated(&self.columns))?;
2605 if !self.include.is_empty() {
2606 write!(f, " INCLUDE ({})", display_comma_separated(&self.include))?;
2607 }
2608 if let Some(value) = self.nulls_distinct {
2609 if value {
2610 write!(f, " NULLS DISTINCT")?;
2611 } else {
2612 write!(f, " NULLS NOT DISTINCT")?;
2613 }
2614 }
2615 if !self.with.is_empty() {
2616 write!(f, " WITH ({})", display_comma_separated(&self.with))?;
2617 }
2618 if let Some(predicate) = &self.predicate {
2619 write!(f, " WHERE {predicate}")?;
2620 }
2621 if !self.index_options.is_empty() {
2622 write!(f, " {}", display_separated(&self.index_options, " "))?;
2623 }
2624 if !self.alter_options.is_empty() {
2625 write!(f, " {}", display_separated(&self.alter_options, " "))?;
2626 }
2627 Ok(())
2628 }
2629}
2630
2631#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2633#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2634#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2635pub struct CreateTable {
2636 pub or_replace: bool,
2637 pub temporary: bool,
2638 pub external: bool,
2639 pub dynamic: bool,
2640 pub global: Option<bool>,
2641 pub if_not_exists: bool,
2642 pub transient: bool,
2643 pub volatile: bool,
2644 pub iceberg: bool,
2645 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2647 pub name: ObjectName,
2648 pub columns: Vec<ColumnDef>,
2650 pub constraints: Vec<TableConstraint>,
2651 pub hive_distribution: HiveDistributionStyle,
2652 pub hive_formats: Option<HiveFormat>,
2653 pub table_options: CreateTableOptions,
2654 pub file_format: Option<FileFormat>,
2655 pub location: Option<String>,
2656 pub query: Option<Box<Query>>,
2657 pub without_rowid: bool,
2658 pub like: Option<CreateTableLikeKind>,
2659 pub clone: Option<ObjectName>,
2660 pub version: Option<TableVersion>,
2661 pub comment: Option<CommentDef>,
2665 pub on_commit: Option<OnCommit>,
2666 pub on_cluster: Option<Ident>,
2669 pub primary_key: Option<Box<Expr>>,
2672 pub order_by: Option<OneOrManyWithParens<Expr>>,
2676 pub partition_by: Option<Box<Expr>>,
2679 pub cluster_by: Option<WrappedCollection<Vec<Expr>>>,
2684 pub clustered_by: Option<ClusteredBy>,
2687 pub inherits: Option<Vec<ObjectName>>,
2692 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
2696 pub partition_of: Option<ObjectName>,
2697 pub for_values: Option<ForValues>,
2700 pub strict: bool,
2704 pub copy_grants: bool,
2707 pub enable_schema_evolution: Option<bool>,
2710 pub change_tracking: Option<bool>,
2713 pub data_retention_time_in_days: Option<u64>,
2716 pub max_data_extension_time_in_days: Option<u64>,
2719 pub default_ddl_collation: Option<String>,
2722 pub with_aggregation_policy: Option<ObjectName>,
2725 pub with_row_access_policy: Option<RowAccessPolicy>,
2728 pub with_tags: Option<Vec<Tag>>,
2731 pub external_volume: Option<String>,
2734 pub base_location: Option<String>,
2737 pub catalog: Option<String>,
2740 pub catalog_sync: Option<String>,
2743 pub storage_serialization_policy: Option<StorageSerializationPolicy>,
2746 pub target_lag: Option<String>,
2749 pub warehouse: Option<Ident>,
2752 pub refresh_mode: Option<RefreshModeKind>,
2755 pub initialize: Option<InitializeKind>,
2758 pub require_user: bool,
2761}
2762
2763impl fmt::Display for CreateTable {
2764 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2765 write!(
2773 f,
2774 "CREATE {or_replace}{external}{global}{temporary}{transient}{volatile}{dynamic}{iceberg}TABLE {if_not_exists}{name}",
2775 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
2776 external = if self.external { "EXTERNAL " } else { "" },
2777 global = self.global
2778 .map(|global| {
2779 if global {
2780 "GLOBAL "
2781 } else {
2782 "LOCAL "
2783 }
2784 })
2785 .unwrap_or(""),
2786 if_not_exists = if self.if_not_exists { "IF NOT EXISTS " } else { "" },
2787 temporary = if self.temporary { "TEMPORARY " } else { "" },
2788 transient = if self.transient { "TRANSIENT " } else { "" },
2789 volatile = if self.volatile { "VOLATILE " } else { "" },
2790 iceberg = if self.iceberg { "ICEBERG " } else { "" },
2792 dynamic = if self.dynamic { "DYNAMIC " } else { "" },
2793 name = self.name,
2794 )?;
2795 if let Some(partition_of) = &self.partition_of {
2796 write!(f, " PARTITION OF {partition_of}")?;
2797 }
2798 if let Some(on_cluster) = &self.on_cluster {
2799 write!(f, " ON CLUSTER {on_cluster}")?;
2800 }
2801 if !self.columns.is_empty() || !self.constraints.is_empty() {
2802 f.write_str(" (")?;
2803 NewLine.fmt(f)?;
2804 Indent(DisplayCommaSeparated(&self.columns)).fmt(f)?;
2805 if !self.columns.is_empty() && !self.constraints.is_empty() {
2806 f.write_str(",")?;
2807 SpaceOrNewline.fmt(f)?;
2808 }
2809 Indent(DisplayCommaSeparated(&self.constraints)).fmt(f)?;
2810 NewLine.fmt(f)?;
2811 f.write_str(")")?;
2812 } else if self.query.is_none()
2813 && self.like.is_none()
2814 && self.clone.is_none()
2815 && self.partition_of.is_none()
2816 {
2817 f.write_str(" ()")?;
2819 } else if let Some(CreateTableLikeKind::Parenthesized(like_in_columns_list)) = &self.like {
2820 write!(f, " ({like_in_columns_list})")?;
2821 }
2822 if let Some(for_values) = &self.for_values {
2823 write!(f, " {for_values}")?;
2824 }
2825
2826 if let Some(comment) = &self.comment {
2829 write!(f, " COMMENT '{comment}'")?;
2830 }
2831
2832 if self.without_rowid {
2834 write!(f, " WITHOUT ROWID")?;
2835 }
2836
2837 if let Some(CreateTableLikeKind::Plain(like)) = &self.like {
2838 write!(f, " {like}")?;
2839 }
2840
2841 if let Some(c) = &self.clone {
2842 write!(f, " CLONE {c}")?;
2843 }
2844
2845 if let Some(version) = &self.version {
2846 write!(f, " {version}")?;
2847 }
2848
2849 match &self.hive_distribution {
2850 HiveDistributionStyle::PARTITIONED { columns } => {
2851 write!(f, " PARTITIONED BY ({})", display_comma_separated(columns))?;
2852 }
2853 HiveDistributionStyle::SKEWED {
2854 columns,
2855 on,
2856 stored_as_directories,
2857 } => {
2858 write!(
2859 f,
2860 " SKEWED BY ({})) ON ({})",
2861 display_comma_separated(columns),
2862 display_comma_separated(on)
2863 )?;
2864 if *stored_as_directories {
2865 write!(f, " STORED AS DIRECTORIES")?;
2866 }
2867 }
2868 _ => (),
2869 }
2870
2871 if let Some(clustered_by) = &self.clustered_by {
2872 write!(f, " {clustered_by}")?;
2873 }
2874
2875 if let Some(HiveFormat {
2876 row_format,
2877 serde_properties,
2878 storage,
2879 location,
2880 }) = &self.hive_formats
2881 {
2882 match row_format {
2883 Some(HiveRowFormat::SERDE { class }) => write!(f, " ROW FORMAT SERDE '{class}'")?,
2884 Some(HiveRowFormat::DELIMITED { delimiters }) => {
2885 write!(f, " ROW FORMAT DELIMITED")?;
2886 if !delimiters.is_empty() {
2887 write!(f, " {}", display_separated(delimiters, " "))?;
2888 }
2889 }
2890 None => (),
2891 }
2892 match storage {
2893 Some(HiveIOFormat::IOF {
2894 input_format,
2895 output_format,
2896 }) => write!(
2897 f,
2898 " STORED AS INPUTFORMAT {input_format} OUTPUTFORMAT {output_format}"
2899 )?,
2900 Some(HiveIOFormat::FileFormat { format }) if !self.external => {
2901 write!(f, " STORED AS {format}")?
2902 }
2903 _ => (),
2904 }
2905 if let Some(serde_properties) = serde_properties.as_ref() {
2906 write!(
2907 f,
2908 " WITH SERDEPROPERTIES ({})",
2909 display_comma_separated(serde_properties)
2910 )?;
2911 }
2912 if !self.external {
2913 if let Some(loc) = location {
2914 write!(f, " LOCATION '{loc}'")?;
2915 }
2916 }
2917 }
2918 if self.external {
2919 if let Some(file_format) = self.file_format {
2920 write!(f, " STORED AS {file_format}")?;
2921 }
2922 if let Some(location) = &self.location {
2923 write!(f, " LOCATION '{location}'")?;
2924 }
2925 }
2926
2927 match &self.table_options {
2928 options @ CreateTableOptions::With(_)
2929 | options @ CreateTableOptions::Plain(_)
2930 | options @ CreateTableOptions::TableProperties(_) => write!(f, " {options}")?,
2931 _ => (),
2932 }
2933
2934 if let Some(primary_key) = &self.primary_key {
2935 write!(f, " PRIMARY KEY {primary_key}")?;
2936 }
2937 if let Some(order_by) = &self.order_by {
2938 write!(f, " ORDER BY {order_by}")?;
2939 }
2940 if let Some(inherits) = &self.inherits {
2941 write!(f, " INHERITS ({})", display_comma_separated(inherits))?;
2942 }
2943 if let Some(partition_by) = self.partition_by.as_ref() {
2944 write!(f, " PARTITION BY {partition_by}")?;
2945 }
2946 if let Some(cluster_by) = self.cluster_by.as_ref() {
2947 write!(f, " CLUSTER BY {cluster_by}")?;
2948 }
2949 if let options @ CreateTableOptions::Options(_) = &self.table_options {
2950 write!(f, " {options}")?;
2951 }
2952 if let Some(external_volume) = self.external_volume.as_ref() {
2953 write!(f, " EXTERNAL_VOLUME='{external_volume}'")?;
2954 }
2955
2956 if let Some(catalog) = self.catalog.as_ref() {
2957 write!(f, " CATALOG='{catalog}'")?;
2958 }
2959
2960 if self.iceberg {
2961 if let Some(base_location) = self.base_location.as_ref() {
2962 write!(f, " BASE_LOCATION='{base_location}'")?;
2963 }
2964 }
2965
2966 if let Some(catalog_sync) = self.catalog_sync.as_ref() {
2967 write!(f, " CATALOG_SYNC='{catalog_sync}'")?;
2968 }
2969
2970 if let Some(storage_serialization_policy) = self.storage_serialization_policy.as_ref() {
2971 write!(
2972 f,
2973 " STORAGE_SERIALIZATION_POLICY={storage_serialization_policy}"
2974 )?;
2975 }
2976
2977 if self.copy_grants {
2978 write!(f, " COPY GRANTS")?;
2979 }
2980
2981 if let Some(is_enabled) = self.enable_schema_evolution {
2982 write!(
2983 f,
2984 " ENABLE_SCHEMA_EVOLUTION={}",
2985 if is_enabled { "TRUE" } else { "FALSE" }
2986 )?;
2987 }
2988
2989 if let Some(is_enabled) = self.change_tracking {
2990 write!(
2991 f,
2992 " CHANGE_TRACKING={}",
2993 if is_enabled { "TRUE" } else { "FALSE" }
2994 )?;
2995 }
2996
2997 if let Some(data_retention_time_in_days) = self.data_retention_time_in_days {
2998 write!(
2999 f,
3000 " DATA_RETENTION_TIME_IN_DAYS={data_retention_time_in_days}",
3001 )?;
3002 }
3003
3004 if let Some(max_data_extension_time_in_days) = self.max_data_extension_time_in_days {
3005 write!(
3006 f,
3007 " MAX_DATA_EXTENSION_TIME_IN_DAYS={max_data_extension_time_in_days}",
3008 )?;
3009 }
3010
3011 if let Some(default_ddl_collation) = &self.default_ddl_collation {
3012 write!(f, " DEFAULT_DDL_COLLATION='{default_ddl_collation}'",)?;
3013 }
3014
3015 if let Some(with_aggregation_policy) = &self.with_aggregation_policy {
3016 write!(f, " WITH AGGREGATION POLICY {with_aggregation_policy}",)?;
3017 }
3018
3019 if let Some(row_access_policy) = &self.with_row_access_policy {
3020 write!(f, " {row_access_policy}",)?;
3021 }
3022
3023 if let Some(tag) = &self.with_tags {
3024 write!(f, " WITH TAG ({})", display_comma_separated(tag.as_slice()))?;
3025 }
3026
3027 if let Some(target_lag) = &self.target_lag {
3028 write!(f, " TARGET_LAG='{target_lag}'")?;
3029 }
3030
3031 if let Some(warehouse) = &self.warehouse {
3032 write!(f, " WAREHOUSE={warehouse}")?;
3033 }
3034
3035 if let Some(refresh_mode) = &self.refresh_mode {
3036 write!(f, " REFRESH_MODE={refresh_mode}")?;
3037 }
3038
3039 if let Some(initialize) = &self.initialize {
3040 write!(f, " INITIALIZE={initialize}")?;
3041 }
3042
3043 if self.require_user {
3044 write!(f, " REQUIRE USER")?;
3045 }
3046
3047 if self.on_commit.is_some() {
3048 let on_commit = match self.on_commit {
3049 Some(OnCommit::DeleteRows) => "ON COMMIT DELETE ROWS",
3050 Some(OnCommit::PreserveRows) => "ON COMMIT PRESERVE ROWS",
3051 Some(OnCommit::Drop) => "ON COMMIT DROP",
3052 None => "",
3053 };
3054 write!(f, " {on_commit}")?;
3055 }
3056 if self.strict {
3057 write!(f, " STRICT")?;
3058 }
3059 if let Some(query) = &self.query {
3060 write!(f, " AS {query}")?;
3061 }
3062 Ok(())
3063 }
3064}
3065
3066#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3072#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3073#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3074pub enum ForValues {
3075 In(Vec<Expr>),
3077 From {
3079 from: Vec<PartitionBoundValue>,
3080 to: Vec<PartitionBoundValue>,
3081 },
3082 With { modulus: u64, remainder: u64 },
3084 Default,
3086}
3087
3088impl fmt::Display for ForValues {
3089 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3090 match self {
3091 ForValues::In(values) => {
3092 write!(f, "FOR VALUES IN ({})", display_comma_separated(values))
3093 }
3094 ForValues::From { from, to } => {
3095 write!(
3096 f,
3097 "FOR VALUES FROM ({}) TO ({})",
3098 display_comma_separated(from),
3099 display_comma_separated(to)
3100 )
3101 }
3102 ForValues::With { modulus, remainder } => {
3103 write!(
3104 f,
3105 "FOR VALUES WITH (MODULUS {modulus}, REMAINDER {remainder})"
3106 )
3107 }
3108 ForValues::Default => write!(f, "DEFAULT"),
3109 }
3110 }
3111}
3112
3113#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3118#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3119#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3120pub enum PartitionBoundValue {
3121 Expr(Expr),
3122 MinValue,
3123 MaxValue,
3124}
3125
3126impl fmt::Display for PartitionBoundValue {
3127 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3128 match self {
3129 PartitionBoundValue::Expr(expr) => write!(f, "{expr}"),
3130 PartitionBoundValue::MinValue => write!(f, "MINVALUE"),
3131 PartitionBoundValue::MaxValue => write!(f, "MAXVALUE"),
3132 }
3133 }
3134}
3135
3136#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3137#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3138#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3139pub struct CreateDomain {
3152 pub name: ObjectName,
3154 pub data_type: DataType,
3156 pub collation: Option<Ident>,
3158 pub default: Option<Expr>,
3160 pub constraints: Vec<TableConstraint>,
3162}
3163
3164impl fmt::Display for CreateDomain {
3165 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3166 write!(
3167 f,
3168 "CREATE DOMAIN {name} AS {data_type}",
3169 name = self.name,
3170 data_type = self.data_type
3171 )?;
3172 if let Some(collation) = &self.collation {
3173 write!(f, " COLLATE {collation}")?;
3174 }
3175 if let Some(default) = &self.default {
3176 write!(f, " DEFAULT {default}")?;
3177 }
3178 if !self.constraints.is_empty() {
3179 write!(f, " {}", display_separated(&self.constraints, " "))?;
3180 }
3181 Ok(())
3182 }
3183}
3184
3185#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3186#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3187#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3188pub struct CreateFunction {
3189 pub or_alter: bool,
3193 pub or_replace: bool,
3194 pub temporary: bool,
3195 pub if_not_exists: bool,
3196 pub name: ObjectName,
3197 pub args: Option<Vec<OperateFunctionArg>>,
3198 pub return_type: Option<DataType>,
3199 pub function_body: Option<CreateFunctionBody>,
3207 pub behavior: Option<FunctionBehavior>,
3213 pub called_on_null: Option<FunctionCalledOnNull>,
3217 pub parallel: Option<FunctionParallel>,
3221 pub security: Option<FunctionSecurity>,
3225 pub set_params: Vec<FunctionDefinitionSetParam>,
3229 pub using: Option<CreateFunctionUsing>,
3231 pub language: Option<Ident>,
3239 pub determinism_specifier: Option<FunctionDeterminismSpecifier>,
3243 pub options: Option<Vec<SqlOption>>,
3247 pub remote_connection: Option<ObjectName>,
3257}
3258
3259impl fmt::Display for CreateFunction {
3260 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3261 write!(
3262 f,
3263 "CREATE {or_alter}{or_replace}{temp}FUNCTION {if_not_exists}{name}",
3264 name = self.name,
3265 temp = if self.temporary { "TEMPORARY " } else { "" },
3266 or_alter = if self.or_alter { "OR ALTER " } else { "" },
3267 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3268 if_not_exists = if self.if_not_exists {
3269 "IF NOT EXISTS "
3270 } else {
3271 ""
3272 },
3273 )?;
3274 if let Some(args) = &self.args {
3275 write!(f, "({})", display_comma_separated(args))?;
3276 }
3277 if let Some(return_type) = &self.return_type {
3278 write!(f, " RETURNS {return_type}")?;
3279 }
3280 if let Some(determinism_specifier) = &self.determinism_specifier {
3281 write!(f, " {determinism_specifier}")?;
3282 }
3283 if let Some(language) = &self.language {
3284 write!(f, " LANGUAGE {language}")?;
3285 }
3286 if let Some(behavior) = &self.behavior {
3287 write!(f, " {behavior}")?;
3288 }
3289 if let Some(called_on_null) = &self.called_on_null {
3290 write!(f, " {called_on_null}")?;
3291 }
3292 if let Some(parallel) = &self.parallel {
3293 write!(f, " {parallel}")?;
3294 }
3295 if let Some(security) = &self.security {
3296 write!(f, " {security}")?;
3297 }
3298 for set_param in &self.set_params {
3299 write!(f, " {set_param}")?;
3300 }
3301 if let Some(remote_connection) = &self.remote_connection {
3302 write!(f, " REMOTE WITH CONNECTION {remote_connection}")?;
3303 }
3304 if let Some(CreateFunctionBody::AsBeforeOptions { body, link_symbol }) = &self.function_body
3305 {
3306 write!(f, " AS {body}")?;
3307 if let Some(link_symbol) = link_symbol {
3308 write!(f, ", {link_symbol}")?;
3309 }
3310 }
3311 if let Some(CreateFunctionBody::Return(function_body)) = &self.function_body {
3312 write!(f, " RETURN {function_body}")?;
3313 }
3314 if let Some(CreateFunctionBody::AsReturnExpr(function_body)) = &self.function_body {
3315 write!(f, " AS RETURN {function_body}")?;
3316 }
3317 if let Some(CreateFunctionBody::AsReturnSelect(function_body)) = &self.function_body {
3318 write!(f, " AS RETURN {function_body}")?;
3319 }
3320 if let Some(using) = &self.using {
3321 write!(f, " {using}")?;
3322 }
3323 if let Some(options) = &self.options {
3324 write!(
3325 f,
3326 " OPTIONS({})",
3327 display_comma_separated(options.as_slice())
3328 )?;
3329 }
3330 if let Some(CreateFunctionBody::AsAfterOptions(function_body)) = &self.function_body {
3331 write!(f, " AS {function_body}")?;
3332 }
3333 if let Some(CreateFunctionBody::AsBeginEnd(bes)) = &self.function_body {
3334 write!(f, " AS {bes}")?;
3335 }
3336 Ok(())
3337 }
3338}
3339
3340#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3350#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3351#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3352pub struct CreateConnector {
3353 pub name: Ident,
3354 pub if_not_exists: bool,
3355 pub connector_type: Option<String>,
3356 pub url: Option<String>,
3357 pub comment: Option<CommentDef>,
3358 pub with_dcproperties: Option<Vec<SqlOption>>,
3359}
3360
3361impl fmt::Display for CreateConnector {
3362 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3363 write!(
3364 f,
3365 "CREATE CONNECTOR {if_not_exists}{name}",
3366 if_not_exists = if self.if_not_exists {
3367 "IF NOT EXISTS "
3368 } else {
3369 ""
3370 },
3371 name = self.name,
3372 )?;
3373
3374 if let Some(connector_type) = &self.connector_type {
3375 write!(f, " TYPE '{connector_type}'")?;
3376 }
3377
3378 if let Some(url) = &self.url {
3379 write!(f, " URL '{url}'")?;
3380 }
3381
3382 if let Some(comment) = &self.comment {
3383 write!(f, " COMMENT = '{comment}'")?;
3384 }
3385
3386 if let Some(with_dcproperties) = &self.with_dcproperties {
3387 write!(
3388 f,
3389 " WITH DCPROPERTIES({})",
3390 display_comma_separated(with_dcproperties)
3391 )?;
3392 }
3393
3394 Ok(())
3395 }
3396}
3397
3398#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3403#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3404#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3405pub enum AlterSchemaOperation {
3406 SetDefaultCollate {
3407 collate: Expr,
3408 },
3409 AddReplica {
3410 replica: Ident,
3411 options: Option<Vec<SqlOption>>,
3412 },
3413 DropReplica {
3414 replica: Ident,
3415 },
3416 SetOptionsParens {
3417 options: Vec<SqlOption>,
3418 },
3419 Rename {
3420 name: ObjectName,
3421 },
3422 OwnerTo {
3423 owner: Owner,
3424 },
3425}
3426
3427impl fmt::Display for AlterSchemaOperation {
3428 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3429 match self {
3430 AlterSchemaOperation::SetDefaultCollate { collate } => {
3431 write!(f, "SET DEFAULT COLLATE {collate}")
3432 }
3433 AlterSchemaOperation::AddReplica { replica, options } => {
3434 write!(f, "ADD REPLICA {replica}")?;
3435 if let Some(options) = options {
3436 write!(f, " OPTIONS ({})", display_comma_separated(options))?;
3437 }
3438 Ok(())
3439 }
3440 AlterSchemaOperation::DropReplica { replica } => write!(f, "DROP REPLICA {replica}"),
3441 AlterSchemaOperation::SetOptionsParens { options } => {
3442 write!(f, "SET OPTIONS ({})", display_comma_separated(options))
3443 }
3444 AlterSchemaOperation::Rename { name } => write!(f, "RENAME TO {name}"),
3445 AlterSchemaOperation::OwnerTo { owner } => write!(f, "OWNER TO {owner}"),
3446 }
3447 }
3448}
3449#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3455#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3456#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3457pub enum RenameTableNameKind {
3458 As(ObjectName),
3459 To(ObjectName),
3460}
3461
3462impl fmt::Display for RenameTableNameKind {
3463 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3464 match self {
3465 RenameTableNameKind::As(name) => write!(f, "AS {name}"),
3466 RenameTableNameKind::To(name) => write!(f, "TO {name}"),
3467 }
3468 }
3469}
3470
3471#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3472#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3473#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3474pub struct AlterSchema {
3475 pub name: ObjectName,
3476 pub if_exists: bool,
3477 pub operations: Vec<AlterSchemaOperation>,
3478}
3479
3480impl fmt::Display for AlterSchema {
3481 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3482 write!(f, "ALTER SCHEMA ")?;
3483 if self.if_exists {
3484 write!(f, "IF EXISTS ")?;
3485 }
3486 write!(f, "{}", self.name)?;
3487 for operation in &self.operations {
3488 write!(f, " {operation}")?;
3489 }
3490
3491 Ok(())
3492 }
3493}
3494
3495impl Spanned for RenameTableNameKind {
3496 fn span(&self) -> Span {
3497 match self {
3498 RenameTableNameKind::As(name) => name.span(),
3499 RenameTableNameKind::To(name) => name.span(),
3500 }
3501 }
3502}
3503
3504#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3505#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3506#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3507pub enum TriggerObjectKind {
3509 For(TriggerObject),
3511 ForEach(TriggerObject),
3513}
3514
3515impl Display for TriggerObjectKind {
3516 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3517 match self {
3518 TriggerObjectKind::For(obj) => write!(f, "FOR {obj}"),
3519 TriggerObjectKind::ForEach(obj) => write!(f, "FOR EACH {obj}"),
3520 }
3521 }
3522}
3523
3524#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3525#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3526#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3527pub struct CreateTrigger {
3541 pub or_alter: bool,
3545 pub temporary: bool,
3562 pub or_replace: bool,
3572 pub is_constraint: bool,
3574 pub name: ObjectName,
3576 pub period: Option<TriggerPeriod>,
3605 pub period_before_table: bool,
3616 pub events: Vec<TriggerEvent>,
3618 pub table_name: ObjectName,
3620 pub referenced_table_name: Option<ObjectName>,
3623 pub referencing: Vec<TriggerReferencing>,
3625 pub trigger_object: Option<TriggerObjectKind>,
3630 pub condition: Option<Expr>,
3632 pub exec_body: Option<TriggerExecBody>,
3634 pub statements_as: bool,
3636 pub statements: Option<ConditionalStatements>,
3638 pub characteristics: Option<ConstraintCharacteristics>,
3640}
3641
3642impl Display for CreateTrigger {
3643 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3644 let CreateTrigger {
3645 or_alter,
3646 temporary,
3647 or_replace,
3648 is_constraint,
3649 name,
3650 period_before_table,
3651 period,
3652 events,
3653 table_name,
3654 referenced_table_name,
3655 referencing,
3656 trigger_object,
3657 condition,
3658 exec_body,
3659 statements_as,
3660 statements,
3661 characteristics,
3662 } = self;
3663 write!(
3664 f,
3665 "CREATE {temporary}{or_alter}{or_replace}{is_constraint}TRIGGER {name} ",
3666 temporary = if *temporary { "TEMPORARY " } else { "" },
3667 or_alter = if *or_alter { "OR ALTER " } else { "" },
3668 or_replace = if *or_replace { "OR REPLACE " } else { "" },
3669 is_constraint = if *is_constraint { "CONSTRAINT " } else { "" },
3670 )?;
3671
3672 if *period_before_table {
3673 if let Some(p) = period {
3674 write!(f, "{p} ")?;
3675 }
3676 if !events.is_empty() {
3677 write!(f, "{} ", display_separated(events, " OR "))?;
3678 }
3679 write!(f, "ON {table_name}")?;
3680 } else {
3681 write!(f, "ON {table_name} ")?;
3682 if let Some(p) = period {
3683 write!(f, "{p}")?;
3684 }
3685 if !events.is_empty() {
3686 write!(f, " {}", display_separated(events, ", "))?;
3687 }
3688 }
3689
3690 if let Some(referenced_table_name) = referenced_table_name {
3691 write!(f, " FROM {referenced_table_name}")?;
3692 }
3693
3694 if let Some(characteristics) = characteristics {
3695 write!(f, " {characteristics}")?;
3696 }
3697
3698 if !referencing.is_empty() {
3699 write!(f, " REFERENCING {}", display_separated(referencing, " "))?;
3700 }
3701
3702 if let Some(trigger_object) = trigger_object {
3703 write!(f, " {trigger_object}")?;
3704 }
3705 if let Some(condition) = condition {
3706 write!(f, " WHEN {condition}")?;
3707 }
3708 if let Some(exec_body) = exec_body {
3709 write!(f, " EXECUTE {exec_body}")?;
3710 }
3711 if let Some(statements) = statements {
3712 if *statements_as {
3713 write!(f, " AS")?;
3714 }
3715 write!(f, " {statements}")?;
3716 }
3717 Ok(())
3718 }
3719}
3720
3721#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3722#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3723#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3724pub struct DropTrigger {
3731 pub if_exists: bool,
3733 pub trigger_name: ObjectName,
3735 pub table_name: Option<ObjectName>,
3737 pub option: Option<ReferentialAction>,
3739}
3740
3741impl fmt::Display for DropTrigger {
3742 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3743 let DropTrigger {
3744 if_exists,
3745 trigger_name,
3746 table_name,
3747 option,
3748 } = self;
3749 write!(f, "DROP TRIGGER")?;
3750 if *if_exists {
3751 write!(f, " IF EXISTS")?;
3752 }
3753 match &table_name {
3754 Some(table_name) => write!(f, " {trigger_name} ON {table_name}")?,
3755 None => write!(f, " {trigger_name}")?,
3756 };
3757 if let Some(option) = option {
3758 write!(f, " {option}")?;
3759 }
3760 Ok(())
3761 }
3762}
3763
3764#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3770#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3771#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3772pub struct Truncate {
3773 pub table_names: Vec<super::TruncateTableTarget>,
3775 pub partitions: Option<Vec<Expr>>,
3777 pub table: bool,
3779 pub identity: Option<super::TruncateIdentityOption>,
3781 pub cascade: Option<super::CascadeOption>,
3783 pub on_cluster: Option<Ident>,
3786}
3787
3788impl fmt::Display for Truncate {
3789 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3790 let table = if self.table { "TABLE " } else { "" };
3791
3792 write!(
3793 f,
3794 "TRUNCATE {table}{table_names}",
3795 table_names = display_comma_separated(&self.table_names)
3796 )?;
3797
3798 if let Some(identity) = &self.identity {
3799 match identity {
3800 super::TruncateIdentityOption::Restart => write!(f, " RESTART IDENTITY")?,
3801 super::TruncateIdentityOption::Continue => write!(f, " CONTINUE IDENTITY")?,
3802 }
3803 }
3804 if let Some(cascade) = &self.cascade {
3805 match cascade {
3806 super::CascadeOption::Cascade => write!(f, " CASCADE")?,
3807 super::CascadeOption::Restrict => write!(f, " RESTRICT")?,
3808 }
3809 }
3810
3811 if let Some(ref parts) = &self.partitions {
3812 if !parts.is_empty() {
3813 write!(f, " PARTITION ({})", display_comma_separated(parts))?;
3814 }
3815 }
3816 if let Some(on_cluster) = &self.on_cluster {
3817 write!(f, " ON CLUSTER {on_cluster}")?;
3818 }
3819 Ok(())
3820 }
3821}
3822
3823impl Spanned for Truncate {
3824 fn span(&self) -> Span {
3825 Span::union_iter(
3826 self.table_names.iter().map(|i| i.name.span()).chain(
3827 self.partitions
3828 .iter()
3829 .flat_map(|i| i.iter().map(|k| k.span())),
3830 ),
3831 )
3832 }
3833}
3834
3835#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3842#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3843#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3844pub struct Msck {
3845 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3847 pub table_name: ObjectName,
3848 pub repair: bool,
3850 pub partition_action: Option<super::AddDropSync>,
3852}
3853
3854impl fmt::Display for Msck {
3855 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3856 write!(
3857 f,
3858 "MSCK {repair}TABLE {table}",
3859 repair = if self.repair { "REPAIR " } else { "" },
3860 table = self.table_name
3861 )?;
3862 if let Some(pa) = &self.partition_action {
3863 write!(f, " {pa}")?;
3864 }
3865 Ok(())
3866 }
3867}
3868
3869impl Spanned for Msck {
3870 fn span(&self) -> Span {
3871 self.table_name.span()
3872 }
3873}
3874
3875#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3877#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3878#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3879pub struct CreateView {
3880 pub or_alter: bool,
3884 pub or_replace: bool,
3885 pub materialized: bool,
3886 pub secure: bool,
3889 pub name: ObjectName,
3891 pub name_before_not_exists: bool,
3902 pub columns: Vec<ViewColumnDef>,
3903 pub query: Box<Query>,
3904 pub options: CreateTableOptions,
3905 pub cluster_by: Vec<Ident>,
3906 pub comment: Option<String>,
3909 pub with_no_schema_binding: bool,
3911 pub if_not_exists: bool,
3913 pub temporary: bool,
3915 pub to: Option<ObjectName>,
3918 pub params: Option<CreateViewParams>,
3920}
3921
3922impl fmt::Display for CreateView {
3923 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3924 write!(
3925 f,
3926 "CREATE {or_alter}{or_replace}",
3927 or_alter = if self.or_alter { "OR ALTER " } else { "" },
3928 or_replace = if self.or_replace { "OR REPLACE " } else { "" },
3929 )?;
3930 if let Some(ref params) = self.params {
3931 params.fmt(f)?;
3932 }
3933 write!(
3934 f,
3935 "{secure}{materialized}{temporary}VIEW {if_not_and_name}{to}",
3936 if_not_and_name = if self.if_not_exists {
3937 if self.name_before_not_exists {
3938 format!("{} IF NOT EXISTS", self.name)
3939 } else {
3940 format!("IF NOT EXISTS {}", self.name)
3941 }
3942 } else {
3943 format!("{}", self.name)
3944 },
3945 secure = if self.secure { "SECURE " } else { "" },
3946 materialized = if self.materialized {
3947 "MATERIALIZED "
3948 } else {
3949 ""
3950 },
3951 temporary = if self.temporary { "TEMPORARY " } else { "" },
3952 to = self
3953 .to
3954 .as_ref()
3955 .map(|to| format!(" TO {to}"))
3956 .unwrap_or_default()
3957 )?;
3958 if !self.columns.is_empty() {
3959 write!(f, " ({})", display_comma_separated(&self.columns))?;
3960 }
3961 if matches!(self.options, CreateTableOptions::With(_)) {
3962 write!(f, " {}", self.options)?;
3963 }
3964 if let Some(ref comment) = self.comment {
3965 write!(f, " COMMENT = '{}'", escape_single_quote_string(comment))?;
3966 }
3967 if !self.cluster_by.is_empty() {
3968 write!(
3969 f,
3970 " CLUSTER BY ({})",
3971 display_comma_separated(&self.cluster_by)
3972 )?;
3973 }
3974 if matches!(self.options, CreateTableOptions::Options(_)) {
3975 write!(f, " {}", self.options)?;
3976 }
3977 f.write_str(" AS")?;
3978 SpaceOrNewline.fmt(f)?;
3979 self.query.fmt(f)?;
3980 if self.with_no_schema_binding {
3981 write!(f, " WITH NO SCHEMA BINDING")?;
3982 }
3983 Ok(())
3984 }
3985}
3986
3987#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3990#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3991#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3992pub struct CreateExtension {
3993 pub name: Ident,
3994 pub if_not_exists: bool,
3995 pub cascade: bool,
3996 pub schema: Option<Ident>,
3997 pub version: Option<Ident>,
3998}
3999
4000impl fmt::Display for CreateExtension {
4001 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4002 write!(
4003 f,
4004 "CREATE EXTENSION {if_not_exists}{name}",
4005 if_not_exists = if self.if_not_exists {
4006 "IF NOT EXISTS "
4007 } else {
4008 ""
4009 },
4010 name = self.name
4011 )?;
4012 if self.cascade || self.schema.is_some() || self.version.is_some() {
4013 write!(f, " WITH")?;
4014
4015 if let Some(name) = &self.schema {
4016 write!(f, " SCHEMA {name}")?;
4017 }
4018 if let Some(version) = &self.version {
4019 write!(f, " VERSION {version}")?;
4020 }
4021 if self.cascade {
4022 write!(f, " CASCADE")?;
4023 }
4024 }
4025
4026 Ok(())
4027 }
4028}
4029
4030impl Spanned for CreateExtension {
4031 fn span(&self) -> Span {
4032 Span::empty()
4033 }
4034}
4035
4036#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4044#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4045#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4046pub struct DropExtension {
4047 pub names: Vec<Ident>,
4048 pub if_exists: bool,
4049 pub cascade_or_restrict: Option<ReferentialAction>,
4051}
4052
4053impl fmt::Display for DropExtension {
4054 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4055 write!(f, "DROP EXTENSION")?;
4056 if self.if_exists {
4057 write!(f, " IF EXISTS")?;
4058 }
4059 write!(f, " {}", display_comma_separated(&self.names))?;
4060 if let Some(cascade_or_restrict) = &self.cascade_or_restrict {
4061 write!(f, " {cascade_or_restrict}")?;
4062 }
4063 Ok(())
4064 }
4065}
4066
4067impl Spanned for DropExtension {
4068 fn span(&self) -> Span {
4069 Span::empty()
4070 }
4071}
4072
4073#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4076#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4077#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4078pub enum AlterTableType {
4079 Iceberg,
4082 Dynamic,
4085}
4086
4087#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4089#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4090#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4091pub struct AlterTable {
4092 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4094 pub name: ObjectName,
4095 pub if_exists: bool,
4096 pub only: bool,
4097 pub operations: Vec<AlterTableOperation>,
4098 pub location: Option<HiveSetLocation>,
4099 pub on_cluster: Option<Ident>,
4103 pub table_type: Option<AlterTableType>,
4105 pub end_token: AttachedToken,
4107}
4108
4109impl fmt::Display for AlterTable {
4110 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4111 match &self.table_type {
4112 Some(AlterTableType::Iceberg) => write!(f, "ALTER ICEBERG TABLE ")?,
4113 Some(AlterTableType::Dynamic) => write!(f, "ALTER DYNAMIC TABLE ")?,
4114 None => write!(f, "ALTER TABLE ")?,
4115 }
4116
4117 if self.if_exists {
4118 write!(f, "IF EXISTS ")?;
4119 }
4120 if self.only {
4121 write!(f, "ONLY ")?;
4122 }
4123 write!(f, "{} ", &self.name)?;
4124 if let Some(cluster) = &self.on_cluster {
4125 write!(f, "ON CLUSTER {cluster} ")?;
4126 }
4127 write!(f, "{}", display_comma_separated(&self.operations))?;
4128 if let Some(loc) = &self.location {
4129 write!(f, " {loc}")?
4130 }
4131 Ok(())
4132 }
4133}
4134
4135#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4137#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4138#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4139pub struct DropFunction {
4140 pub if_exists: bool,
4141 pub func_desc: Vec<FunctionDesc>,
4143 pub drop_behavior: Option<DropBehavior>,
4145}
4146
4147impl fmt::Display for DropFunction {
4148 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4149 write!(
4150 f,
4151 "DROP FUNCTION{} {}",
4152 if self.if_exists { " IF EXISTS" } else { "" },
4153 display_comma_separated(&self.func_desc),
4154 )?;
4155 if let Some(op) = &self.drop_behavior {
4156 write!(f, " {op}")?;
4157 }
4158 Ok(())
4159 }
4160}
4161
4162impl Spanned for DropFunction {
4163 fn span(&self) -> Span {
4164 Span::empty()
4165 }
4166}
4167
4168#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4171#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4172#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4173pub struct CreateOperator {
4174 pub name: ObjectName,
4176 pub function: ObjectName,
4178 pub is_procedure: bool,
4180 pub left_arg: Option<DataType>,
4182 pub right_arg: Option<DataType>,
4184 pub options: Vec<OperatorOption>,
4186}
4187
4188#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4191#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4192#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4193pub struct CreateOperatorFamily {
4194 pub name: ObjectName,
4196 pub using: Ident,
4198}
4199
4200#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4203#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4204#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4205pub struct CreateOperatorClass {
4206 pub name: ObjectName,
4208 pub default: bool,
4210 pub for_type: DataType,
4212 pub using: Ident,
4214 pub family: Option<ObjectName>,
4216 pub items: Vec<OperatorClassItem>,
4218}
4219
4220impl fmt::Display for CreateOperator {
4221 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4222 write!(f, "CREATE OPERATOR {} (", self.name)?;
4223
4224 let function_keyword = if self.is_procedure {
4225 "PROCEDURE"
4226 } else {
4227 "FUNCTION"
4228 };
4229 let mut params = vec![format!("{} = {}", function_keyword, self.function)];
4230
4231 if let Some(left_arg) = &self.left_arg {
4232 params.push(format!("LEFTARG = {}", left_arg));
4233 }
4234 if let Some(right_arg) = &self.right_arg {
4235 params.push(format!("RIGHTARG = {}", right_arg));
4236 }
4237
4238 for option in &self.options {
4239 params.push(option.to_string());
4240 }
4241
4242 write!(f, "{}", params.join(", "))?;
4243 write!(f, ")")
4244 }
4245}
4246
4247impl fmt::Display for CreateOperatorFamily {
4248 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4249 write!(
4250 f,
4251 "CREATE OPERATOR FAMILY {} USING {}",
4252 self.name, self.using
4253 )
4254 }
4255}
4256
4257impl fmt::Display for CreateOperatorClass {
4258 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4259 write!(f, "CREATE OPERATOR CLASS {}", self.name)?;
4260 if self.default {
4261 write!(f, " DEFAULT")?;
4262 }
4263 write!(f, " FOR TYPE {} USING {}", self.for_type, self.using)?;
4264 if let Some(family) = &self.family {
4265 write!(f, " FAMILY {}", family)?;
4266 }
4267 write!(f, " AS {}", display_comma_separated(&self.items))
4268 }
4269}
4270
4271#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4273#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4274#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4275pub struct OperatorArgTypes {
4276 pub left: DataType,
4277 pub right: DataType,
4278}
4279
4280impl fmt::Display for OperatorArgTypes {
4281 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4282 write!(f, "{}, {}", self.left, self.right)
4283 }
4284}
4285
4286#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4288#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4289#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4290pub enum OperatorClassItem {
4291 Operator {
4293 strategy_number: u32,
4294 operator_name: ObjectName,
4295 op_types: Option<OperatorArgTypes>,
4297 purpose: Option<OperatorPurpose>,
4299 },
4300 Function {
4302 support_number: u32,
4303 op_types: Option<Vec<DataType>>,
4305 function_name: ObjectName,
4306 argument_types: Vec<DataType>,
4308 },
4309 Storage { storage_type: DataType },
4311}
4312
4313#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4315#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4316#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4317pub enum OperatorPurpose {
4318 ForSearch,
4319 ForOrderBy { sort_family: ObjectName },
4320}
4321
4322impl fmt::Display for OperatorClassItem {
4323 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4324 match self {
4325 OperatorClassItem::Operator {
4326 strategy_number,
4327 operator_name,
4328 op_types,
4329 purpose,
4330 } => {
4331 write!(f, "OPERATOR {strategy_number} {operator_name}")?;
4332 if let Some(types) = op_types {
4333 write!(f, " ({types})")?;
4334 }
4335 if let Some(purpose) = purpose {
4336 write!(f, " {purpose}")?;
4337 }
4338 Ok(())
4339 }
4340 OperatorClassItem::Function {
4341 support_number,
4342 op_types,
4343 function_name,
4344 argument_types,
4345 } => {
4346 write!(f, "FUNCTION {support_number}")?;
4347 if let Some(types) = op_types {
4348 write!(f, " ({})", display_comma_separated(types))?;
4349 }
4350 write!(f, " {function_name}")?;
4351 if !argument_types.is_empty() {
4352 write!(f, "({})", display_comma_separated(argument_types))?;
4353 }
4354 Ok(())
4355 }
4356 OperatorClassItem::Storage { storage_type } => {
4357 write!(f, "STORAGE {storage_type}")
4358 }
4359 }
4360 }
4361}
4362
4363impl fmt::Display for OperatorPurpose {
4364 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4365 match self {
4366 OperatorPurpose::ForSearch => write!(f, "FOR SEARCH"),
4367 OperatorPurpose::ForOrderBy { sort_family } => {
4368 write!(f, "FOR ORDER BY {sort_family}")
4369 }
4370 }
4371 }
4372}
4373
4374#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4377#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4378#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4379pub struct DropOperator {
4380 pub if_exists: bool,
4382 pub operators: Vec<DropOperatorSignature>,
4384 pub drop_behavior: Option<DropBehavior>,
4386}
4387
4388#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4390#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4391#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4392pub struct DropOperatorSignature {
4393 pub name: ObjectName,
4395 pub left_type: Option<DataType>,
4397 pub right_type: DataType,
4399}
4400
4401impl fmt::Display for DropOperatorSignature {
4402 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4403 write!(f, "{} (", self.name)?;
4404 if let Some(left_type) = &self.left_type {
4405 write!(f, "{}", left_type)?;
4406 } else {
4407 write!(f, "NONE")?;
4408 }
4409 write!(f, ", {})", self.right_type)
4410 }
4411}
4412
4413impl fmt::Display for DropOperator {
4414 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4415 write!(f, "DROP OPERATOR")?;
4416 if self.if_exists {
4417 write!(f, " IF EXISTS")?;
4418 }
4419 write!(f, " {}", display_comma_separated(&self.operators))?;
4420 if let Some(drop_behavior) = &self.drop_behavior {
4421 write!(f, " {}", drop_behavior)?;
4422 }
4423 Ok(())
4424 }
4425}
4426
4427impl Spanned for DropOperator {
4428 fn span(&self) -> Span {
4429 Span::empty()
4430 }
4431}
4432
4433#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4436#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4437#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4438pub struct DropOperatorFamily {
4439 pub if_exists: bool,
4441 pub names: Vec<ObjectName>,
4443 pub using: Ident,
4445 pub drop_behavior: Option<DropBehavior>,
4447}
4448
4449impl fmt::Display for DropOperatorFamily {
4450 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4451 write!(f, "DROP OPERATOR FAMILY")?;
4452 if self.if_exists {
4453 write!(f, " IF EXISTS")?;
4454 }
4455 write!(f, " {}", display_comma_separated(&self.names))?;
4456 write!(f, " USING {}", self.using)?;
4457 if let Some(drop_behavior) = &self.drop_behavior {
4458 write!(f, " {}", drop_behavior)?;
4459 }
4460 Ok(())
4461 }
4462}
4463
4464impl Spanned for DropOperatorFamily {
4465 fn span(&self) -> Span {
4466 Span::empty()
4467 }
4468}
4469
4470#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4473#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4474#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4475pub struct DropOperatorClass {
4476 pub if_exists: bool,
4478 pub names: Vec<ObjectName>,
4480 pub using: Ident,
4482 pub drop_behavior: Option<DropBehavior>,
4484}
4485
4486impl fmt::Display for DropOperatorClass {
4487 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4488 write!(f, "DROP OPERATOR CLASS")?;
4489 if self.if_exists {
4490 write!(f, " IF EXISTS")?;
4491 }
4492 write!(f, " {}", display_comma_separated(&self.names))?;
4493 write!(f, " USING {}", self.using)?;
4494 if let Some(drop_behavior) = &self.drop_behavior {
4495 write!(f, " {}", drop_behavior)?;
4496 }
4497 Ok(())
4498 }
4499}
4500
4501impl Spanned for DropOperatorClass {
4502 fn span(&self) -> Span {
4503 Span::empty()
4504 }
4505}