1#[cfg(not(feature = "std"))]
20use alloc::{
21 boxed::Box,
22 format,
23 string::{String, ToString},
24 vec,
25 vec::Vec,
26};
27use helpers::{
28 attached_token::AttachedToken,
29 stmt_data_loading::{FileStagingCommand, StageLoadSelectItemKind},
30};
31
32use core::cmp::Ordering;
33use core::ops::{Deref, DerefMut};
34use core::{
35 fmt::{self, Display},
36 hash,
37};
38
39#[cfg(feature = "serde")]
40use serde::{Deserialize, Serialize};
41
42#[cfg(feature = "visitor")]
43use core::ops::ControlFlow;
44#[cfg(feature = "visitor")]
45use sqlparser_derive::{Visit, VisitMut};
46
47use crate::{
48 display_utils::SpaceOrNewline,
49 tokenizer::{Span, Token},
50};
51use crate::{
52 display_utils::{Indent, NewLine},
53 keywords::Keyword,
54};
55
56pub use self::data_type::{
57 ArrayElemTypeDef, BinaryLength, CharLengthUnits, CharacterLength, DataType, EnumMember,
58 ExactNumberInfo, IntervalFields, MapBracketKind, StructBracketKind, TimezoneInfo,
59};
60pub use self::dcl::{
61 AlterRoleOperation, CreateRole, Grant, ResetConfig, Revoke, RoleOption, SecondaryRoles,
62 SetConfigValue, Use,
63};
64pub use self::ddl::{
65 Alignment, AlterCollation, AlterCollationOperation, AlterColumnOperation, AlterConnectorOwner,
66 AlterFunction, AlterFunctionAction, AlterFunctionKind, AlterFunctionOperation,
67 AlterIndexOperation, AlterOperator, AlterOperatorClass, AlterOperatorClassOperation,
68 AlterOperatorFamily, AlterOperatorFamilyOperation, AlterOperatorOperation, AlterPolicy,
69 AlterPolicyOperation, AlterSchema, AlterSchemaOperation, AlterTable, AlterTableAlgorithm,
70 AlterTableLock, AlterTableOperation, AlterTableType, AlterTextSearch, AlterTextSearchOperation,
71 AlterTextSearchOption, AlterType, AlterTypeAddValue, AlterTypeAddValuePosition,
72 AlterTypeOperation, AlterTypeRename, AlterTypeRenameValue, ClusteredBy, ColumnDef,
73 ColumnOption, ColumnOptionDef, ColumnOptions, ColumnPolicy, ColumnPolicyProperty,
74 ConstraintCharacteristics, CreateCollation, CreateCollationDefinition, CreateConnector,
75 CreateDomain, CreateExtension, CreateForeignTable, CreateFunction, CreateIndex, CreateOperator,
76 CreateOperatorClass, CreateOperatorFamily, CreatePolicy, CreatePolicyCommand, CreatePolicyType,
77 CreateTable, CreateTextSearch, CreateTrigger, CreateView, Deduplicate, DeferrableInitial,
78 DistStyle, DropBehavior, DropExtension, DropFunction, DropOperator, DropOperatorClass,
79 DropOperatorFamily, DropOperatorSignature, DropPolicy, DropTrigger, ForValues,
80 FunctionReturnType, GeneratedAs, GeneratedExpressionMode, IdentityParameters, IdentityProperty,
81 IdentityPropertyFormatKind, IdentityPropertyKind, IdentityPropertyOrder, IndexColumn,
82 IndexOption, IndexType, KeyOrIndexDisplay, Msck, NullsDistinctOption, OperatorArgTypes,
83 OperatorClassItem, OperatorFamilyDropItem, OperatorFamilyItem, OperatorOption, OperatorPurpose,
84 Owner, Partition, PartitionBoundValue, ProcedureParam, ReferentialAction, RenameTableNameKind,
85 ReplicaIdentity, TagsColumnOption, TextSearchObjectType, TriggerObjectKind, Truncate,
86 UserDefinedTypeCompositeAttributeDef, UserDefinedTypeInternalLength,
87 UserDefinedTypeRangeOption, UserDefinedTypeRepresentation, UserDefinedTypeSqlDefinitionOption,
88 UserDefinedTypeStorage, ViewColumnDef, WithData,
89};
90pub use self::dml::{
91 Delete, Insert, Merge, MergeAction, MergeClause, MergeClauseKind, MergeInsertExpr,
92 MergeInsertKind, MergeUpdateExpr, MergeUpdateKind, MultiTableInsertIntoClause,
93 MultiTableInsertType, MultiTableInsertValue, MultiTableInsertValues,
94 MultiTableInsertWhenClause, OutputClause, Update,
95};
96pub use self::operator::{BinaryOperator, UnaryOperator};
97pub use self::procedural::{
98 DoStatement, PlPgSqlBlock, PlPgSqlDeclaration, PlPgSqlIfBranch, PlPgSqlStatement,
99};
100pub use self::query::{
101 AfterMatchSkip, ConnectByKind, Cte, CteAsMaterialized, Distinct, EmptyMatchesMode,
102 ExceptSelectItem, ExcludeSelectItem, ExprWithAlias, ExprWithAliasAndOrderBy, Fetch, ForClause,
103 ForJson, ForXml, FormatClause, GroupByExpr, GroupByWithModifier, IdentWithAlias,
104 IlikeSelectItem, InputFormatClause, Interpolate, InterpolateExpr, Join, JoinConstraint,
105 JoinOperator, JsonTableColumn, JsonTableColumnErrorHandling, JsonTableNamedColumn,
106 JsonTableNestedColumn, LateralView, LimitClause, LockClause, LockType, MatchRecognizePattern,
107 MatchRecognizeSymbol, Measure, NamedWindowDefinition, NamedWindowExpr, NonBlock, Offset,
108 OffsetRows, OpenJsonTableColumn, OrderBy, OrderByExpr, OrderByKind, OrderByOptions,
109 OrderBySort, PipeOperator, PivotValueSource, ProjectionSelect, Query, RenameSelectItem,
110 RepetitionQuantifier, ReplaceSelectElement, ReplaceSelectItem, RowsPerMatch, Select,
111 SelectFlavor, SelectInto, SelectItem, SelectItemQualifiedWildcardKind, SelectModifiers,
112 SetExpr, SetOperator, SetQuantifier, Setting, SymbolDefinition, Table, TableAlias,
113 TableAliasColumnDef, TableFactor, TableFunctionArgs, TableIndexHintForClause,
114 TableIndexHintType, TableIndexHints, TableIndexType, TableSample, TableSampleBucket,
115 TableSampleKind, TableSampleMethod, TableSampleModifier, TableSampleQuantity, TableSampleSeed,
116 TableSampleSeedModifier, TableSampleUnit, TableVersion, TableWithJoins, Top, TopQuantity,
117 UpdateTableFromKind, ValueTableMode, Values, WildcardAdditionalOptions, With, WithFill,
118 XmlNamespaceDefinition, XmlPassingArgument, XmlPassingClause, XmlTableColumn,
119 XmlTableColumnOption,
120};
121
122pub use self::trigger::{
123 TriggerEvent, TriggerExecBody, TriggerExecBodyType, TriggerObject, TriggerPeriod,
124 TriggerReferencing, TriggerReferencingType,
125};
126
127pub use self::value::{
128 escape_double_quote_string, escape_quoted_string, DateTimeField, DollarQuotedString,
129 NormalizationForm, QuoteDelimitedString, TrimWhereField, Value, ValueWithSpan,
130};
131
132use crate::ast::helpers::key_value_options::KeyValueOptions;
133use crate::ast::helpers::stmt_data_loading::StageParamsObject;
134
135#[cfg(feature = "visitor")]
136pub use visitor::*;
137
138pub use self::data_type::GeometricTypeKind;
139
140mod data_type;
141mod dcl;
142mod ddl;
143mod dml;
144pub mod helpers;
146pub mod table_constraints;
147pub use table_constraints::{
148 CheckConstraint, ConstraintUsingIndex, ExcludeConstraint, ExcludeConstraintElement,
149 ExcludeConstraintOperator, ForeignKeyConstraint, FullTextOrSpatialConstraint, IndexConstraint,
150 PrimaryKeyConstraint, TableConstraint, UniqueConstraint,
151};
152mod operator;
153mod procedural;
154mod query;
155mod spans;
156pub use spans::Spanned;
157
158pub mod comments;
159mod trigger;
160mod value;
161
162#[cfg(feature = "visitor")]
163mod visitor;
164
165pub struct DisplaySeparated<'a, T>
167where
168 T: fmt::Display,
169{
170 slice: &'a [T],
171 sep: &'static str,
172}
173
174impl<T> fmt::Display for DisplaySeparated<'_, T>
175where
176 T: fmt::Display,
177{
178 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
179 let mut delim = "";
180 for t in self.slice {
181 f.write_str(delim)?;
182 delim = self.sep;
183 t.fmt(f)?;
184 }
185 Ok(())
186 }
187}
188
189pub(crate) fn display_separated<'a, T>(slice: &'a [T], sep: &'static str) -> DisplaySeparated<'a, T>
190where
191 T: fmt::Display,
192{
193 DisplaySeparated { slice, sep }
194}
195
196pub(crate) fn display_comma_separated<T>(slice: &[T]) -> DisplaySeparated<'_, T>
197where
198 T: fmt::Display,
199{
200 DisplaySeparated { slice, sep: ", " }
201}
202
203fn format_statement_list(f: &mut fmt::Formatter, statements: &[Statement]) -> fmt::Result {
206 write!(f, "{}", display_separated(statements, "; "))?;
207 write!(f, ";")
210}
211
212#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
214#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
215#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
216pub struct Parens<T> {
217 pub opening_token: AttachedToken,
219 pub content: T,
221 pub closing_token: AttachedToken,
223}
224
225impl<T> Parens<T> {
226 pub fn with_empty_span(content: T) -> Self {
229 Self {
230 opening_token: AttachedToken::empty(),
231 content,
232 closing_token: AttachedToken::empty(),
233 }
234 }
235}
236
237impl<T> Deref for Parens<T> {
238 type Target = T;
239
240 fn deref(&self) -> &Self::Target {
241 &self.content
242 }
243}
244
245impl<T> DerefMut for Parens<T> {
246 fn deref_mut(&mut self) -> &mut Self::Target {
247 &mut self.content
248 }
249}
250
251#[derive(Debug, Clone)]
253#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
254pub struct Ident {
255 pub value: String,
257 pub quote_style: Option<char>,
260 pub span: Span,
262}
263
264impl PartialEq for Ident {
265 fn eq(&self, other: &Self) -> bool {
266 let Ident {
267 value,
268 quote_style,
269 span: _,
271 } = self;
272
273 value == &other.value && quote_style == &other.quote_style
274 }
275}
276
277impl core::hash::Hash for Ident {
278 fn hash<H: hash::Hasher>(&self, state: &mut H) {
279 let Ident {
280 value,
281 quote_style,
282 span: _,
284 } = self;
285
286 value.hash(state);
287 quote_style.hash(state);
288 }
289}
290
291impl Eq for Ident {}
292
293impl PartialOrd for Ident {
294 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
295 Some(self.cmp(other))
296 }
297}
298
299impl Ord for Ident {
300 fn cmp(&self, other: &Self) -> Ordering {
301 let Ident {
302 value,
303 quote_style,
304 span: _,
306 } = self;
307
308 let Ident {
309 value: other_value,
310 quote_style: other_quote_style,
311 span: _,
313 } = other;
314
315 value
317 .cmp(other_value)
318 .then_with(|| quote_style.cmp(other_quote_style))
319 }
320}
321
322impl Ident {
323 pub fn new<S>(value: S) -> Self
325 where
326 S: Into<String>,
327 {
328 Ident {
329 value: value.into(),
330 quote_style: None,
331 span: Span::empty(),
332 }
333 }
334
335 pub fn with_quote<S>(quote: char, value: S) -> Self
338 where
339 S: Into<String>,
340 {
341 assert!(quote == '\'' || quote == '"' || quote == '`' || quote == '[');
342 Ident {
343 value: value.into(),
344 quote_style: Some(quote),
345 span: Span::empty(),
346 }
347 }
348
349 pub fn with_span<S>(span: Span, value: S) -> Self
351 where
352 S: Into<String>,
353 {
354 Ident {
355 value: value.into(),
356 quote_style: None,
357 span,
358 }
359 }
360
361 pub fn with_quote_and_span<S>(quote: char, span: Span, value: S) -> Self
363 where
364 S: Into<String>,
365 {
366 assert!(quote == '\'' || quote == '"' || quote == '`' || quote == '[');
367 Ident {
368 value: value.into(),
369 quote_style: Some(quote),
370 span,
371 }
372 }
373}
374
375impl From<&str> for Ident {
376 fn from(value: &str) -> Self {
377 Ident {
378 value: value.to_string(),
379 quote_style: None,
380 span: Span::empty(),
381 }
382 }
383}
384
385pub(crate) fn fmt_ident(
386 f: &mut fmt::Formatter,
387 value: &str,
388 quote_style: Option<char>,
389) -> fmt::Result {
390 match quote_style {
391 Some('[') => write!(f, "[{value}]"),
392 Some(q) => {
393 let escaped = value::escape_quoted_string(value, q);
394 write!(f, "{q}{escaped}{q}")
395 }
396 None => f.write_str(value),
397 }
398}
399
400impl fmt::Display for Ident {
401 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
402 fmt_ident(f, &self.value, self.quote_style)
403 }
404}
405
406#[cfg(feature = "visitor")]
407impl Visit for Ident {
408 fn visit<V: Visitor>(&self, visitor: &mut V) -> ControlFlow<V::Break> {
409 visitor.pre_visit_ident(self)?;
410 visitor.post_visit_ident(self)
411 }
412}
413
414#[cfg(feature = "visitor")]
415impl VisitMut for Ident {
416 fn visit<V: VisitorMut>(&mut self, visitor: &mut V) -> ControlFlow<V::Break> {
417 visitor.pre_visit_ident(self)?;
418 visitor.post_visit_ident(self)
419 }
420}
421
422#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
424#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
425#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
426pub struct ObjectName(pub Vec<ObjectNamePart>);
427
428impl From<Vec<Ident>> for ObjectName {
429 fn from(idents: Vec<Ident>) -> Self {
430 ObjectName(idents.into_iter().map(ObjectNamePart::Identifier).collect())
431 }
432}
433
434impl From<Ident> for ObjectName {
435 fn from(ident: Ident) -> Self {
436 ObjectName(vec![ObjectNamePart::Identifier(ident)])
437 }
438}
439
440impl fmt::Display for ObjectName {
441 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
442 write!(f, "{}", display_separated(&self.0, "."))
443 }
444}
445
446#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
448#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
449#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
450pub enum ObjectNamePart {
451 Identifier(Ident),
453 Function(ObjectNamePartFunction),
455}
456
457impl ObjectNamePart {
458 pub fn as_ident(&self) -> Option<&Ident> {
460 match self {
461 ObjectNamePart::Identifier(ident) => Some(ident),
462 ObjectNamePart::Function(_) => None,
463 }
464 }
465}
466
467impl fmt::Display for ObjectNamePart {
468 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
469 match self {
470 ObjectNamePart::Identifier(ident) => write!(f, "{ident}"),
471 ObjectNamePart::Function(func) => write!(f, "{func}"),
472 }
473 }
474}
475
476#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
481#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
482#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
483pub struct ObjectNamePartFunction {
484 pub name: Ident,
486 pub args: Vec<FunctionArg>,
488}
489
490impl fmt::Display for ObjectNamePartFunction {
491 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
492 write!(f, "{}(", self.name)?;
493 write!(f, "{})", display_comma_separated(&self.args))
494 }
495}
496
497#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
500#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
501#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
502pub struct Array {
503 pub elem: Vec<Expr>,
505
506 pub named: bool,
508}
509
510impl fmt::Display for Array {
511 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
512 write!(
513 f,
514 "{}[{}]",
515 if self.named { "ARRAY" } else { "" },
516 display_comma_separated(&self.elem)
517 )
518 }
519}
520
521#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
530#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
531#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
532pub struct Interval {
533 pub value: Box<Expr>,
535 pub leading_field: Option<DateTimeField>,
537 pub leading_precision: Option<u64>,
539 pub last_field: Option<DateTimeField>,
541 pub fractional_seconds_precision: Option<u64>,
545}
546
547impl fmt::Display for Interval {
548 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
549 let value = self.value.as_ref();
550 match (
551 &self.leading_field,
552 self.leading_precision,
553 self.fractional_seconds_precision,
554 ) {
555 (
556 Some(DateTimeField::Second),
557 Some(leading_precision),
558 Some(fractional_seconds_precision),
559 ) => {
560 assert!(self.last_field.is_none());
563 write!(
564 f,
565 "INTERVAL {value} SECOND ({leading_precision}, {fractional_seconds_precision})"
566 )
567 }
568 _ => {
569 write!(f, "INTERVAL {value}")?;
570 if let Some(leading_field) = &self.leading_field {
571 write!(f, " {leading_field}")?;
572 }
573 if let Some(leading_precision) = self.leading_precision {
574 write!(f, " ({leading_precision})")?;
575 }
576 if let Some(last_field) = &self.last_field {
577 write!(f, " TO {last_field}")?;
578 }
579 if let Some(fractional_seconds_precision) = self.fractional_seconds_precision {
580 write!(f, " ({fractional_seconds_precision})")?;
581 }
582 Ok(())
583 }
584 }
585 }
586}
587
588#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
592#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
593#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
594pub struct StructField {
595 pub field_name: Option<Ident>,
597 pub field_type: DataType,
599 pub options: Option<Vec<SqlOption>>,
602}
603
604impl fmt::Display for StructField {
605 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
606 if let Some(name) = &self.field_name {
607 write!(f, "{name} {}", self.field_type)?;
608 } else {
609 write!(f, "{}", self.field_type)?;
610 }
611 if let Some(options) = &self.options {
612 write!(f, " OPTIONS({})", display_separated(options, ", "))
613 } else {
614 Ok(())
615 }
616 }
617}
618
619#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
623#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
624#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
625pub struct UnionField {
626 pub field_name: Ident,
628 pub field_type: DataType,
630}
631
632impl fmt::Display for UnionField {
633 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
634 write!(f, "{} {}", self.field_name, self.field_type)
635 }
636}
637
638#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
642#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
643#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
644pub struct DictionaryField {
645 pub key: Ident,
647 pub value: Box<Expr>,
649}
650
651impl fmt::Display for DictionaryField {
652 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
653 write!(f, "{}: {}", self.key, self.value)
654 }
655}
656
657#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
659#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
660#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
661pub struct Map {
662 pub entries: Vec<MapEntry>,
664}
665
666impl Display for Map {
667 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
668 write!(f, "MAP {{{}}}", display_comma_separated(&self.entries))
669 }
670}
671
672#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
676#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
677#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
678pub struct MapEntry {
679 pub key: Box<Expr>,
681 pub value: Box<Expr>,
683}
684
685impl fmt::Display for MapEntry {
686 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
687 write!(f, "{}: {}", self.key, self.value)
688 }
689}
690
691#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
694#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
695#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
696pub enum CastFormat {
697 Value(ValueWithSpan),
699 ValueAtTimeZone(ValueWithSpan, ValueWithSpan),
701}
702
703#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
705#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
706#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
707pub enum JsonPathElem {
708 Dot {
712 key: String,
714 quoted: bool,
716 },
717 Bracket {
722 key: Expr,
724 },
725 ColonBracket {
730 key: Expr,
732 },
733}
734
735#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
740#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
741#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
742pub struct JsonPath {
743 pub path: Vec<JsonPathElem>,
745}
746
747impl fmt::Display for JsonPath {
748 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
749 for (i, elem) in self.path.iter().enumerate() {
750 match elem {
751 JsonPathElem::Dot { key, quoted } => {
752 if i == 0 {
753 write!(f, ":")?;
754 } else {
755 write!(f, ".")?;
756 }
757
758 if *quoted {
759 write!(f, "\"{}\"", escape_double_quote_string(key))?;
760 } else {
761 write!(f, "{key}")?;
762 }
763 }
764 JsonPathElem::Bracket { key } => {
765 write!(f, "[{key}]")?;
766 }
767 JsonPathElem::ColonBracket { key } => {
768 write!(f, ":[{key}]")?;
769 }
770 }
771 }
772 Ok(())
773 }
774}
775
776#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
778#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
779#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
780pub enum CastKind {
781 Cast,
783 TryCast,
788 SafeCast,
792 DoubleColon,
794}
795
796#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
800#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
801#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
802pub enum ConstraintReferenceMatchKind {
803 Full,
805 Partial,
807 Simple,
809}
810
811impl fmt::Display for ConstraintReferenceMatchKind {
812 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
813 match self {
814 Self::Full => write!(f, "MATCH FULL"),
815 Self::Partial => write!(f, "MATCH PARTIAL"),
816 Self::Simple => write!(f, "MATCH SIMPLE"),
817 }
818 }
819}
820
821#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
828#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
829#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
830pub enum ExtractSyntax {
831 From,
833 Comma,
835}
836
837#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
846#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
847#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
848pub enum CeilFloorKind {
849 DateTimeField(DateTimeField),
851 Scale(ValueWithSpan),
853}
854
855#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
858#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
859#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
860pub struct CaseWhen {
861 pub condition: Expr,
863 pub result: Expr,
865}
866
867impl fmt::Display for CaseWhen {
868 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
869 f.write_str("WHEN ")?;
870 self.condition.fmt(f)?;
871 f.write_str(" THEN")?;
872 SpaceOrNewline.fmt(f)?;
873 Indent(&self.result).fmt(f)?;
874 Ok(())
875 }
876}
877
878#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
896#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
897#[cfg_attr(
898 feature = "visitor",
899 derive(Visit, VisitMut),
900 visit(with = "visit_expr")
901)]
902pub enum Expr {
903 Identifier(Ident),
905 CompoundIdentifier(Vec<Ident>),
907 CompoundFieldAccess {
926 root: Box<Expr>,
928 access_chain: Vec<AccessExpr>,
930 },
931 JsonAccess {
937 value: Box<Expr>,
939 path: JsonPath,
941 },
942 IsFalse(Box<Expr>),
944 IsNotFalse(Box<Expr>),
946 IsTrue(Box<Expr>),
948 IsNotTrue(Box<Expr>),
950 IsNull(Box<Expr>),
952 IsNotNull(Box<Expr>),
954 IsUnknown(Box<Expr>),
956 IsNotUnknown(Box<Expr>),
958 IsDistinctFrom(Box<Expr>, Box<Expr>),
960 IsNotDistinctFrom(Box<Expr>, Box<Expr>),
962 IsJson {
964 expr: Box<Expr>,
966 kind: Option<JsonPredicateType>,
968 unique_keys: Option<JsonKeyUniqueness>,
970 negated: bool,
972 },
973 IsNormalized {
975 expr: Box<Expr>,
977 form: Option<NormalizationForm>,
979 negated: bool,
981 },
982 InList {
984 expr: Box<Expr>,
986 list: Vec<Expr>,
988 negated: bool,
990 },
991 InSubquery {
993 expr: Box<Expr>,
995 subquery: Box<Query>,
997 negated: bool,
999 },
1000 InUnnest {
1002 expr: Box<Expr>,
1004 array_expr: Box<Expr>,
1006 negated: bool,
1008 },
1009 Between {
1011 expr: Box<Expr>,
1013 negated: bool,
1015 low: Box<Expr>,
1017 high: Box<Expr>,
1019 },
1020 BinaryOp {
1022 left: Box<Expr>,
1024 op: BinaryOperator,
1026 right: Box<Expr>,
1028 },
1029 Like {
1031 negated: bool,
1033 any: bool,
1036 expr: Box<Expr>,
1038 pattern: Box<Expr>,
1040 escape_char: Option<Box<Expr>>,
1042 },
1043 ILike {
1045 negated: bool,
1047 any: bool,
1050 expr: Box<Expr>,
1052 pattern: Box<Expr>,
1054 escape_char: Option<Box<Expr>>,
1056 },
1057 SimilarTo {
1059 negated: bool,
1061 expr: Box<Expr>,
1063 pattern: Box<Expr>,
1065 escape_char: Option<Box<Expr>>,
1067 },
1068 RLike {
1070 negated: bool,
1072 expr: Box<Expr>,
1074 pattern: Box<Expr>,
1076 regexp: bool,
1078 },
1079 AnyOp {
1082 left: Box<Expr>,
1084 compare_op: BinaryOperator,
1086 right: Box<Expr>,
1088 is_some: bool,
1090 },
1091 AllOp {
1094 left: Box<Expr>,
1096 compare_op: BinaryOperator,
1098 right: Box<Expr>,
1100 },
1101
1102 UnaryOp {
1104 op: UnaryOperator,
1106 expr: Box<Expr>,
1108 },
1109 Convert {
1111 is_try: bool,
1114 expr: Box<Expr>,
1116 data_type: Option<DataType>,
1118 charset: Option<ObjectName>,
1120 target_before_value: bool,
1122 styles: Vec<Expr>,
1126 },
1127 Cast {
1129 kind: CastKind,
1131 expr: Box<Expr>,
1133 data_type: DataType,
1135 format: Option<CastFormat>,
1139 },
1140 AtTimeZone {
1142 timestamp: Box<Expr>,
1144 time_zone: Box<Expr>,
1146 },
1147 Extract {
1155 field: DateTimeField,
1157 syntax: ExtractSyntax,
1159 expr: Box<Expr>,
1161 },
1162 Ceil {
1169 expr: Box<Expr>,
1171 field: CeilFloorKind,
1173 },
1174 Floor {
1181 expr: Box<Expr>,
1183 field: CeilFloorKind,
1185 },
1186 Position {
1190 expr: Box<Expr>,
1192 r#in: Box<Expr>,
1194 },
1195 Substring {
1203 expr: Box<Expr>,
1205 substring_from: Option<Box<Expr>>,
1207 substring_for: Option<Box<Expr>>,
1209
1210 special: bool,
1214
1215 shorthand: bool,
1218 },
1219 Trim {
1225 trim_where: Option<TrimWhereField>,
1227 trim_what: Option<Box<Expr>>,
1229 expr: Box<Expr>,
1231 trim_characters: Option<Vec<Expr>>,
1233 },
1234 Overlay {
1238 expr: Box<Expr>,
1240 overlay_what: Box<Expr>,
1242 overlay_from: Box<Expr>,
1244 overlay_for: Option<Box<Expr>>,
1246 },
1247 Collate {
1249 expr: Box<Expr>,
1251 collation: ObjectName,
1253 },
1254 Nested(Box<Expr>),
1256 Value(ValueWithSpan),
1258 Prefixed {
1262 prefix: Ident,
1264 value: Box<Expr>,
1267 },
1268 TypedString(TypedString),
1272 Function(Function),
1274 Case {
1280 case_token: AttachedToken,
1282 end_token: AttachedToken,
1284 operand: Option<Box<Expr>>,
1286 conditions: Vec<CaseWhen>,
1288 else_result: Option<Box<Expr>>,
1290 },
1291 Exists {
1294 subquery: Box<Query>,
1296 negated: bool,
1298 },
1299 Subquery(Box<Query>),
1302 GroupingSets(Vec<Vec<Expr>>),
1304 Cube(Vec<Vec<Expr>>),
1306 Rollup(Vec<Vec<Expr>>),
1308 Tuple(Vec<Expr>),
1310 Struct {
1319 values: Vec<Expr>,
1321 fields: Vec<StructField>,
1323 },
1324 Named {
1331 expr: Box<Expr>,
1333 name: Ident,
1335 },
1336 Dictionary(Vec<DictionaryField>),
1344 Map(Map),
1352 Array(Array),
1354 Interval(Interval),
1356 MatchAgainst {
1367 columns: Vec<ObjectName>,
1369 match_value: ValueWithSpan,
1371 opt_search_modifier: Option<SearchModifier>,
1373 },
1374 Wildcard(AttachedToken),
1376 QualifiedWildcard(ObjectName, AttachedToken),
1379 OuterJoin(Box<Expr>),
1394 Prior(Box<Expr>),
1396 Lambda(LambdaFunction),
1407 MemberOf(MemberOf),
1409}
1410
1411impl Expr {
1412 pub fn value(value: impl Into<ValueWithSpan>) -> Self {
1414 Expr::Value(value.into())
1415 }
1416}
1417
1418#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1420#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1421#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1422pub enum Subscript {
1423 Index {
1425 index: Expr,
1427 },
1428
1429 Slice {
1451 lower_bound: Option<Expr>,
1453 upper_bound: Option<Expr>,
1455 stride: Option<Expr>,
1457 },
1458}
1459
1460impl fmt::Display for Subscript {
1461 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1462 match self {
1463 Subscript::Index { index } => write!(f, "{index}"),
1464 Subscript::Slice {
1465 lower_bound,
1466 upper_bound,
1467 stride,
1468 } => {
1469 if let Some(lower) = lower_bound {
1470 write!(f, "{lower}")?;
1471 }
1472 write!(f, ":")?;
1473 if let Some(upper) = upper_bound {
1474 write!(f, "{upper}")?;
1475 }
1476 if let Some(stride) = stride {
1477 write!(f, ":")?;
1478 write!(f, "{stride}")?;
1479 }
1480 Ok(())
1481 }
1482 }
1483 }
1484}
1485
1486#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1489#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1490#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1491pub enum AccessExpr {
1492 Dot(Expr),
1494 Subscript(Subscript),
1496}
1497
1498const fn is_number_expr(expr: &Expr) -> bool {
1499 matches!(expr, Expr::Value(v) if matches!(v.value, Value::Number(_, _)))
1500}
1501
1502impl fmt::Display for AccessExpr {
1503 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1504 match self {
1505 AccessExpr::Dot(expr) if is_number_expr(expr) => write!(f, " . {expr}"),
1506 AccessExpr::Dot(expr) => write!(f, ".{expr}"),
1507 AccessExpr::Subscript(subscript) => write!(f, "[{subscript}]"),
1508 }
1509 }
1510}
1511
1512#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1514#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1515#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1516pub struct LambdaFunction {
1517 pub params: OneOrManyWithParens<LambdaFunctionParameter>,
1519 pub body: Box<Expr>,
1521 pub syntax: LambdaSyntax,
1523}
1524
1525impl fmt::Display for LambdaFunction {
1526 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1527 match self.syntax {
1528 LambdaSyntax::Arrow => write!(f, "{} -> {}", self.params, self.body),
1529 LambdaSyntax::LambdaKeyword => {
1530 write!(f, "lambda ")?;
1533 match &self.params {
1534 OneOrManyWithParens::One(p) => write!(f, "{p}")?,
1535 OneOrManyWithParens::Many(ps) => write!(f, "{}", display_comma_separated(ps))?,
1536 };
1537 write!(f, " : {}", self.body)
1538 }
1539 }
1540 }
1541}
1542
1543#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1545#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1546#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1547pub struct LambdaFunctionParameter {
1548 pub name: Ident,
1550 pub data_type: Option<DataType>,
1553}
1554
1555impl fmt::Display for LambdaFunctionParameter {
1556 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1557 match &self.data_type {
1558 Some(dt) => write!(f, "{} {}", self.name, dt),
1559 None => write!(f, "{}", self.name),
1560 }
1561 }
1562}
1563
1564#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Copy)]
1566#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1567#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1568pub enum LambdaSyntax {
1569 Arrow,
1576 LambdaKeyword,
1581}
1582
1583#[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 OneOrManyWithParens<T> {
1609 One(T),
1611 Many(Vec<T>),
1613}
1614
1615impl<T> Deref for OneOrManyWithParens<T> {
1616 type Target = [T];
1617
1618 fn deref(&self) -> &[T] {
1619 match self {
1620 OneOrManyWithParens::One(one) => core::slice::from_ref(one),
1621 OneOrManyWithParens::Many(many) => many,
1622 }
1623 }
1624}
1625
1626impl<T> AsRef<[T]> for OneOrManyWithParens<T> {
1627 fn as_ref(&self) -> &[T] {
1628 self
1629 }
1630}
1631
1632impl<'a, T> IntoIterator for &'a OneOrManyWithParens<T> {
1633 type Item = &'a T;
1634 type IntoIter = core::slice::Iter<'a, T>;
1635
1636 fn into_iter(self) -> Self::IntoIter {
1637 self.iter()
1638 }
1639}
1640
1641#[derive(Debug, Clone)]
1643pub struct OneOrManyWithParensIntoIter<T> {
1644 inner: OneOrManyWithParensIntoIterInner<T>,
1645}
1646
1647#[derive(Debug, Clone)]
1648enum OneOrManyWithParensIntoIterInner<T> {
1649 One(core::iter::Once<T>),
1650 Many(<Vec<T> as IntoIterator>::IntoIter),
1651}
1652
1653impl<T> core::iter::FusedIterator for OneOrManyWithParensIntoIter<T>
1654where
1655 core::iter::Once<T>: core::iter::FusedIterator,
1656 <Vec<T> as IntoIterator>::IntoIter: core::iter::FusedIterator,
1657{
1658}
1659
1660impl<T> core::iter::ExactSizeIterator for OneOrManyWithParensIntoIter<T>
1661where
1662 core::iter::Once<T>: core::iter::ExactSizeIterator,
1663 <Vec<T> as IntoIterator>::IntoIter: core::iter::ExactSizeIterator,
1664{
1665}
1666
1667impl<T> core::iter::Iterator for OneOrManyWithParensIntoIter<T> {
1668 type Item = T;
1669
1670 fn next(&mut self) -> Option<Self::Item> {
1671 match &mut self.inner {
1672 OneOrManyWithParensIntoIterInner::One(one) => one.next(),
1673 OneOrManyWithParensIntoIterInner::Many(many) => many.next(),
1674 }
1675 }
1676
1677 fn size_hint(&self) -> (usize, Option<usize>) {
1678 match &self.inner {
1679 OneOrManyWithParensIntoIterInner::One(one) => one.size_hint(),
1680 OneOrManyWithParensIntoIterInner::Many(many) => many.size_hint(),
1681 }
1682 }
1683
1684 fn count(self) -> usize
1685 where
1686 Self: Sized,
1687 {
1688 match self.inner {
1689 OneOrManyWithParensIntoIterInner::One(one) => one.count(),
1690 OneOrManyWithParensIntoIterInner::Many(many) => many.count(),
1691 }
1692 }
1693
1694 fn fold<B, F>(mut self, init: B, f: F) -> B
1695 where
1696 Self: Sized,
1697 F: FnMut(B, Self::Item) -> B,
1698 {
1699 match &mut self.inner {
1700 OneOrManyWithParensIntoIterInner::One(one) => one.fold(init, f),
1701 OneOrManyWithParensIntoIterInner::Many(many) => many.fold(init, f),
1702 }
1703 }
1704}
1705
1706impl<T> core::iter::DoubleEndedIterator for OneOrManyWithParensIntoIter<T> {
1707 fn next_back(&mut self) -> Option<Self::Item> {
1708 match &mut self.inner {
1709 OneOrManyWithParensIntoIterInner::One(one) => one.next_back(),
1710 OneOrManyWithParensIntoIterInner::Many(many) => many.next_back(),
1711 }
1712 }
1713}
1714
1715impl<T> IntoIterator for OneOrManyWithParens<T> {
1716 type Item = T;
1717
1718 type IntoIter = OneOrManyWithParensIntoIter<T>;
1719
1720 fn into_iter(self) -> Self::IntoIter {
1721 let inner = match self {
1722 OneOrManyWithParens::One(one) => {
1723 OneOrManyWithParensIntoIterInner::One(core::iter::once(one))
1724 }
1725 OneOrManyWithParens::Many(many) => {
1726 OneOrManyWithParensIntoIterInner::Many(many.into_iter())
1727 }
1728 };
1729
1730 OneOrManyWithParensIntoIter { inner }
1731 }
1732}
1733
1734impl<T> fmt::Display for OneOrManyWithParens<T>
1735where
1736 T: fmt::Display,
1737{
1738 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1739 match self {
1740 OneOrManyWithParens::One(value) => write!(f, "{value}"),
1741 OneOrManyWithParens::Many(values) => {
1742 write!(f, "({})", display_comma_separated(values))
1743 }
1744 }
1745 }
1746}
1747
1748impl fmt::Display for CastFormat {
1749 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1750 match self {
1751 CastFormat::Value(v) => write!(f, "{v}"),
1752 CastFormat::ValueAtTimeZone(v, tz) => write!(f, "{v} AT TIME ZONE {tz}"),
1753 }
1754 }
1755}
1756
1757impl fmt::Display for Expr {
1758 #[cfg_attr(feature = "recursive-protection", recursive::recursive)]
1759 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1760 match self {
1761 Expr::Identifier(s) => write!(f, "{s}"),
1762 Expr::Wildcard(_) => f.write_str("*"),
1763 Expr::QualifiedWildcard(prefix, _) => write!(f, "{prefix}.*"),
1764 Expr::CompoundIdentifier(s) => write!(f, "{}", display_separated(s, ".")),
1765 Expr::CompoundFieldAccess { root, access_chain } => {
1766 write!(f, "{root}")?;
1767 let mut prev_is_number = is_number_expr(root);
1768 for field in access_chain {
1769 match field {
1770 AccessExpr::Dot(expr) if prev_is_number => write!(f, " . {expr}")?,
1771 _ => write!(f, "{field}")?,
1772 }
1773 prev_is_number = matches!(field, AccessExpr::Dot(expr) if is_number_expr(expr));
1774 }
1775 Ok(())
1776 }
1777 Expr::IsTrue(ast) => write!(f, "{ast} IS TRUE"),
1778 Expr::IsNotTrue(ast) => write!(f, "{ast} IS NOT TRUE"),
1779 Expr::IsFalse(ast) => write!(f, "{ast} IS FALSE"),
1780 Expr::IsNotFalse(ast) => write!(f, "{ast} IS NOT FALSE"),
1781 Expr::IsNull(ast) => write!(f, "{ast} IS NULL"),
1782 Expr::IsNotNull(ast) => write!(f, "{ast} IS NOT NULL"),
1783 Expr::IsUnknown(ast) => write!(f, "{ast} IS UNKNOWN"),
1784 Expr::IsNotUnknown(ast) => write!(f, "{ast} IS NOT UNKNOWN"),
1785 Expr::IsJson {
1786 expr,
1787 kind,
1788 unique_keys,
1789 negated,
1790 } => {
1791 write!(f, "{expr} IS ")?;
1792 if *negated {
1793 write!(f, "NOT ")?;
1794 }
1795 write!(f, "JSON")?;
1796 if let Some(kind) = kind {
1797 write!(f, " {kind}")?;
1798 }
1799 if let Some(unique_keys) = unique_keys {
1800 write!(f, " {unique_keys}")?;
1801 }
1802 Ok(())
1803 }
1804 Expr::InList {
1805 expr,
1806 list,
1807 negated,
1808 } => write!(
1809 f,
1810 "{} {}IN ({})",
1811 expr,
1812 if *negated { "NOT " } else { "" },
1813 display_comma_separated(list)
1814 ),
1815 Expr::InSubquery {
1816 expr,
1817 subquery,
1818 negated,
1819 } => write!(
1820 f,
1821 "{} {}IN ({})",
1822 expr,
1823 if *negated { "NOT " } else { "" },
1824 subquery
1825 ),
1826 Expr::InUnnest {
1827 expr,
1828 array_expr,
1829 negated,
1830 } => write!(
1831 f,
1832 "{} {}IN UNNEST({})",
1833 expr,
1834 if *negated { "NOT " } else { "" },
1835 array_expr
1836 ),
1837 Expr::Between {
1838 expr,
1839 negated,
1840 low,
1841 high,
1842 } => write!(
1843 f,
1844 "{} {}BETWEEN {} AND {}",
1845 expr,
1846 if *negated { "NOT " } else { "" },
1847 low,
1848 high
1849 ),
1850 Expr::BinaryOp { left, op, right } => write!(f, "{left} {op} {right}"),
1851 Expr::Like {
1852 negated,
1853 expr,
1854 pattern,
1855 escape_char,
1856 any,
1857 } => match escape_char {
1858 Some(ch) => write!(
1859 f,
1860 "{} {}LIKE {}{} ESCAPE {}",
1861 expr,
1862 if *negated { "NOT " } else { "" },
1863 if *any { "ANY " } else { "" },
1864 pattern,
1865 ch
1866 ),
1867 _ => write!(
1868 f,
1869 "{} {}LIKE {}{}",
1870 expr,
1871 if *negated { "NOT " } else { "" },
1872 if *any { "ANY " } else { "" },
1873 pattern
1874 ),
1875 },
1876 Expr::ILike {
1877 negated,
1878 expr,
1879 pattern,
1880 escape_char,
1881 any,
1882 } => match escape_char {
1883 Some(ch) => write!(
1884 f,
1885 "{} {}ILIKE {}{} ESCAPE {}",
1886 expr,
1887 if *negated { "NOT " } else { "" },
1888 if *any { "ANY" } else { "" },
1889 pattern,
1890 ch
1891 ),
1892 _ => write!(
1893 f,
1894 "{} {}ILIKE {}{}",
1895 expr,
1896 if *negated { "NOT " } else { "" },
1897 if *any { "ANY " } else { "" },
1898 pattern
1899 ),
1900 },
1901 Expr::RLike {
1902 negated,
1903 expr,
1904 pattern,
1905 regexp,
1906 } => write!(
1907 f,
1908 "{} {}{} {}",
1909 expr,
1910 if *negated { "NOT " } else { "" },
1911 if *regexp { "REGEXP" } else { "RLIKE" },
1912 pattern
1913 ),
1914 Expr::IsNormalized {
1915 expr,
1916 form,
1917 negated,
1918 } => {
1919 let not_ = if *negated { "NOT " } else { "" };
1920 if let Some(form) = form {
1921 write!(f, "{} IS {}{} NORMALIZED", expr, not_, form)
1922 } else {
1923 write!(f, "{expr} IS {not_}NORMALIZED")
1924 }
1925 }
1926 Expr::SimilarTo {
1927 negated,
1928 expr,
1929 pattern,
1930 escape_char,
1931 } => match escape_char {
1932 Some(ch) => write!(
1933 f,
1934 "{} {}SIMILAR TO {} ESCAPE {}",
1935 expr,
1936 if *negated { "NOT " } else { "" },
1937 pattern,
1938 ch
1939 ),
1940 _ => write!(
1941 f,
1942 "{} {}SIMILAR TO {}",
1943 expr,
1944 if *negated { "NOT " } else { "" },
1945 pattern
1946 ),
1947 },
1948 Expr::AnyOp {
1949 left,
1950 compare_op,
1951 right,
1952 is_some,
1953 } => {
1954 let add_parens = !matches!(right.as_ref(), Expr::Subquery(_));
1955 write!(
1956 f,
1957 "{left} {compare_op} {}{}{right}{}",
1958 if *is_some { "SOME" } else { "ANY" },
1959 if add_parens { "(" } else { "" },
1960 if add_parens { ")" } else { "" },
1961 )
1962 }
1963 Expr::AllOp {
1964 left,
1965 compare_op,
1966 right,
1967 } => {
1968 let add_parens = !matches!(right.as_ref(), Expr::Subquery(_));
1969 write!(
1970 f,
1971 "{left} {compare_op} ALL{}{right}{}",
1972 if add_parens { "(" } else { "" },
1973 if add_parens { ")" } else { "" },
1974 )
1975 }
1976 Expr::UnaryOp { op, expr } => match op {
1977 UnaryOperator::PGPostfixFactorial => {
1978 if matches!(
1979 expr.as_ref(),
1980 Expr::UnaryOp {
1981 op: UnaryOperator::PGPostfixFactorial,
1982 ..
1983 }
1984 ) {
1985 write!(f, "{expr} {op}")
1986 } else {
1987 write!(f, "{expr}{op}")
1988 }
1989 }
1990 UnaryOperator::Not
1991 | UnaryOperator::BitwiseNot
1992 | UnaryOperator::Hash
1993 | UnaryOperator::AtDashAt
1994 | UnaryOperator::DoubleAt
1995 | UnaryOperator::PGAbs
1996 | UnaryOperator::QuestionDash
1997 | UnaryOperator::QuestionPipe
1998 | UnaryOperator::PGSquareRoot
1999 | UnaryOperator::PGCubeRoot => write!(f, "{op} {expr}"),
2000 UnaryOperator::Minus | UnaryOperator::BangNot => {
2001 if starts_with_operator_char(expr) {
2002 write!(f, "{op} {expr}")
2003 } else {
2004 write!(f, "{op}{expr}")
2005 }
2006 }
2007 UnaryOperator::Plus | UnaryOperator::PGPrefixFactorial => write!(f, "{op}{expr}"),
2008 },
2009 Expr::Convert {
2010 is_try,
2011 expr,
2012 target_before_value,
2013 data_type,
2014 charset,
2015 styles,
2016 } => {
2017 write!(f, "{}CONVERT(", if *is_try { "TRY_" } else { "" })?;
2018 if let Some(data_type) = data_type {
2019 if let Some(charset) = charset {
2020 write!(f, "{expr}, {data_type} CHARACTER SET {charset}")
2021 } else if *target_before_value {
2022 write!(f, "{data_type}, {expr}")
2023 } else {
2024 write!(f, "{expr}, {data_type}")
2025 }
2026 } else if let Some(charset) = charset {
2027 write!(f, "{expr} USING {charset}")
2028 } else {
2029 write!(f, "{expr}") }?;
2031 if !styles.is_empty() {
2032 write!(f, ", {}", display_comma_separated(styles))?;
2033 }
2034 write!(f, ")")
2035 }
2036 Expr::Cast {
2037 kind,
2038 expr,
2039 data_type,
2040 format,
2041 } => match kind {
2042 CastKind::Cast => {
2043 if matches!(data_type, DataType::Unspecified) {
2044 write!(f, "CAST({expr} AS")?;
2045 } else {
2046 write!(f, "CAST({expr} AS {data_type}")?;
2047 }
2048 if let Some(format) = format {
2049 write!(f, " FORMAT {format}")?;
2050 }
2051 write!(f, ")")
2052 }
2053 CastKind::TryCast => {
2054 if let Some(format) = format {
2055 write!(f, "TRY_CAST({expr} AS {data_type} FORMAT {format})")
2056 } else {
2057 write!(f, "TRY_CAST({expr} AS {data_type})")
2058 }
2059 }
2060 CastKind::SafeCast => {
2061 if let Some(format) = format {
2062 write!(f, "SAFE_CAST({expr} AS {data_type} FORMAT {format})")
2063 } else {
2064 write!(f, "SAFE_CAST({expr} AS {data_type})")
2065 }
2066 }
2067 CastKind::DoubleColon => {
2068 write!(f, "{expr}::{data_type}")
2069 }
2070 },
2071 Expr::Extract {
2072 field,
2073 syntax,
2074 expr,
2075 } => match syntax {
2076 ExtractSyntax::From => write!(f, "EXTRACT({field} FROM {expr})"),
2077 ExtractSyntax::Comma => write!(f, "EXTRACT({field}, {expr})"),
2078 },
2079 Expr::Ceil { expr, field } => match field {
2080 CeilFloorKind::DateTimeField(DateTimeField::NoDateTime) => {
2081 write!(f, "CEIL({expr})")
2082 }
2083 CeilFloorKind::DateTimeField(dt_field) => write!(f, "CEIL({expr} TO {dt_field})"),
2084 CeilFloorKind::Scale(s) => write!(f, "CEIL({expr}, {s})"),
2085 },
2086 Expr::Floor { expr, field } => match field {
2087 CeilFloorKind::DateTimeField(DateTimeField::NoDateTime) => {
2088 write!(f, "FLOOR({expr})")
2089 }
2090 CeilFloorKind::DateTimeField(dt_field) => write!(f, "FLOOR({expr} TO {dt_field})"),
2091 CeilFloorKind::Scale(s) => write!(f, "FLOOR({expr}, {s})"),
2092 },
2093 Expr::Position { expr, r#in } => write!(f, "POSITION({expr} IN {in})"),
2094 Expr::Collate { expr, collation } => write!(f, "{expr} COLLATE {collation}"),
2095 Expr::Nested(ast) => write!(f, "({ast})"),
2096 Expr::Value(v) => write!(f, "{v}"),
2097 Expr::Prefixed { prefix, value } => write!(f, "{prefix} {value}"),
2098 Expr::TypedString(ts) => ts.fmt(f),
2099 Expr::Function(fun) => fun.fmt(f),
2100 Expr::Case {
2101 case_token: _,
2102 end_token: _,
2103 operand,
2104 conditions,
2105 else_result,
2106 } => {
2107 f.write_str("CASE")?;
2108 if let Some(operand) = operand {
2109 f.write_str(" ")?;
2110 operand.fmt(f)?;
2111 }
2112 for when in conditions {
2113 SpaceOrNewline.fmt(f)?;
2114 Indent(when).fmt(f)?;
2115 }
2116 if let Some(else_result) = else_result {
2117 SpaceOrNewline.fmt(f)?;
2118 Indent("ELSE").fmt(f)?;
2119 SpaceOrNewline.fmt(f)?;
2120 Indent(Indent(else_result)).fmt(f)?;
2121 }
2122 SpaceOrNewline.fmt(f)?;
2123 f.write_str("END")
2124 }
2125 Expr::Exists { subquery, negated } => write!(
2126 f,
2127 "{}EXISTS ({})",
2128 if *negated { "NOT " } else { "" },
2129 subquery
2130 ),
2131 Expr::Subquery(s) => write!(f, "({s})"),
2132 Expr::GroupingSets(sets) => {
2133 write!(f, "GROUPING SETS (")?;
2134 let mut sep = "";
2135 for set in sets {
2136 write!(f, "{sep}")?;
2137 sep = ", ";
2138 write!(f, "({})", display_comma_separated(set))?;
2139 }
2140 write!(f, ")")
2141 }
2142 Expr::Cube(sets) => {
2143 write!(f, "CUBE (")?;
2144 let mut sep = "";
2145 for set in sets {
2146 write!(f, "{sep}")?;
2147 sep = ", ";
2148 if set.len() == 1 {
2149 write!(f, "{}", set[0])?;
2150 } else {
2151 write!(f, "({})", display_comma_separated(set))?;
2152 }
2153 }
2154 write!(f, ")")
2155 }
2156 Expr::Rollup(sets) => {
2157 write!(f, "ROLLUP (")?;
2158 let mut sep = "";
2159 for set in sets {
2160 write!(f, "{sep}")?;
2161 sep = ", ";
2162 if set.len() == 1 {
2163 write!(f, "{}", set[0])?;
2164 } else {
2165 write!(f, "({})", display_comma_separated(set))?;
2166 }
2167 }
2168 write!(f, ")")
2169 }
2170 Expr::Substring {
2171 expr,
2172 substring_from,
2173 substring_for,
2174 special,
2175 shorthand,
2176 } => {
2177 f.write_str("SUBSTR")?;
2178 if !*shorthand {
2179 f.write_str("ING")?;
2180 }
2181 write!(f, "({expr}")?;
2182 if let Some(from_part) = substring_from {
2183 if *special {
2184 write!(f, ", {from_part}")?;
2185 } else {
2186 write!(f, " FROM {from_part}")?;
2187 }
2188 }
2189 if let Some(for_part) = substring_for {
2190 if *special {
2191 write!(f, ", {for_part}")?;
2192 } else {
2193 write!(f, " FOR {for_part}")?;
2194 }
2195 }
2196
2197 write!(f, ")")
2198 }
2199 Expr::Overlay {
2200 expr,
2201 overlay_what,
2202 overlay_from,
2203 overlay_for,
2204 } => {
2205 write!(
2206 f,
2207 "OVERLAY({expr} PLACING {overlay_what} FROM {overlay_from}"
2208 )?;
2209 if let Some(for_part) = overlay_for {
2210 write!(f, " FOR {for_part}")?;
2211 }
2212
2213 write!(f, ")")
2214 }
2215 Expr::IsDistinctFrom(a, b) => write!(f, "{a} IS DISTINCT FROM {b}"),
2216 Expr::IsNotDistinctFrom(a, b) => write!(f, "{a} IS NOT DISTINCT FROM {b}"),
2217 Expr::Trim {
2218 expr,
2219 trim_where,
2220 trim_what,
2221 trim_characters,
2222 } => {
2223 write!(f, "TRIM(")?;
2224 if let Some(ident) = trim_where {
2225 write!(f, "{ident} ")?;
2226 }
2227 if let Some(trim_char) = trim_what {
2228 write!(f, "{trim_char} FROM {expr}")?;
2229 } else {
2230 write!(f, "{expr}")?;
2231 }
2232 if let Some(characters) = trim_characters {
2233 write!(f, ", {}", display_comma_separated(characters))?;
2234 }
2235
2236 write!(f, ")")
2237 }
2238 Expr::Tuple(exprs) => {
2239 write!(f, "({})", display_comma_separated(exprs))
2240 }
2241 Expr::Struct { values, fields } => {
2242 if !fields.is_empty() {
2243 write!(
2244 f,
2245 "STRUCT<{}>({})",
2246 display_comma_separated(fields),
2247 display_comma_separated(values)
2248 )
2249 } else {
2250 write!(f, "STRUCT({})", display_comma_separated(values))
2251 }
2252 }
2253 Expr::Named { expr, name } => {
2254 write!(f, "{expr} AS {name}")
2255 }
2256 Expr::Dictionary(fields) => {
2257 write!(f, "{{{}}}", display_comma_separated(fields))
2258 }
2259 Expr::Map(map) => {
2260 write!(f, "{map}")
2261 }
2262 Expr::Array(set) => {
2263 write!(f, "{set}")
2264 }
2265 Expr::JsonAccess { value, path } => {
2266 write!(f, "{value}{path}")
2267 }
2268 Expr::AtTimeZone {
2269 timestamp,
2270 time_zone,
2271 } => {
2272 write!(f, "{timestamp} AT TIME ZONE {time_zone}")
2273 }
2274 Expr::Interval(interval) => {
2275 write!(f, "{interval}")
2276 }
2277 Expr::MatchAgainst {
2278 columns,
2279 match_value: match_expr,
2280 opt_search_modifier,
2281 } => {
2282 write!(f, "MATCH ({}) AGAINST ", display_comma_separated(columns),)?;
2283
2284 if let Some(search_modifier) = opt_search_modifier {
2285 write!(f, "({match_expr} {search_modifier})")?;
2286 } else {
2287 write!(f, "({match_expr})")?;
2288 }
2289
2290 Ok(())
2291 }
2292 Expr::OuterJoin(expr) => {
2293 write!(f, "{expr} (+)")
2294 }
2295 Expr::Prior(expr) => write!(f, "PRIOR {expr}"),
2296 Expr::Lambda(lambda) => write!(f, "{lambda}"),
2297 Expr::MemberOf(member_of) => write!(f, "{member_of}"),
2298 }
2299 }
2300}
2301
2302#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2311#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2312#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2313pub enum WindowType {
2314 WindowSpec(WindowSpec),
2316 NamedWindow(Ident),
2318}
2319
2320impl Display for WindowType {
2321 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2322 match self {
2323 WindowType::WindowSpec(spec) => {
2324 f.write_str("(")?;
2325 NewLine.fmt(f)?;
2326 Indent(spec).fmt(f)?;
2327 NewLine.fmt(f)?;
2328 f.write_str(")")
2329 }
2330 WindowType::NamedWindow(name) => name.fmt(f),
2331 }
2332 }
2333}
2334
2335#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2337#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2338#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2339pub struct WindowSpec {
2340 pub window_name: Option<Ident>,
2348 pub partition_by: Vec<Expr>,
2350 pub order_by: Vec<OrderByExpr>,
2352 pub window_frame: Option<WindowFrame>,
2354}
2355
2356impl fmt::Display for WindowSpec {
2357 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2358 let mut is_first = true;
2359 if let Some(window_name) = &self.window_name {
2360 if !is_first {
2361 SpaceOrNewline.fmt(f)?;
2362 }
2363 is_first = false;
2364 write!(f, "{window_name}")?;
2365 }
2366 if !self.partition_by.is_empty() {
2367 if !is_first {
2368 SpaceOrNewline.fmt(f)?;
2369 }
2370 is_first = false;
2371 write!(
2372 f,
2373 "PARTITION BY {}",
2374 display_comma_separated(&self.partition_by)
2375 )?;
2376 }
2377 if !self.order_by.is_empty() {
2378 if !is_first {
2379 SpaceOrNewline.fmt(f)?;
2380 }
2381 is_first = false;
2382 write!(f, "ORDER BY {}", display_comma_separated(&self.order_by))?;
2383 }
2384 if let Some(window_frame) = &self.window_frame {
2385 if !is_first {
2386 SpaceOrNewline.fmt(f)?;
2387 }
2388 if let Some(end_bound) = &window_frame.end_bound {
2389 write!(
2390 f,
2391 "{} BETWEEN {} AND {}",
2392 window_frame.units, window_frame.start_bound, end_bound
2393 )?;
2394 } else {
2395 write!(f, "{} {}", window_frame.units, window_frame.start_bound)?;
2396 }
2397 }
2398 Ok(())
2399 }
2400}
2401
2402#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2408#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2409#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2410pub struct WindowFrame {
2411 pub units: WindowFrameUnits,
2413 pub start_bound: WindowFrameBound,
2415 pub end_bound: Option<WindowFrameBound>,
2419 }
2421
2422impl Default for WindowFrame {
2423 fn default() -> Self {
2427 Self {
2428 units: WindowFrameUnits::Range,
2429 start_bound: WindowFrameBound::Preceding(None),
2430 end_bound: None,
2431 }
2432 }
2433}
2434
2435#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2436#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2437#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2438pub enum WindowFrameUnits {
2440 Rows,
2442 Range,
2444 Groups,
2446}
2447
2448impl fmt::Display for WindowFrameUnits {
2449 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2450 f.write_str(match self {
2451 WindowFrameUnits::Rows => "ROWS",
2452 WindowFrameUnits::Range => "RANGE",
2453 WindowFrameUnits::Groups => "GROUPS",
2454 })
2455 }
2456}
2457
2458#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2462#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2463#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2464pub enum NullTreatment {
2466 IgnoreNulls,
2468 RespectNulls,
2470}
2471
2472impl fmt::Display for NullTreatment {
2473 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2474 f.write_str(match self {
2475 NullTreatment::IgnoreNulls => "IGNORE NULLS",
2476 NullTreatment::RespectNulls => "RESPECT NULLS",
2477 })
2478 }
2479}
2480
2481#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2483#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2484#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2485pub enum WindowFrameBound {
2486 CurrentRow,
2488 Preceding(Option<Box<Expr>>),
2490 Following(Option<Box<Expr>>),
2492}
2493
2494impl fmt::Display for WindowFrameBound {
2495 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2496 match self {
2497 WindowFrameBound::CurrentRow => f.write_str("CURRENT ROW"),
2498 WindowFrameBound::Preceding(None) => f.write_str("UNBOUNDED PRECEDING"),
2499 WindowFrameBound::Following(None) => f.write_str("UNBOUNDED FOLLOWING"),
2500 WindowFrameBound::Preceding(Some(n)) => write!(f, "{n} PRECEDING"),
2501 WindowFrameBound::Following(Some(n)) => write!(f, "{n} FOLLOWING"),
2502 }
2503 }
2504}
2505
2506#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2507#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2508#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2509pub enum AddDropSync {
2511 ADD,
2513 DROP,
2515 SYNC,
2517}
2518
2519impl fmt::Display for AddDropSync {
2520 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2521 match self {
2522 AddDropSync::SYNC => f.write_str("SYNC PARTITIONS"),
2523 AddDropSync::DROP => f.write_str("DROP PARTITIONS"),
2524 AddDropSync::ADD => f.write_str("ADD PARTITIONS"),
2525 }
2526 }
2527}
2528
2529#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2530#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2531#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2532pub enum ShowCreateObject {
2534 Event,
2536 Function,
2538 Procedure,
2540 Table,
2542 Trigger,
2544 View,
2546}
2547
2548impl fmt::Display for ShowCreateObject {
2549 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2550 match self {
2551 ShowCreateObject::Event => f.write_str("EVENT"),
2552 ShowCreateObject::Function => f.write_str("FUNCTION"),
2553 ShowCreateObject::Procedure => f.write_str("PROCEDURE"),
2554 ShowCreateObject::Table => f.write_str("TABLE"),
2555 ShowCreateObject::Trigger => f.write_str("TRIGGER"),
2556 ShowCreateObject::View => f.write_str("VIEW"),
2557 }
2558 }
2559}
2560
2561#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2562#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2563#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2564pub enum CommentObject {
2566 Collation,
2568 Column,
2570 Database,
2572 Domain,
2574 Extension,
2576 Function,
2578 Index,
2580 MaterializedView,
2582 Procedure,
2584 Role,
2586 Schema,
2588 Sequence,
2590 Table,
2592 Type,
2594 User,
2596 View,
2598}
2599
2600impl fmt::Display for CommentObject {
2601 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2602 match self {
2603 CommentObject::Collation => f.write_str("COLLATION"),
2604 CommentObject::Column => f.write_str("COLUMN"),
2605 CommentObject::Database => f.write_str("DATABASE"),
2606 CommentObject::Domain => f.write_str("DOMAIN"),
2607 CommentObject::Extension => f.write_str("EXTENSION"),
2608 CommentObject::Function => f.write_str("FUNCTION"),
2609 CommentObject::Index => f.write_str("INDEX"),
2610 CommentObject::MaterializedView => f.write_str("MATERIALIZED VIEW"),
2611 CommentObject::Procedure => f.write_str("PROCEDURE"),
2612 CommentObject::Role => f.write_str("ROLE"),
2613 CommentObject::Schema => f.write_str("SCHEMA"),
2614 CommentObject::Sequence => f.write_str("SEQUENCE"),
2615 CommentObject::Table => f.write_str("TABLE"),
2616 CommentObject::Type => f.write_str("TYPE"),
2617 CommentObject::User => f.write_str("USER"),
2618 CommentObject::View => f.write_str("VIEW"),
2619 }
2620 }
2621}
2622
2623#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2624#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2625#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2626pub enum Password {
2628 Password(Expr),
2630 NullPassword,
2632}
2633
2634#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2651#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2652#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2653pub struct CaseStatement {
2654 pub case_token: AttachedToken,
2656 pub match_expr: Option<Expr>,
2658 pub when_blocks: Vec<ConditionalStatementBlock>,
2660 pub else_block: Option<ConditionalStatementBlock>,
2662 pub end_case_token: AttachedToken,
2664}
2665
2666impl fmt::Display for CaseStatement {
2667 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2668 let CaseStatement {
2669 case_token: _,
2670 match_expr,
2671 when_blocks,
2672 else_block,
2673 end_case_token: AttachedToken(end),
2674 } = self;
2675
2676 write!(f, "CASE")?;
2677
2678 if let Some(expr) = match_expr {
2679 write!(f, " {expr}")?;
2680 }
2681
2682 if !when_blocks.is_empty() {
2683 write!(f, " {}", display_separated(when_blocks, " "))?;
2684 }
2685
2686 if let Some(else_block) = else_block {
2687 write!(f, " {else_block}")?;
2688 }
2689
2690 write!(f, " END")?;
2691
2692 if let Token::Word(w) = &end.token {
2693 if w.keyword == Keyword::CASE {
2694 write!(f, " CASE")?;
2695 }
2696 }
2697
2698 Ok(())
2699 }
2700}
2701
2702#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2724#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2725#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2726pub struct IfStatement {
2727 pub if_block: ConditionalStatementBlock,
2729 pub elseif_blocks: Vec<ConditionalStatementBlock>,
2731 pub else_block: Option<ConditionalStatementBlock>,
2733 pub end_token: Option<AttachedToken>,
2735}
2736
2737impl fmt::Display for IfStatement {
2738 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2739 let IfStatement {
2740 if_block,
2741 elseif_blocks,
2742 else_block,
2743 end_token,
2744 } = self;
2745
2746 write!(f, "{if_block}")?;
2747
2748 for elseif_block in elseif_blocks {
2749 write!(f, " {elseif_block}")?;
2750 }
2751
2752 if let Some(else_block) = else_block {
2753 write!(f, " {else_block}")?;
2754 }
2755
2756 if let Some(AttachedToken(end_token)) = end_token {
2757 write!(f, " END {end_token}")?;
2758 }
2759
2760 Ok(())
2761 }
2762}
2763
2764#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2776#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2777#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2778pub struct WhileStatement {
2779 pub while_block: ConditionalStatementBlock,
2781}
2782
2783impl fmt::Display for WhileStatement {
2784 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2785 let WhileStatement { while_block } = self;
2786 write!(f, "{while_block}")?;
2787 Ok(())
2788 }
2789}
2790
2791#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2816#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2817#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2818pub struct ConditionalStatementBlock {
2819 pub start_token: AttachedToken,
2821 pub condition: Option<Expr>,
2823 pub then_token: Option<AttachedToken>,
2825 pub conditional_statements: ConditionalStatements,
2827}
2828
2829impl ConditionalStatementBlock {
2830 pub fn statements(&self) -> &Vec<Statement> {
2832 self.conditional_statements.statements()
2833 }
2834}
2835
2836impl fmt::Display for ConditionalStatementBlock {
2837 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2838 let ConditionalStatementBlock {
2839 start_token: AttachedToken(start_token),
2840 condition,
2841 then_token,
2842 conditional_statements,
2843 } = self;
2844
2845 write!(f, "{start_token}")?;
2846
2847 if let Some(condition) = condition {
2848 write!(f, " {condition}")?;
2849 }
2850
2851 if then_token.is_some() {
2852 write!(f, " THEN")?;
2853 }
2854
2855 if !conditional_statements.statements().is_empty() {
2856 write!(f, " {conditional_statements}")?;
2857 }
2858
2859 Ok(())
2860 }
2861}
2862
2863#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2865#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2866#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2867pub enum ConditionalStatements {
2869 Sequence {
2871 statements: Vec<Statement>,
2873 },
2874 BeginEnd(BeginEndStatements),
2876}
2877
2878impl ConditionalStatements {
2879 pub fn statements(&self) -> &Vec<Statement> {
2881 match self {
2882 ConditionalStatements::Sequence { statements } => statements,
2883 ConditionalStatements::BeginEnd(bes) => &bes.statements,
2884 }
2885 }
2886}
2887
2888impl fmt::Display for ConditionalStatements {
2889 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2890 match self {
2891 ConditionalStatements::Sequence { statements } => {
2892 if !statements.is_empty() {
2893 format_statement_list(f, statements)?;
2894 }
2895 Ok(())
2896 }
2897 ConditionalStatements::BeginEnd(bes) => write!(f, "{bes}"),
2898 }
2899 }
2900}
2901
2902#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2911#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2912#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2913pub struct BeginEndStatements {
2914 pub begin_token: AttachedToken,
2916 pub statements: Vec<Statement>,
2918 pub end_token: AttachedToken,
2920}
2921
2922impl fmt::Display for BeginEndStatements {
2923 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2924 let BeginEndStatements {
2925 begin_token: AttachedToken(begin_token),
2926 statements,
2927 end_token: AttachedToken(end_token),
2928 } = self;
2929
2930 if begin_token.token != Token::EOF {
2931 write!(f, "{begin_token} ")?;
2932 }
2933 if !statements.is_empty() {
2934 format_statement_list(f, statements)?;
2935 }
2936 if end_token.token != Token::EOF {
2937 write!(f, " {end_token}")?;
2938 }
2939 Ok(())
2940 }
2941}
2942
2943#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2955#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2956#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2957pub struct RaiseStatement {
2958 pub value: Option<RaiseStatementValue>,
2960}
2961
2962impl fmt::Display for RaiseStatement {
2963 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2964 let RaiseStatement { value } = self;
2965
2966 write!(f, "RAISE")?;
2967 if let Some(value) = value {
2968 write!(f, " {value}")?;
2969 }
2970
2971 Ok(())
2972 }
2973}
2974
2975#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2977#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2978#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2979pub enum RaiseStatementValue {
2980 UsingMessage(Expr),
2982 Expr(Expr),
2984}
2985
2986impl fmt::Display for RaiseStatementValue {
2987 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2988 match self {
2989 RaiseStatementValue::Expr(expr) => write!(f, "{expr}"),
2990 RaiseStatementValue::UsingMessage(expr) => write!(f, "USING MESSAGE = {expr}"),
2991 }
2992 }
2993}
2994
2995#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3003#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3004#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3005pub struct ThrowStatement {
3006 pub error_number: Option<Box<Expr>>,
3008 pub message: Option<Box<Expr>>,
3010 pub state: Option<Box<Expr>>,
3012}
3013
3014impl fmt::Display for ThrowStatement {
3015 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3016 let ThrowStatement {
3017 error_number,
3018 message,
3019 state,
3020 } = self;
3021
3022 write!(f, "THROW")?;
3023 if let (Some(error_number), Some(message), Some(state)) = (error_number, message, state) {
3024 write!(f, " {error_number}, {message}, {state}")?;
3025 }
3026 Ok(())
3027 }
3028}
3029
3030#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3038#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3039#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3040pub enum DeclareAssignment {
3041 Expr(Box<Expr>),
3043
3044 Default(Box<Expr>),
3046
3047 DuckAssignment(Box<Expr>),
3054
3055 For(Box<Expr>),
3062
3063 MsSqlAssignment(Box<Expr>),
3070}
3071
3072impl fmt::Display for DeclareAssignment {
3073 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3074 match self {
3075 DeclareAssignment::Expr(expr) => {
3076 write!(f, "{expr}")
3077 }
3078 DeclareAssignment::Default(expr) => {
3079 write!(f, "DEFAULT {expr}")
3080 }
3081 DeclareAssignment::DuckAssignment(expr) => {
3082 write!(f, ":= {expr}")
3083 }
3084 DeclareAssignment::MsSqlAssignment(expr) => {
3085 write!(f, "= {expr}")
3086 }
3087 DeclareAssignment::For(expr) => {
3088 write!(f, "FOR {expr}")
3089 }
3090 }
3091 }
3092}
3093
3094#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3096#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3097#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3098pub enum DeclareType {
3099 Cursor,
3105
3106 ResultSet,
3114
3115 Exception,
3123}
3124
3125impl fmt::Display for DeclareType {
3126 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3127 match self {
3128 DeclareType::Cursor => {
3129 write!(f, "CURSOR")
3130 }
3131 DeclareType::ResultSet => {
3132 write!(f, "RESULTSET")
3133 }
3134 DeclareType::Exception => {
3135 write!(f, "EXCEPTION")
3136 }
3137 }
3138 }
3139}
3140
3141#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3154#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3155#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3156pub struct Declare {
3157 pub names: Vec<Ident>,
3160 pub data_type: Option<DataType>,
3163 pub assignment: Option<DeclareAssignment>,
3165 pub declare_type: Option<DeclareType>,
3167 pub binary: Option<bool>,
3169 pub sensitive: Option<bool>,
3173 pub scroll: Option<bool>,
3177 pub hold: Option<bool>,
3181 pub for_query: Option<Box<Query>>,
3183}
3184
3185impl fmt::Display for Declare {
3186 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3187 let Declare {
3188 names,
3189 data_type,
3190 assignment,
3191 declare_type,
3192 binary,
3193 sensitive,
3194 scroll,
3195 hold,
3196 for_query,
3197 } = self;
3198 write!(f, "{}", display_comma_separated(names))?;
3199
3200 if let Some(true) = binary {
3201 write!(f, " BINARY")?;
3202 }
3203
3204 if let Some(sensitive) = sensitive {
3205 if *sensitive {
3206 write!(f, " INSENSITIVE")?;
3207 } else {
3208 write!(f, " ASENSITIVE")?;
3209 }
3210 }
3211
3212 if let Some(scroll) = scroll {
3213 if *scroll {
3214 write!(f, " SCROLL")?;
3215 } else {
3216 write!(f, " NO SCROLL")?;
3217 }
3218 }
3219
3220 if let Some(declare_type) = declare_type {
3221 write!(f, " {declare_type}")?;
3222 }
3223
3224 if let Some(hold) = hold {
3225 if *hold {
3226 write!(f, " WITH HOLD")?;
3227 } else {
3228 write!(f, " WITHOUT HOLD")?;
3229 }
3230 }
3231
3232 if let Some(query) = for_query {
3233 write!(f, " FOR {query}")?;
3234 }
3235
3236 if let Some(data_type) = data_type {
3237 write!(f, " {data_type}")?;
3238 }
3239
3240 if let Some(expr) = assignment {
3241 write!(f, " {expr}")?;
3242 }
3243 Ok(())
3244 }
3245}
3246
3247#[derive(Debug, Default, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3249#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3250#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3251pub enum CreateTableOptions {
3253 #[default]
3255 None,
3256 With(Vec<SqlOption>),
3258 Options(Vec<SqlOption>),
3260 Plain(Vec<SqlOption>),
3262 TableProperties(Vec<SqlOption>),
3264}
3265
3266impl fmt::Display for CreateTableOptions {
3267 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3268 match self {
3269 CreateTableOptions::With(with_options) => {
3270 write!(f, "WITH ({})", display_comma_separated(with_options))
3271 }
3272 CreateTableOptions::Options(options) => {
3273 write!(f, "OPTIONS({})", display_comma_separated(options))
3274 }
3275 CreateTableOptions::TableProperties(options) => {
3276 write!(f, "TBLPROPERTIES ({})", display_comma_separated(options))
3277 }
3278 CreateTableOptions::Plain(options) => {
3279 write!(f, "{}", display_separated(options, " "))
3280 }
3281 CreateTableOptions::None => Ok(()),
3282 }
3283 }
3284}
3285
3286#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3293#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3294#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3295pub enum FromTable {
3296 WithFromKeyword(Vec<TableWithJoins>),
3298 WithoutKeyword(Vec<TableWithJoins>),
3301}
3302impl Display for FromTable {
3303 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3304 match self {
3305 FromTable::WithFromKeyword(tables) => {
3306 write!(f, "FROM {}", display_comma_separated(tables))
3307 }
3308 FromTable::WithoutKeyword(tables) => {
3309 write!(f, "{}", display_comma_separated(tables))
3310 }
3311 }
3312 }
3313}
3314
3315#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3316#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3317#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3318pub enum Set {
3320 SingleAssignment {
3324 scope: Option<ContextModifier>,
3326 hivevar: bool,
3328 variable: ObjectName,
3330 values: Vec<Expr>,
3332 },
3333 ParenthesizedAssignments {
3337 variables: Vec<ObjectName>,
3339 values: Vec<Expr>,
3341 },
3342 MultipleAssignments {
3346 assignments: Vec<SetAssignment>,
3348 },
3349 SetSessionAuthorization(SetSessionAuthorizationParam),
3358 SetSessionParam(SetSessionParamKind),
3362 SetRole {
3373 context_modifier: Option<ContextModifier>,
3375 role_name: Option<Ident>,
3377 },
3378 SetTimeZone {
3388 local: bool,
3390 value: Expr,
3392 },
3393 SetNames {
3397 charset_name: Ident,
3399 collation_name: Option<String>,
3401 },
3402 SetNamesDefault {},
3408 SetTransaction {
3412 modes: Vec<TransactionMode>,
3414 snapshot: Option<ValueWithSpan>,
3416 session: bool,
3418 },
3419}
3420
3421impl Display for Set {
3422 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3423 match self {
3424 Self::ParenthesizedAssignments { variables, values } => write!(
3425 f,
3426 "SET ({}) = ({})",
3427 display_comma_separated(variables),
3428 display_comma_separated(values)
3429 ),
3430 Self::MultipleAssignments { assignments } => {
3431 write!(f, "SET {}", display_comma_separated(assignments))
3432 }
3433 Self::SetRole {
3434 context_modifier,
3435 role_name,
3436 } => {
3437 let role_name = role_name.clone().unwrap_or_else(|| Ident::new("NONE"));
3438 write!(
3439 f,
3440 "SET {modifier}ROLE {role_name}",
3441 modifier = context_modifier.map(|m| format!("{m}")).unwrap_or_default()
3442 )
3443 }
3444 Self::SetSessionAuthorization(kind) => write!(f, "SET SESSION AUTHORIZATION {kind}"),
3445 Self::SetSessionParam(kind) => write!(f, "SET {kind}"),
3446 Self::SetTransaction {
3447 modes,
3448 snapshot,
3449 session,
3450 } => {
3451 if *session {
3452 write!(f, "SET SESSION CHARACTERISTICS AS TRANSACTION")?;
3453 } else {
3454 write!(f, "SET TRANSACTION")?;
3455 }
3456 if !modes.is_empty() {
3457 write!(f, " {}", display_comma_separated(modes))?;
3458 }
3459 if let Some(snapshot_id) = snapshot {
3460 write!(f, " SNAPSHOT {snapshot_id}")?;
3461 }
3462 Ok(())
3463 }
3464 Self::SetTimeZone { local, value } => {
3465 f.write_str("SET ")?;
3466 if *local {
3467 f.write_str("LOCAL ")?;
3468 }
3469 write!(f, "TIME ZONE {value}")
3470 }
3471 Self::SetNames {
3472 charset_name,
3473 collation_name,
3474 } => {
3475 write!(f, "SET NAMES {charset_name}")?;
3476
3477 if let Some(collation) = collation_name {
3478 f.write_str(" COLLATE ")?;
3479 f.write_str(collation)?;
3480 };
3481
3482 Ok(())
3483 }
3484 Self::SetNamesDefault {} => {
3485 f.write_str("SET NAMES DEFAULT")?;
3486
3487 Ok(())
3488 }
3489 Set::SingleAssignment {
3490 scope,
3491 hivevar,
3492 variable,
3493 values,
3494 } => {
3495 write!(
3496 f,
3497 "SET {}{}{} = {}",
3498 scope.map(|s| format!("{s}")).unwrap_or_default(),
3499 if *hivevar { "HIVEVAR:" } else { "" },
3500 variable,
3501 display_comma_separated(values)
3502 )
3503 }
3504 }
3505 }
3506}
3507
3508#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3514#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3515#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3516pub struct ExceptionWhen {
3517 pub idents: Vec<Ident>,
3519 pub statements: Vec<Statement>,
3521}
3522
3523impl Display for ExceptionWhen {
3524 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3525 write!(
3526 f,
3527 "WHEN {idents} THEN",
3528 idents = display_separated(&self.idents, " OR ")
3529 )?;
3530
3531 if !self.statements.is_empty() {
3532 write!(f, " ")?;
3533 format_statement_list(f, &self.statements)?;
3534 }
3535
3536 Ok(())
3537 }
3538}
3539
3540#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3547#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3548#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3549pub struct Analyze {
3550 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3551 pub table_name: Option<ObjectName>,
3553 pub partitions: Option<Vec<Expr>>,
3555 pub for_columns: bool,
3557 pub columns: Vec<Ident>,
3559 pub cache_metadata: bool,
3561 pub noscan: bool,
3563 pub compute_statistics: bool,
3565 pub has_table_keyword: bool,
3567}
3568
3569impl fmt::Display for Analyze {
3570 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3571 write!(f, "ANALYZE")?;
3572 if let Some(ref table_name) = self.table_name {
3573 if self.has_table_keyword {
3574 write!(f, " TABLE")?;
3575 }
3576 write!(f, " {table_name}")?;
3577 }
3578 if !self.for_columns && !self.columns.is_empty() {
3579 write!(f, " ({})", display_comma_separated(&self.columns))?;
3580 }
3581 if let Some(ref parts) = self.partitions {
3582 if !parts.is_empty() {
3583 write!(f, " PARTITION ({})", display_comma_separated(parts))?;
3584 }
3585 }
3586 if self.compute_statistics {
3587 write!(f, " COMPUTE STATISTICS")?;
3588 }
3589 if self.noscan {
3590 write!(f, " NOSCAN")?;
3591 }
3592 if self.cache_metadata {
3593 write!(f, " CACHE METADATA")?;
3594 }
3595 if self.for_columns {
3596 write!(f, " FOR COLUMNS")?;
3597 if !self.columns.is_empty() {
3598 write!(f, " {}", display_comma_separated(&self.columns))?;
3599 }
3600 }
3601 Ok(())
3602 }
3603}
3604
3605#[allow(clippy::large_enum_variant)]
3607#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3608#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3609#[cfg_attr(
3610 feature = "visitor",
3611 derive(Visit, VisitMut),
3612 visit(with = "visit_statement")
3613)]
3614pub enum Statement {
3615 Analyze(Analyze),
3620 Set(Set),
3622 Truncate(Truncate),
3627 Msck(Msck),
3632 Query(Box<Query>),
3636 Insert(Insert),
3640 Install {
3644 extension_name: Ident,
3646 },
3647 Load {
3651 extension_name: Ident,
3653 },
3654 Directory {
3657 overwrite: bool,
3659 local: bool,
3661 path: String,
3663 file_format: Option<FileFormat>,
3665 source: Box<Query>,
3667 },
3668 Case(CaseStatement),
3670 If(IfStatement),
3672 While(WhileStatement),
3674 Raise(RaiseStatement),
3676 Do(DoStatement),
3678 Call(Function),
3682 Copy {
3686 source: CopySource,
3688 to: bool,
3690 target: CopyTarget,
3692 options: Vec<CopyOption>,
3694 legacy_options: Vec<CopyLegacyOption>,
3696 values: Vec<Option<String>>,
3698 },
3699 CopyIntoSnowflake {
3711 kind: CopyIntoSnowflakeKind,
3713 into: ObjectName,
3715 into_columns: Option<Vec<Ident>>,
3717 from_obj: Option<ObjectName>,
3719 from_obj_alias: Option<Ident>,
3721 stage_params: StageParamsObject,
3723 from_transformations: Option<Vec<StageLoadSelectItemKind>>,
3725 from_query: Option<Box<Query>>,
3727 files: Option<Vec<String>>,
3729 pattern: Option<String>,
3731 file_format: KeyValueOptions,
3733 copy_options: KeyValueOptions,
3735 validation_mode: Option<String>,
3737 partition: Option<Box<Expr>>,
3739 },
3740 Open(OpenStatement),
3745 Close {
3750 cursor: CloseCursor,
3752 },
3753 Update(Update),
3757 Delete(Delete),
3761 CreateView(CreateView),
3765 CreateTable(CreateTable),
3769 CreateVirtualTable {
3774 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3775 name: ObjectName,
3777 if_not_exists: bool,
3779 module_name: Ident,
3781 module_args: Vec<Ident>,
3783 },
3784 CreateIndex(CreateIndex),
3788 CreateRole(CreateRole),
3793 CreateSecret {
3798 or_replace: bool,
3800 temporary: Option<bool>,
3802 if_not_exists: bool,
3804 name: Option<Ident>,
3806 storage_specifier: Option<Ident>,
3808 secret_type: Ident,
3810 options: Vec<SecretOption>,
3812 },
3813 CreateServer(CreateServerStatement),
3815 CreateForeignTable(CreateForeignTable),
3820 CreatePolicy(CreatePolicy),
3825 CreateConnector(CreateConnector),
3830 CreateOperator(CreateOperator),
3835 CreateOperatorFamily(CreateOperatorFamily),
3840 CreateOperatorClass(CreateOperatorClass),
3845 CreateTextSearch(CreateTextSearch),
3849 AlterTable(AlterTable),
3853 AlterSchema(AlterSchema),
3858 AlterIndex {
3862 if_exists: bool,
3864 name: ObjectName,
3866 operation: AlterIndexOperation,
3868 },
3869 AlterTrigger {
3873 name: Ident,
3875 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3877 table_name: ObjectName,
3878 new_name: Ident,
3880 },
3881 AlterView {
3885 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3887 name: ObjectName,
3888 columns: Vec<Ident>,
3890 query: Box<Query>,
3892 with_options: Vec<SqlOption>,
3894 },
3895 AlterFunction(AlterFunction),
3902 AlterType(AlterType),
3907 AlterCollation(AlterCollation),
3912 AlterOperator(AlterOperator),
3917 AlterOperatorFamily(AlterOperatorFamily),
3922 AlterOperatorClass(AlterOperatorClass),
3927 AlterTextSearch(AlterTextSearch),
3931 AlterRole {
3935 name: Ident,
3937 operation: AlterRoleOperation,
3939 },
3940 AlterPolicy(AlterPolicy),
3945 AlterConnector {
3954 name: Ident,
3956 properties: Option<Vec<SqlOption>>,
3958 url: Option<String>,
3960 owner: Option<ddl::AlterConnectorOwner>,
3962 },
3963 AlterSession {
3969 set: bool,
3971 session_params: KeyValueOptions,
3973 },
3974 AttachDatabase {
3979 schema_name: Ident,
3981 database_file_name: Expr,
3983 database: bool,
3985 },
3986 AttachDuckDBDatabase {
3992 if_not_exists: bool,
3994 database: bool,
3996 database_path: Ident,
3998 database_alias: Option<Ident>,
4000 attach_options: Vec<AttachDuckDBDatabaseOption>,
4002 },
4003 DetachDuckDBDatabase {
4009 if_exists: bool,
4011 database: bool,
4013 database_alias: Ident,
4015 },
4016 Drop {
4020 object_type: ObjectType,
4022 if_exists: bool,
4024 names: Vec<ObjectName>,
4026 cascade: bool,
4029 restrict: bool,
4032 purge: bool,
4035 temporary: bool,
4037 table: Option<ObjectName>,
4040 },
4041 DropFunction(DropFunction),
4045 DropDomain(DropDomain),
4053 DropProcedure {
4057 if_exists: bool,
4059 proc_desc: Vec<FunctionDesc>,
4061 drop_behavior: Option<DropBehavior>,
4063 },
4064 DropSecret {
4068 if_exists: bool,
4070 temporary: Option<bool>,
4072 name: Ident,
4074 storage_specifier: Option<Ident>,
4076 },
4077 DropPolicy(DropPolicy),
4082 DropConnector {
4087 if_exists: bool,
4089 name: Ident,
4091 },
4092 Declare {
4100 stmts: Vec<Declare>,
4102 },
4103 CreateExtension(CreateExtension),
4112 CreateCollation(CreateCollation),
4118 DropExtension(DropExtension),
4124 DropOperator(DropOperator),
4130 DropOperatorFamily(DropOperatorFamily),
4136 DropOperatorClass(DropOperatorClass),
4142 Fetch {
4150 name: Ident,
4152 direction: FetchDirection,
4154 position: FetchPosition,
4156 into: Option<ObjectName>,
4158 },
4159 Flush {
4166 object_type: FlushType,
4168 location: Option<FlushLocation>,
4170 channel: Option<String>,
4172 read_lock: bool,
4174 export: bool,
4176 tables: Vec<ObjectName>,
4178 },
4179 Discard {
4186 object_type: DiscardObject,
4188 },
4189 ShowFunctions {
4193 filter: Option<ShowStatementFilter>,
4195 },
4196 ShowVariable {
4202 variable: Vec<Ident>,
4204 },
4205 ShowStatus {
4211 filter: Option<ShowStatementFilter>,
4213 global: bool,
4215 session: bool,
4217 },
4218 ShowVariables {
4224 filter: Option<ShowStatementFilter>,
4226 global: bool,
4228 session: bool,
4230 },
4231 ShowCreate {
4237 obj_type: ShowCreateObject,
4239 obj_name: ObjectName,
4241 },
4242 ShowColumns {
4246 extended: bool,
4248 full: bool,
4250 show_options: ShowStatementOptions,
4252 },
4253 ShowCatalogs {
4257 terse: bool,
4259 history: bool,
4261 show_options: ShowStatementOptions,
4263 },
4264 ShowDatabases {
4268 terse: bool,
4270 history: bool,
4272 show_options: ShowStatementOptions,
4274 },
4275 ShowProcessList {
4281 full: bool,
4283 },
4284 ShowSchemas {
4288 terse: bool,
4290 history: bool,
4292 show_options: ShowStatementOptions,
4294 },
4295 ShowCharset(ShowCharset),
4302 ShowObjects(ShowObjects),
4308 ShowTables {
4312 terse: bool,
4314 history: bool,
4316 extended: bool,
4318 full: bool,
4320 external: bool,
4322 show_options: ShowStatementOptions,
4324 },
4325 ShowViews {
4329 terse: bool,
4331 materialized: bool,
4333 show_options: ShowStatementOptions,
4335 },
4336 ShowCollation {
4342 filter: Option<ShowStatementFilter>,
4344 },
4345 Use(Use),
4349 StartTransaction {
4359 modes: Vec<TransactionMode>,
4361 begin: bool,
4363 transaction: Option<BeginTransactionKind>,
4365 modifier: Option<TransactionModifier>,
4367 statements: Vec<Statement>,
4376 exception: Option<Vec<ExceptionWhen>>,
4390 has_end_keyword: bool,
4392 },
4393 Comment {
4399 object_type: CommentObject,
4401 object_name: ObjectName,
4403 comment: Option<String>,
4405 if_exists: bool,
4408 },
4409 Commit {
4419 chain: bool,
4421 end: bool,
4423 modifier: Option<TransactionModifier>,
4425 },
4426 Rollback {
4430 chain: bool,
4432 savepoint: Option<Ident>,
4434 },
4435 CreateSchema {
4439 schema_name: SchemaName,
4441 or_replace: bool,
4443 if_not_exists: bool,
4445 with: Option<Vec<SqlOption>>,
4453 options: Option<Vec<SqlOption>>,
4461 default_collate_spec: Option<Expr>,
4469 clone: Option<ObjectName>,
4477 },
4478 CreateDatabase {
4484 db_name: ObjectName,
4486 if_not_exists: bool,
4488 location: Option<String>,
4490 managed_location: Option<String>,
4492 or_replace: bool,
4494 transient: bool,
4496 clone: Option<ObjectName>,
4498 data_retention_time_in_days: Option<u64>,
4500 max_data_extension_time_in_days: Option<u64>,
4502 external_volume: Option<String>,
4504 catalog: Option<String>,
4506 replace_invalid_characters: Option<bool>,
4508 default_ddl_collation: Option<String>,
4510 storage_serialization_policy: Option<StorageSerializationPolicy>,
4512 comment: Option<String>,
4514 default_charset: Option<String>,
4516 default_collation: Option<String>,
4518 catalog_sync: Option<String>,
4520 catalog_sync_namespace_mode: Option<CatalogSyncNamespaceMode>,
4522 catalog_sync_namespace_flatten_delimiter: Option<String>,
4524 with_tags: Option<Vec<Tag>>,
4526 with_contacts: Option<Vec<ContactEntry>>,
4528 },
4529 CreateFunction(CreateFunction),
4539 CreateTrigger(CreateTrigger),
4541 DropTrigger(DropTrigger),
4543 CreateProcedure {
4547 or_alter: bool,
4549 name: ObjectName,
4551 params: Option<Vec<ProcedureParam>>,
4553 language: Option<Ident>,
4555 body: ConditionalStatements,
4557 },
4558 CreateMacro {
4565 or_replace: bool,
4567 temporary: bool,
4569 name: ObjectName,
4571 args: Option<Vec<MacroArg>>,
4573 definition: MacroDefinition,
4575 },
4576 CreateStage {
4581 or_replace: bool,
4583 temporary: bool,
4585 if_not_exists: bool,
4587 name: ObjectName,
4589 stage_params: StageParamsObject,
4591 directory_table_params: KeyValueOptions,
4593 file_format: KeyValueOptions,
4595 copy_options: KeyValueOptions,
4597 comment: Option<String>,
4599 },
4600 CreateFileFormat {
4607 or_replace: bool,
4609 temporary: bool,
4611 volatile: bool,
4613 if_not_exists: bool,
4615 name: ObjectName,
4617 options: KeyValueOptions,
4619 comment: Option<String>,
4621 },
4622 CreateWarehouse(CreateWarehouse),
4630 Assert {
4634 condition: Expr,
4636 message: Option<Expr>,
4638 },
4639 Grant(Grant),
4643 Deny(DenyStatement),
4647 Revoke(Revoke),
4651 Deallocate {
4657 name: Ident,
4659 prepare: bool,
4661 },
4662 Execute {
4671 name: Option<ObjectName>,
4673 parameters: Vec<Expr>,
4675 has_parentheses: bool,
4677 immediate: bool,
4679 into: Vec<Ident>,
4681 using: Vec<ExprWithAlias>,
4683 output: bool,
4686 default: bool,
4689 },
4690 Prepare {
4696 name: Ident,
4698 data_types: Vec<DataType>,
4700 statement: Box<Statement>,
4702 },
4703 Kill {
4710 modifier: Option<KillType>,
4712 id: u64,
4715 },
4716 ExplainTable {
4721 describe_alias: DescribeAlias,
4723 hive_format: Option<HiveDescribeFormat>,
4725 has_table_keyword: bool,
4730 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4732 table_name: ObjectName,
4733 },
4734 Explain {
4738 describe_alias: DescribeAlias,
4740 analyze: bool,
4742 verbose: bool,
4744 query_plan: bool,
4749 estimate: bool,
4752 statement: Box<Statement>,
4754 format: Option<AnalyzeFormatKind>,
4756 options: Option<Vec<UtilityOption>>,
4758 },
4759 Savepoint {
4764 name: Ident,
4766 },
4767 ReleaseSavepoint {
4771 name: Ident,
4773 },
4774 Merge(Merge),
4783 Cache {
4791 table_flag: Option<ObjectName>,
4793 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4795 table_name: ObjectName,
4796 has_as: bool,
4798 options: Vec<SqlOption>,
4800 query: Option<Box<Query>>,
4802 },
4803 UNCache {
4807 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4809 table_name: ObjectName,
4810 if_exists: bool,
4812 },
4813 CreateSequence {
4818 temporary: bool,
4820 if_not_exists: bool,
4822 name: ObjectName,
4824 data_type: Option<DataType>,
4826 sequence_options: Vec<SequenceOptions>,
4828 owned_by: Option<ObjectName>,
4830 },
4831 CreateDomain(CreateDomain),
4833 CreateType {
4837 name: ObjectName,
4839 representation: Option<UserDefinedTypeRepresentation>,
4841 },
4842 Pragma {
4846 name: ObjectName,
4848 value: Option<ValueWithSpan>,
4850 is_eq: bool,
4852 },
4853 Lock(Lock),
4859 LockTables {
4864 tables: Vec<LockTable>,
4866 },
4867 UnlockTables,
4872 Unload {
4884 query: Option<Box<Query>>,
4886 query_text: Option<String>,
4888 to: Ident,
4890 auth: Option<IamRoleKind>,
4892 with: Vec<SqlOption>,
4894 options: Vec<CopyLegacyOption>,
4896 },
4897 OptimizeTable {
4909 name: ObjectName,
4911 has_table_keyword: bool,
4913 on_cluster: Option<Ident>,
4916 partition: Option<Partition>,
4919 include_final: bool,
4922 deduplicate: Option<Deduplicate>,
4925 predicate: Option<Expr>,
4928 zorder: Option<Vec<Expr>>,
4931 },
4932 LISTEN {
4939 channel: Ident,
4941 },
4942 UNLISTEN {
4949 channel: Ident,
4951 },
4952 NOTIFY {
4959 channel: Ident,
4961 payload: Option<String>,
4963 },
4964 LoadData {
4973 local: bool,
4975 inpath: String,
4977 overwrite: bool,
4979 table_name: ObjectName,
4981 partitioned: Option<Vec<Expr>>,
4983 table_format: Option<HiveLoadDataFormat>,
4985 },
4986 RenameTable(Vec<RenameTable>),
4993 List(FileStagingCommand),
4996 Put {
5003 source: String,
5005 stage: ObjectName,
5007 options: KeyValueOptions,
5009 },
5010 Remove(FileStagingCommand),
5013 RaisError {
5020 message: Box<Expr>,
5022 severity: Box<Expr>,
5024 state: Box<Expr>,
5026 arguments: Vec<Expr>,
5028 options: Vec<RaisErrorOption>,
5030 },
5031 Throw(ThrowStatement),
5033 Print(PrintStatement),
5039 WaitFor(WaitForStatement),
5043 Return(ReturnStatement),
5049 ExportData(ExportData),
5058 CreateUser(CreateUser),
5063 AlterUser(AlterUser),
5068 Vacuum(VacuumStatement),
5075 Reset(ResetStatement),
5083}
5084
5085impl From<Analyze> for Statement {
5086 fn from(analyze: Analyze) -> Self {
5087 Statement::Analyze(analyze)
5088 }
5089}
5090
5091impl From<ddl::Truncate> for Statement {
5092 fn from(truncate: ddl::Truncate) -> Self {
5093 Statement::Truncate(truncate)
5094 }
5095}
5096
5097impl From<Lock> for Statement {
5098 fn from(lock: Lock) -> Self {
5099 Statement::Lock(lock)
5100 }
5101}
5102
5103impl From<ddl::Msck> for Statement {
5104 fn from(msck: ddl::Msck) -> Self {
5105 Statement::Msck(msck)
5106 }
5107}
5108
5109#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5115#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5116#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5117pub enum CurrentGrantsKind {
5118 CopyCurrentGrants,
5120 RevokeCurrentGrants,
5122}
5123
5124impl fmt::Display for CurrentGrantsKind {
5125 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5126 match self {
5127 CurrentGrantsKind::CopyCurrentGrants => write!(f, "COPY CURRENT GRANTS"),
5128 CurrentGrantsKind::RevokeCurrentGrants => write!(f, "REVOKE CURRENT GRANTS"),
5129 }
5130 }
5131}
5132
5133#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5134#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5135#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5136pub enum RaisErrorOption {
5139 Log,
5141 NoWait,
5143 SetError,
5145}
5146
5147impl fmt::Display for RaisErrorOption {
5148 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5149 match self {
5150 RaisErrorOption::Log => write!(f, "LOG"),
5151 RaisErrorOption::NoWait => write!(f, "NOWAIT"),
5152 RaisErrorOption::SetError => write!(f, "SETERROR"),
5153 }
5154 }
5155}
5156
5157impl fmt::Display for Statement {
5158 #[allow(clippy::cognitive_complexity)]
5183 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5184 match self {
5185 Statement::Flush {
5186 object_type,
5187 location,
5188 channel,
5189 read_lock,
5190 export,
5191 tables,
5192 } => {
5193 write!(f, "FLUSH")?;
5194 if let Some(location) = location {
5195 f.write_str(" ")?;
5196 location.fmt(f)?;
5197 }
5198 write!(f, " {object_type}")?;
5199
5200 if let Some(channel) = channel {
5201 write!(f, " FOR CHANNEL {channel}")?;
5202 }
5203
5204 write!(
5205 f,
5206 "{tables}{read}{export}",
5207 tables = if !tables.is_empty() {
5208 format!(" {}", display_comma_separated(tables))
5209 } else {
5210 String::new()
5211 },
5212 export = if *export { " FOR EXPORT" } else { "" },
5213 read = if *read_lock { " WITH READ LOCK" } else { "" }
5214 )
5215 }
5216 Statement::Kill { modifier, id } => {
5217 write!(f, "KILL ")?;
5218
5219 if let Some(m) = modifier {
5220 write!(f, "{m} ")?;
5221 }
5222
5223 write!(f, "{id}")
5224 }
5225 Statement::ExplainTable {
5226 describe_alias,
5227 hive_format,
5228 has_table_keyword,
5229 table_name,
5230 } => {
5231 write!(f, "{describe_alias} ")?;
5232
5233 if let Some(format) = hive_format {
5234 write!(f, "{format} ")?;
5235 }
5236 if *has_table_keyword {
5237 write!(f, "TABLE ")?;
5238 }
5239
5240 write!(f, "{table_name}")
5241 }
5242 Statement::Explain {
5243 describe_alias,
5244 verbose,
5245 analyze,
5246 query_plan,
5247 estimate,
5248 statement,
5249 format,
5250 options,
5251 } => {
5252 write!(f, "{describe_alias} ")?;
5253
5254 if *query_plan {
5255 write!(f, "QUERY PLAN ")?;
5256 }
5257 if *analyze {
5258 write!(f, "ANALYZE ")?;
5259 }
5260 if *estimate {
5261 write!(f, "ESTIMATE ")?;
5262 }
5263
5264 if *verbose {
5265 write!(f, "VERBOSE ")?;
5266 }
5267
5268 if let Some(format) = format {
5269 write!(f, "{format} ")?;
5270 }
5271
5272 if let Some(options) = options {
5273 write!(f, "({}) ", display_comma_separated(options))?;
5274 }
5275
5276 write!(f, "{statement}")
5277 }
5278 Statement::Query(s) => s.fmt(f),
5279 Statement::Declare { stmts } => {
5280 write!(f, "DECLARE ")?;
5281 write!(f, "{}", display_separated(stmts, "; "))
5282 }
5283 Statement::Fetch {
5284 name,
5285 direction,
5286 position,
5287 into,
5288 } => {
5289 write!(f, "FETCH {direction} {position} {name}")?;
5290
5291 if let Some(into) = into {
5292 write!(f, " INTO {into}")?;
5293 }
5294
5295 Ok(())
5296 }
5297 Statement::Directory {
5298 overwrite,
5299 local,
5300 path,
5301 file_format,
5302 source,
5303 } => {
5304 write!(
5305 f,
5306 "INSERT{overwrite}{local} DIRECTORY '{path}'",
5307 overwrite = if *overwrite { " OVERWRITE" } else { "" },
5308 local = if *local { " LOCAL" } else { "" },
5309 path = path
5310 )?;
5311 if let Some(ref ff) = file_format {
5312 write!(f, " STORED AS {ff}")?
5313 }
5314 write!(f, " {source}")
5315 }
5316 Statement::Msck(msck) => msck.fmt(f),
5317 Statement::Truncate(truncate) => truncate.fmt(f),
5318 Statement::Case(stmt) => {
5319 write!(f, "{stmt}")
5320 }
5321 Statement::If(stmt) => {
5322 write!(f, "{stmt}")
5323 }
5324 Statement::While(stmt) => {
5325 write!(f, "{stmt}")
5326 }
5327 Statement::Raise(stmt) => {
5328 write!(f, "{stmt}")
5329 }
5330 Statement::Do(stmt) => {
5331 write!(f, "{stmt}")
5332 }
5333 Statement::AttachDatabase {
5334 schema_name,
5335 database_file_name,
5336 database,
5337 } => {
5338 let keyword = if *database { "DATABASE " } else { "" };
5339 write!(f, "ATTACH {keyword}{database_file_name} AS {schema_name}")
5340 }
5341 Statement::AttachDuckDBDatabase {
5342 if_not_exists,
5343 database,
5344 database_path,
5345 database_alias,
5346 attach_options,
5347 } => {
5348 write!(
5349 f,
5350 "ATTACH{database}{if_not_exists} {database_path}",
5351 database = if *database { " DATABASE" } else { "" },
5352 if_not_exists = if *if_not_exists { " IF NOT EXISTS" } else { "" },
5353 )?;
5354 if let Some(alias) = database_alias {
5355 write!(f, " AS {alias}")?;
5356 }
5357 if !attach_options.is_empty() {
5358 write!(f, " ({})", display_comma_separated(attach_options))?;
5359 }
5360 Ok(())
5361 }
5362 Statement::DetachDuckDBDatabase {
5363 if_exists,
5364 database,
5365 database_alias,
5366 } => {
5367 write!(
5368 f,
5369 "DETACH{database}{if_exists} {database_alias}",
5370 database = if *database { " DATABASE" } else { "" },
5371 if_exists = if *if_exists { " IF EXISTS" } else { "" },
5372 )?;
5373 Ok(())
5374 }
5375 Statement::Analyze(analyze) => analyze.fmt(f),
5376 Statement::Insert(insert) => insert.fmt(f),
5377 Statement::Install {
5378 extension_name: name,
5379 } => write!(f, "INSTALL {name}"),
5380
5381 Statement::Load {
5382 extension_name: name,
5383 } => write!(f, "LOAD {name}"),
5384
5385 Statement::Call(function) => write!(f, "CALL {function}"),
5386
5387 Statement::Copy {
5388 source,
5389 to,
5390 target,
5391 options,
5392 legacy_options,
5393 values,
5394 } => {
5395 write!(f, "COPY")?;
5396 match source {
5397 CopySource::Query(query) => write!(f, " ({query})")?,
5398 CopySource::Table {
5399 table_name,
5400 columns,
5401 } => {
5402 write!(f, " {table_name}")?;
5403 if !columns.is_empty() {
5404 write!(f, " ({})", display_comma_separated(columns))?;
5405 }
5406 }
5407 }
5408 write!(f, " {} {}", if *to { "TO" } else { "FROM" }, target)?;
5409 if !options.is_empty() {
5410 write!(f, " ({})", display_comma_separated(options))?;
5411 }
5412 if !legacy_options.is_empty() {
5413 write!(f, " {}", display_separated(legacy_options, " "))?;
5414 }
5415 if !values.is_empty() {
5416 writeln!(f, ";")?;
5417 let mut delim = "";
5418 for v in values {
5419 write!(f, "{delim}")?;
5420 delim = "\t";
5421 if let Some(v) = v {
5422 write!(f, "{v}")?;
5423 } else {
5424 write!(f, "\\N")?;
5425 }
5426 }
5427 write!(f, "\n\\.")?;
5428 }
5429 Ok(())
5430 }
5431 Statement::Update(update) => update.fmt(f),
5432 Statement::Delete(delete) => delete.fmt(f),
5433 Statement::Open(open) => open.fmt(f),
5434 Statement::Close { cursor } => {
5435 write!(f, "CLOSE {cursor}")?;
5436
5437 Ok(())
5438 }
5439 Statement::CreateDatabase {
5440 db_name,
5441 if_not_exists,
5442 location,
5443 managed_location,
5444 or_replace,
5445 transient,
5446 clone,
5447 data_retention_time_in_days,
5448 max_data_extension_time_in_days,
5449 external_volume,
5450 catalog,
5451 replace_invalid_characters,
5452 default_ddl_collation,
5453 storage_serialization_policy,
5454 comment,
5455 default_charset,
5456 default_collation,
5457 catalog_sync,
5458 catalog_sync_namespace_mode,
5459 catalog_sync_namespace_flatten_delimiter,
5460 with_tags,
5461 with_contacts,
5462 } => {
5463 write!(
5464 f,
5465 "CREATE {or_replace}{transient}DATABASE {if_not_exists}{name}",
5466 or_replace = if *or_replace { "OR REPLACE " } else { "" },
5467 transient = if *transient { "TRANSIENT " } else { "" },
5468 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
5469 name = db_name,
5470 )?;
5471
5472 if let Some(l) = location {
5473 write!(f, " LOCATION '{l}'")?;
5474 }
5475 if let Some(ml) = managed_location {
5476 write!(f, " MANAGEDLOCATION '{ml}'")?;
5477 }
5478 if let Some(clone) = clone {
5479 write!(f, " CLONE {clone}")?;
5480 }
5481
5482 if let Some(value) = data_retention_time_in_days {
5483 write!(f, " DATA_RETENTION_TIME_IN_DAYS = {value}")?;
5484 }
5485
5486 if let Some(value) = max_data_extension_time_in_days {
5487 write!(f, " MAX_DATA_EXTENSION_TIME_IN_DAYS = {value}")?;
5488 }
5489
5490 if let Some(vol) = external_volume {
5491 write!(f, " EXTERNAL_VOLUME = '{vol}'")?;
5492 }
5493
5494 if let Some(cat) = catalog {
5495 write!(f, " CATALOG = '{cat}'")?;
5496 }
5497
5498 if let Some(true) = replace_invalid_characters {
5499 write!(f, " REPLACE_INVALID_CHARACTERS = TRUE")?;
5500 } else if let Some(false) = replace_invalid_characters {
5501 write!(f, " REPLACE_INVALID_CHARACTERS = FALSE")?;
5502 }
5503
5504 if let Some(collation) = default_ddl_collation {
5505 write!(f, " DEFAULT_DDL_COLLATION = '{collation}'")?;
5506 }
5507
5508 if let Some(policy) = storage_serialization_policy {
5509 write!(f, " STORAGE_SERIALIZATION_POLICY = {policy}")?;
5510 }
5511
5512 if let Some(comment) = comment {
5513 write!(f, " COMMENT = '{comment}'")?;
5514 }
5515
5516 if let Some(charset) = default_charset {
5517 write!(f, " DEFAULT CHARACTER SET {charset}")?;
5518 }
5519
5520 if let Some(collation) = default_collation {
5521 write!(f, " DEFAULT COLLATE {collation}")?;
5522 }
5523
5524 if let Some(sync) = catalog_sync {
5525 write!(f, " CATALOG_SYNC = '{sync}'")?;
5526 }
5527
5528 if let Some(mode) = catalog_sync_namespace_mode {
5529 write!(f, " CATALOG_SYNC_NAMESPACE_MODE = {mode}")?;
5530 }
5531
5532 if let Some(delim) = catalog_sync_namespace_flatten_delimiter {
5533 write!(f, " CATALOG_SYNC_NAMESPACE_FLATTEN_DELIMITER = '{delim}'")?;
5534 }
5535
5536 if let Some(tags) = with_tags {
5537 write!(f, " WITH TAG ({})", display_comma_separated(tags))?;
5538 }
5539
5540 if let Some(contacts) = with_contacts {
5541 write!(f, " WITH CONTACT ({})", display_comma_separated(contacts))?;
5542 }
5543 Ok(())
5544 }
5545 Statement::CreateFunction(create_function) => create_function.fmt(f),
5546 Statement::CreateDomain(create_domain) => create_domain.fmt(f),
5547 Statement::CreateTrigger(create_trigger) => create_trigger.fmt(f),
5548 Statement::DropTrigger(drop_trigger) => drop_trigger.fmt(f),
5549 Statement::CreateProcedure {
5550 name,
5551 or_alter,
5552 params,
5553 language,
5554 body,
5555 } => {
5556 write!(
5557 f,
5558 "CREATE {or_alter}PROCEDURE {name}",
5559 or_alter = if *or_alter { "OR ALTER " } else { "" },
5560 name = name
5561 )?;
5562
5563 if let Some(p) = params {
5564 if !p.is_empty() {
5565 write!(f, " ({})", display_comma_separated(p))?;
5566 }
5567 }
5568
5569 if let Some(language) = language {
5570 write!(f, " LANGUAGE {language}")?;
5571 }
5572
5573 write!(f, " AS {body}")
5574 }
5575 Statement::CreateMacro {
5576 or_replace,
5577 temporary,
5578 name,
5579 args,
5580 definition,
5581 } => {
5582 write!(
5583 f,
5584 "CREATE {or_replace}{temp}MACRO {name}",
5585 temp = if *temporary { "TEMPORARY " } else { "" },
5586 or_replace = if *or_replace { "OR REPLACE " } else { "" },
5587 )?;
5588 if let Some(args) = args {
5589 write!(f, "({})", display_comma_separated(args))?;
5590 }
5591 match definition {
5592 MacroDefinition::Expr(expr) => write!(f, " AS {expr}")?,
5593 MacroDefinition::Table(query) => write!(f, " AS TABLE {query}")?,
5594 }
5595 Ok(())
5596 }
5597 Statement::CreateView(create_view) => create_view.fmt(f),
5598 Statement::CreateTable(create_table) => create_table.fmt(f),
5599 Statement::LoadData {
5600 local,
5601 inpath,
5602 overwrite,
5603 table_name,
5604 partitioned,
5605 table_format,
5606 } => {
5607 write!(
5608 f,
5609 "LOAD DATA {local}INPATH '{inpath}' {overwrite}INTO TABLE {table_name}",
5610 local = if *local { "LOCAL " } else { "" },
5611 inpath = inpath,
5612 overwrite = if *overwrite { "OVERWRITE " } else { "" },
5613 table_name = table_name,
5614 )?;
5615 if let Some(ref parts) = &partitioned {
5616 if !parts.is_empty() {
5617 write!(f, " PARTITION ({})", display_comma_separated(parts))?;
5618 }
5619 }
5620 if let Some(HiveLoadDataFormat {
5621 serde,
5622 input_format,
5623 }) = &table_format
5624 {
5625 write!(f, " INPUTFORMAT {input_format} SERDE {serde}")?;
5626 }
5627 Ok(())
5628 }
5629 Statement::CreateVirtualTable {
5630 name,
5631 if_not_exists,
5632 module_name,
5633 module_args,
5634 } => {
5635 write!(
5636 f,
5637 "CREATE VIRTUAL TABLE {if_not_exists}{name} USING {module_name}",
5638 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
5639 name = name,
5640 module_name = module_name
5641 )?;
5642 if !module_args.is_empty() {
5643 write!(f, " ({})", display_comma_separated(module_args))?;
5644 }
5645 Ok(())
5646 }
5647 Statement::CreateIndex(create_index) => create_index.fmt(f),
5648 Statement::CreateExtension(create_extension) => write!(f, "{create_extension}"),
5649 Statement::CreateCollation(create_collation) => write!(f, "{create_collation}"),
5650 Statement::DropExtension(drop_extension) => write!(f, "{drop_extension}"),
5651 Statement::DropOperator(drop_operator) => write!(f, "{drop_operator}"),
5652 Statement::DropOperatorFamily(drop_operator_family) => {
5653 write!(f, "{drop_operator_family}")
5654 }
5655 Statement::DropOperatorClass(drop_operator_class) => {
5656 write!(f, "{drop_operator_class}")
5657 }
5658 Statement::CreateRole(create_role) => write!(f, "{create_role}"),
5659 Statement::CreateSecret {
5660 or_replace,
5661 temporary,
5662 if_not_exists,
5663 name,
5664 storage_specifier,
5665 secret_type,
5666 options,
5667 } => {
5668 write!(
5669 f,
5670 "CREATE {or_replace}",
5671 or_replace = if *or_replace { "OR REPLACE " } else { "" },
5672 )?;
5673 if let Some(t) = temporary {
5674 write!(f, "{}", if *t { "TEMPORARY " } else { "PERSISTENT " })?;
5675 }
5676 write!(
5677 f,
5678 "SECRET {if_not_exists}",
5679 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
5680 )?;
5681 if let Some(n) = name {
5682 write!(f, "{n} ")?;
5683 };
5684 if let Some(s) = storage_specifier {
5685 write!(f, "IN {s} ")?;
5686 }
5687 write!(f, "( TYPE {secret_type}",)?;
5688 if !options.is_empty() {
5689 write!(f, ", {o}", o = display_comma_separated(options))?;
5690 }
5691 write!(f, " )")?;
5692 Ok(())
5693 }
5694 Statement::CreateServer(stmt) => {
5695 write!(f, "{stmt}")
5696 }
5697 Statement::CreateForeignTable(stmt) => write!(f, "{stmt}"),
5698 Statement::CreatePolicy(policy) => write!(f, "{policy}"),
5699 Statement::CreateConnector(create_connector) => create_connector.fmt(f),
5700 Statement::CreateOperator(create_operator) => create_operator.fmt(f),
5701 Statement::CreateOperatorFamily(create_operator_family) => {
5702 create_operator_family.fmt(f)
5703 }
5704 Statement::CreateOperatorClass(create_operator_class) => create_operator_class.fmt(f),
5705 Statement::CreateTextSearch(create_text_search) => create_text_search.fmt(f),
5706 Statement::AlterTable(alter_table) => write!(f, "{alter_table}"),
5707 Statement::AlterIndex {
5708 if_exists,
5709 name,
5710 operation,
5711 } => {
5712 write!(
5713 f,
5714 "ALTER INDEX {if_exists}{name} {operation}",
5715 if_exists = if *if_exists { "IF EXISTS " } else { "" }
5716 )
5717 }
5718 Statement::AlterTrigger {
5719 name,
5720 table_name,
5721 new_name,
5722 } => write!(
5723 f,
5724 "ALTER TRIGGER {name} ON {table_name} RENAME TO {new_name}"
5725 ),
5726 Statement::AlterView {
5727 name,
5728 columns,
5729 query,
5730 with_options,
5731 } => {
5732 write!(f, "ALTER VIEW {name}")?;
5733 if !with_options.is_empty() {
5734 write!(f, " WITH ({})", display_comma_separated(with_options))?;
5735 }
5736 if !columns.is_empty() {
5737 write!(f, " ({})", display_comma_separated(columns))?;
5738 }
5739 write!(f, " AS {query}")
5740 }
5741 Statement::AlterFunction(alter_function) => write!(f, "{alter_function}"),
5742 Statement::AlterType(AlterType { name, operation }) => {
5743 write!(f, "ALTER TYPE {name} {operation}")
5744 }
5745 Statement::AlterCollation(alter_collation) => write!(f, "{alter_collation}"),
5746 Statement::AlterOperator(alter_operator) => write!(f, "{alter_operator}"),
5747 Statement::AlterOperatorFamily(alter_operator_family) => {
5748 write!(f, "{alter_operator_family}")
5749 }
5750 Statement::AlterOperatorClass(alter_operator_class) => {
5751 write!(f, "{alter_operator_class}")
5752 }
5753 Statement::AlterTextSearch(alter_text_search) => write!(f, "{alter_text_search}"),
5754 Statement::AlterRole { name, operation } => {
5755 write!(f, "ALTER ROLE {name} {operation}")
5756 }
5757 Statement::AlterPolicy(alter_policy) => write!(f, "{alter_policy}"),
5758 Statement::AlterConnector {
5759 name,
5760 properties,
5761 url,
5762 owner,
5763 } => {
5764 write!(f, "ALTER CONNECTOR {name}")?;
5765 if let Some(properties) = properties {
5766 write!(
5767 f,
5768 " SET DCPROPERTIES({})",
5769 display_comma_separated(properties)
5770 )?;
5771 }
5772 if let Some(url) = url {
5773 write!(f, " SET URL '{url}'")?;
5774 }
5775 if let Some(owner) = owner {
5776 write!(f, " SET OWNER {owner}")?;
5777 }
5778 Ok(())
5779 }
5780 Statement::AlterSession {
5781 set,
5782 session_params,
5783 } => {
5784 write!(
5785 f,
5786 "ALTER SESSION {set}",
5787 set = if *set { "SET" } else { "UNSET" }
5788 )?;
5789 if !session_params.options.is_empty() {
5790 if *set {
5791 write!(f, " {session_params}")?;
5792 } else {
5793 let options = session_params
5794 .options
5795 .iter()
5796 .map(|p| p.option_name.clone())
5797 .collect::<Vec<_>>();
5798 write!(f, " {}", display_separated(&options, ", "))?;
5799 }
5800 }
5801 Ok(())
5802 }
5803 Statement::Drop {
5804 object_type,
5805 if_exists,
5806 names,
5807 cascade,
5808 restrict,
5809 purge,
5810 temporary,
5811 table,
5812 } => {
5813 write!(
5814 f,
5815 "DROP {}{}{} {}{}{}{}",
5816 if *temporary { "TEMPORARY " } else { "" },
5817 object_type,
5818 if *if_exists { " IF EXISTS" } else { "" },
5819 display_comma_separated(names),
5820 if *cascade { " CASCADE" } else { "" },
5821 if *restrict { " RESTRICT" } else { "" },
5822 if *purge { " PURGE" } else { "" },
5823 )?;
5824 if let Some(table_name) = table.as_ref() {
5825 write!(f, " ON {table_name}")?;
5826 };
5827 Ok(())
5828 }
5829 Statement::DropFunction(drop_function) => write!(f, "{drop_function}"),
5830 Statement::DropDomain(DropDomain {
5831 if_exists,
5832 name,
5833 drop_behavior,
5834 }) => {
5835 write!(
5836 f,
5837 "DROP DOMAIN{} {name}",
5838 if *if_exists { " IF EXISTS" } else { "" },
5839 )?;
5840 if let Some(op) = drop_behavior {
5841 write!(f, " {op}")?;
5842 }
5843 Ok(())
5844 }
5845 Statement::DropProcedure {
5846 if_exists,
5847 proc_desc,
5848 drop_behavior,
5849 } => {
5850 write!(
5851 f,
5852 "DROP PROCEDURE{} {}",
5853 if *if_exists { " IF EXISTS" } else { "" },
5854 display_comma_separated(proc_desc),
5855 )?;
5856 if let Some(op) = drop_behavior {
5857 write!(f, " {op}")?;
5858 }
5859 Ok(())
5860 }
5861 Statement::DropSecret {
5862 if_exists,
5863 temporary,
5864 name,
5865 storage_specifier,
5866 } => {
5867 write!(f, "DROP ")?;
5868 if let Some(t) = temporary {
5869 write!(f, "{}", if *t { "TEMPORARY " } else { "PERSISTENT " })?;
5870 }
5871 write!(
5872 f,
5873 "SECRET {if_exists}{name}",
5874 if_exists = if *if_exists { "IF EXISTS " } else { "" },
5875 )?;
5876 if let Some(s) = storage_specifier {
5877 write!(f, " FROM {s}")?;
5878 }
5879 Ok(())
5880 }
5881 Statement::DropPolicy(policy) => write!(f, "{policy}"),
5882 Statement::DropConnector { if_exists, name } => {
5883 write!(
5884 f,
5885 "DROP CONNECTOR {if_exists}{name}",
5886 if_exists = if *if_exists { "IF EXISTS " } else { "" }
5887 )?;
5888 Ok(())
5889 }
5890 Statement::Discard { object_type } => {
5891 write!(f, "DISCARD {object_type}")?;
5892 Ok(())
5893 }
5894 Self::Set(set) => write!(f, "{set}"),
5895 Statement::ShowVariable { variable } => {
5896 write!(f, "SHOW")?;
5897 if !variable.is_empty() {
5898 write!(f, " {}", display_separated(variable, " "))?;
5899 }
5900 Ok(())
5901 }
5902 Statement::ShowStatus {
5903 filter,
5904 global,
5905 session,
5906 } => {
5907 write!(f, "SHOW")?;
5908 if *global {
5909 write!(f, " GLOBAL")?;
5910 }
5911 if *session {
5912 write!(f, " SESSION")?;
5913 }
5914 write!(f, " STATUS")?;
5915 if let Some(filter) = filter {
5916 write!(f, " {}", filter)?;
5917 }
5918 Ok(())
5919 }
5920 Statement::ShowVariables {
5921 filter,
5922 global,
5923 session,
5924 } => {
5925 write!(f, "SHOW")?;
5926 if *global {
5927 write!(f, " GLOBAL")?;
5928 }
5929 if *session {
5930 write!(f, " SESSION")?;
5931 }
5932 write!(f, " VARIABLES")?;
5933 if let Some(filter) = filter {
5934 write!(f, " {}", filter)?;
5935 }
5936 Ok(())
5937 }
5938 Statement::ShowCreate { obj_type, obj_name } => {
5939 write!(f, "SHOW CREATE {obj_type} {obj_name}",)?;
5940 Ok(())
5941 }
5942 Statement::ShowColumns {
5943 extended,
5944 full,
5945 show_options,
5946 } => {
5947 write!(
5948 f,
5949 "SHOW {extended}{full}COLUMNS{show_options}",
5950 extended = if *extended { "EXTENDED " } else { "" },
5951 full = if *full { "FULL " } else { "" },
5952 )?;
5953 Ok(())
5954 }
5955 Statement::ShowDatabases {
5956 terse,
5957 history,
5958 show_options,
5959 } => {
5960 write!(
5961 f,
5962 "SHOW {terse}DATABASES{history}{show_options}",
5963 terse = if *terse { "TERSE " } else { "" },
5964 history = if *history { " HISTORY" } else { "" },
5965 )?;
5966 Ok(())
5967 }
5968 Statement::ShowCatalogs {
5969 terse,
5970 history,
5971 show_options,
5972 } => {
5973 write!(
5974 f,
5975 "SHOW {terse}CATALOGS{history}{show_options}",
5976 terse = if *terse { "TERSE " } else { "" },
5977 history = if *history { " HISTORY" } else { "" },
5978 )?;
5979 Ok(())
5980 }
5981 Statement::ShowProcessList { full } => {
5982 write!(
5983 f,
5984 "SHOW {full}PROCESSLIST",
5985 full = if *full { "FULL " } else { "" },
5986 )?;
5987 Ok(())
5988 }
5989 Statement::ShowSchemas {
5990 terse,
5991 history,
5992 show_options,
5993 } => {
5994 write!(
5995 f,
5996 "SHOW {terse}SCHEMAS{history}{show_options}",
5997 terse = if *terse { "TERSE " } else { "" },
5998 history = if *history { " HISTORY" } else { "" },
5999 )?;
6000 Ok(())
6001 }
6002 Statement::ShowObjects(ShowObjects {
6003 terse,
6004 show_options,
6005 }) => {
6006 write!(
6007 f,
6008 "SHOW {terse}OBJECTS{show_options}",
6009 terse = if *terse { "TERSE " } else { "" },
6010 )?;
6011 Ok(())
6012 }
6013 Statement::ShowTables {
6014 terse,
6015 history,
6016 extended,
6017 full,
6018 external,
6019 show_options,
6020 } => {
6021 write!(
6022 f,
6023 "SHOW {terse}{extended}{full}{external}TABLES{history}{show_options}",
6024 terse = if *terse { "TERSE " } else { "" },
6025 extended = if *extended { "EXTENDED " } else { "" },
6026 full = if *full { "FULL " } else { "" },
6027 external = if *external { "EXTERNAL " } else { "" },
6028 history = if *history { " HISTORY" } else { "" },
6029 )?;
6030 Ok(())
6031 }
6032 Statement::ShowViews {
6033 terse,
6034 materialized,
6035 show_options,
6036 } => {
6037 write!(
6038 f,
6039 "SHOW {terse}{materialized}VIEWS{show_options}",
6040 terse = if *terse { "TERSE " } else { "" },
6041 materialized = if *materialized { "MATERIALIZED " } else { "" }
6042 )?;
6043 Ok(())
6044 }
6045 Statement::ShowFunctions { filter } => {
6046 write!(f, "SHOW FUNCTIONS")?;
6047 if let Some(filter) = filter {
6048 write!(f, " {filter}")?;
6049 }
6050 Ok(())
6051 }
6052 Statement::Use(use_expr) => use_expr.fmt(f),
6053 Statement::ShowCollation { filter } => {
6054 write!(f, "SHOW COLLATION")?;
6055 if let Some(filter) = filter {
6056 write!(f, " {filter}")?;
6057 }
6058 Ok(())
6059 }
6060 Statement::ShowCharset(show_stm) => show_stm.fmt(f),
6061 Statement::StartTransaction {
6062 modes,
6063 begin: syntax_begin,
6064 transaction,
6065 modifier,
6066 statements,
6067 exception,
6068 has_end_keyword,
6069 } => {
6070 if *syntax_begin {
6071 if let Some(modifier) = *modifier {
6072 write!(f, "BEGIN {modifier}")?;
6073 } else {
6074 write!(f, "BEGIN")?;
6075 }
6076 } else {
6077 write!(f, "START")?;
6078 }
6079 if let Some(transaction) = transaction {
6080 write!(f, " {transaction}")?;
6081 }
6082 if !modes.is_empty() {
6083 write!(f, " {}", display_comma_separated(modes))?;
6084 }
6085 if !statements.is_empty() {
6086 write!(f, " ")?;
6087 format_statement_list(f, statements)?;
6088 }
6089 if let Some(exception_when) = exception {
6090 write!(f, " EXCEPTION")?;
6091 for when in exception_when {
6092 write!(f, " {when}")?;
6093 }
6094 }
6095 if *has_end_keyword {
6096 write!(f, " END")?;
6097 }
6098 Ok(())
6099 }
6100 Statement::Commit {
6101 chain,
6102 end: end_syntax,
6103 modifier,
6104 } => {
6105 if *end_syntax {
6106 write!(f, "END")?;
6107 if let Some(modifier) = *modifier {
6108 write!(f, " {modifier}")?;
6109 }
6110 if *chain {
6111 write!(f, " AND CHAIN")?;
6112 }
6113 } else {
6114 write!(f, "COMMIT{}", if *chain { " AND CHAIN" } else { "" })?;
6115 }
6116 Ok(())
6117 }
6118 Statement::Rollback { chain, savepoint } => {
6119 write!(f, "ROLLBACK")?;
6120
6121 if *chain {
6122 write!(f, " AND CHAIN")?;
6123 }
6124
6125 if let Some(savepoint) = savepoint {
6126 write!(f, " TO SAVEPOINT {savepoint}")?;
6127 }
6128
6129 Ok(())
6130 }
6131 Statement::CreateSchema {
6132 schema_name,
6133 or_replace,
6134 if_not_exists,
6135 with,
6136 options,
6137 default_collate_spec,
6138 clone,
6139 } => {
6140 write!(
6141 f,
6142 "CREATE {or_replace}SCHEMA {if_not_exists}{name}",
6143 or_replace = if *or_replace { "OR REPLACE " } else { "" },
6144 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
6145 name = schema_name
6146 )?;
6147
6148 if let Some(collate) = default_collate_spec {
6149 write!(f, " DEFAULT COLLATE {collate}")?;
6150 }
6151
6152 if let Some(with) = with {
6153 write!(f, " WITH ({})", display_comma_separated(with))?;
6154 }
6155
6156 if let Some(options) = options {
6157 write!(f, " OPTIONS({})", display_comma_separated(options))?;
6158 }
6159
6160 if let Some(clone) = clone {
6161 write!(f, " CLONE {clone}")?;
6162 }
6163 Ok(())
6164 }
6165 Statement::Assert { condition, message } => {
6166 write!(f, "ASSERT {condition}")?;
6167 if let Some(m) = message {
6168 write!(f, " AS {m}")?;
6169 }
6170 Ok(())
6171 }
6172 Statement::Grant(grant) => write!(f, "{grant}"),
6173 Statement::Deny(s) => write!(f, "{s}"),
6174 Statement::Revoke(revoke) => write!(f, "{revoke}"),
6175 Statement::Deallocate { name, prepare } => write!(
6176 f,
6177 "DEALLOCATE {prepare}{name}",
6178 prepare = if *prepare { "PREPARE " } else { "" },
6179 name = name,
6180 ),
6181 Statement::Execute {
6182 name,
6183 parameters,
6184 has_parentheses,
6185 immediate,
6186 into,
6187 using,
6188 output,
6189 default,
6190 } => {
6191 let (open, close) = if *has_parentheses {
6192 (if name.is_some() { "(" } else { " (" }, ")")
6194 } else {
6195 (if parameters.is_empty() { "" } else { " " }, "")
6196 };
6197 write!(f, "EXECUTE")?;
6198 if *immediate {
6199 write!(f, " IMMEDIATE")?;
6200 }
6201 if let Some(name) = name {
6202 write!(f, " {name}")?;
6203 }
6204 write!(f, "{open}{}{close}", display_comma_separated(parameters),)?;
6205 if !into.is_empty() {
6206 write!(f, " INTO {}", display_comma_separated(into))?;
6207 }
6208 if !using.is_empty() {
6209 write!(f, " USING {}", display_comma_separated(using))?;
6210 };
6211 if *output {
6212 write!(f, " OUTPUT")?;
6213 }
6214 if *default {
6215 write!(f, " DEFAULT")?;
6216 }
6217 Ok(())
6218 }
6219 Statement::Prepare {
6220 name,
6221 data_types,
6222 statement,
6223 } => {
6224 write!(f, "PREPARE {name} ")?;
6225 if !data_types.is_empty() {
6226 write!(f, "({}) ", display_comma_separated(data_types))?;
6227 }
6228 write!(f, "AS {statement}")
6229 }
6230 Statement::Comment {
6231 object_type,
6232 object_name,
6233 comment,
6234 if_exists,
6235 } => {
6236 write!(f, "COMMENT ")?;
6237 if *if_exists {
6238 write!(f, "IF EXISTS ")?
6239 };
6240 write!(f, "ON {object_type} {object_name} IS ")?;
6241 if let Some(c) = comment {
6242 write!(f, "'{c}'")
6243 } else {
6244 write!(f, "NULL")
6245 }
6246 }
6247 Statement::Savepoint { name } => {
6248 write!(f, "SAVEPOINT ")?;
6249 write!(f, "{name}")
6250 }
6251 Statement::ReleaseSavepoint { name } => {
6252 write!(f, "RELEASE SAVEPOINT {name}")
6253 }
6254 Statement::Merge(merge) => merge.fmt(f),
6255 Statement::Cache {
6256 table_name,
6257 table_flag,
6258 has_as,
6259 options,
6260 query,
6261 } => {
6262 if let Some(table_flag) = table_flag {
6263 write!(f, "CACHE {table_flag} TABLE {table_name}")?;
6264 } else {
6265 write!(f, "CACHE TABLE {table_name}")?;
6266 }
6267
6268 if !options.is_empty() {
6269 write!(f, " OPTIONS({})", display_comma_separated(options))?;
6270 }
6271
6272 match (*has_as, query) {
6273 (true, Some(query)) => write!(f, " AS {query}"),
6274 (true, None) => f.write_str(" AS"),
6275 (false, Some(query)) => write!(f, " {query}"),
6276 (false, None) => Ok(()),
6277 }
6278 }
6279 Statement::UNCache {
6280 table_name,
6281 if_exists,
6282 } => {
6283 if *if_exists {
6284 write!(f, "UNCACHE TABLE IF EXISTS {table_name}")
6285 } else {
6286 write!(f, "UNCACHE TABLE {table_name}")
6287 }
6288 }
6289 Statement::CreateSequence {
6290 temporary,
6291 if_not_exists,
6292 name,
6293 data_type,
6294 sequence_options,
6295 owned_by,
6296 } => {
6297 let as_type: String = if let Some(dt) = data_type.as_ref() {
6298 [" AS ", &dt.to_string()].concat()
6301 } else {
6302 "".to_string()
6303 };
6304 write!(
6305 f,
6306 "CREATE {temporary}SEQUENCE {if_not_exists}{name}{as_type}",
6307 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
6308 temporary = if *temporary { "TEMPORARY " } else { "" },
6309 name = name,
6310 as_type = as_type
6311 )?;
6312 for sequence_option in sequence_options {
6313 write!(f, "{sequence_option}")?;
6314 }
6315 if let Some(ob) = owned_by.as_ref() {
6316 write!(f, " OWNED BY {ob}")?;
6317 }
6318 write!(f, "")
6319 }
6320 Statement::CreateStage {
6321 or_replace,
6322 temporary,
6323 if_not_exists,
6324 name,
6325 stage_params,
6326 directory_table_params,
6327 file_format,
6328 copy_options,
6329 comment,
6330 ..
6331 } => {
6332 write!(
6333 f,
6334 "CREATE {or_replace}{temp}STAGE {if_not_exists}{name}{stage_params}",
6335 temp = if *temporary { "TEMPORARY " } else { "" },
6336 or_replace = if *or_replace { "OR REPLACE " } else { "" },
6337 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
6338 )?;
6339 if !directory_table_params.options.is_empty() {
6340 write!(f, " DIRECTORY=({directory_table_params})")?;
6341 }
6342 if !file_format.options.is_empty() {
6343 write!(f, " FILE_FORMAT=({file_format})")?;
6344 }
6345 if !copy_options.options.is_empty() {
6346 write!(f, " COPY_OPTIONS=({copy_options})")?;
6347 }
6348 if let Some(comment) = comment {
6349 write!(f, " COMMENT='{}'", comment)?;
6350 }
6351 Ok(())
6352 }
6353 Statement::CreateFileFormat {
6354 or_replace,
6355 temporary,
6356 volatile,
6357 if_not_exists,
6358 name,
6359 options,
6360 comment,
6361 } => {
6362 write!(
6363 f,
6364 "CREATE {or_replace}{temp}{volatile}FILE FORMAT {if_not_exists}{name}",
6365 or_replace = if *or_replace { "OR REPLACE " } else { "" },
6366 temp = if *temporary { "TEMPORARY " } else { "" },
6367 volatile = if *volatile { "VOLATILE " } else { "" },
6368 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
6369 )?;
6370 if !options.options.is_empty() {
6371 write!(f, " {options}")?;
6372 }
6373 if let Some(comment) = comment {
6374 write!(f, " COMMENT='{}'", comment)?;
6375 }
6376 Ok(())
6377 }
6378 Statement::CreateWarehouse(s) => write!(f, "{s}"),
6379 Statement::CopyIntoSnowflake {
6380 kind,
6381 into,
6382 into_columns,
6383 from_obj,
6384 from_obj_alias,
6385 stage_params,
6386 from_transformations,
6387 from_query,
6388 files,
6389 pattern,
6390 file_format,
6391 copy_options,
6392 validation_mode,
6393 partition,
6394 } => {
6395 write!(f, "COPY INTO {into}")?;
6396 if let Some(into_columns) = into_columns {
6397 write!(f, " ({})", display_comma_separated(into_columns))?;
6398 }
6399 if let Some(from_transformations) = from_transformations {
6400 if let Some(from_stage) = from_obj {
6402 write!(
6403 f,
6404 " FROM (SELECT {} FROM {}{}",
6405 display_separated(from_transformations, ", "),
6406 from_stage,
6407 stage_params
6408 )?;
6409 }
6410 if let Some(from_obj_alias) = from_obj_alias {
6411 write!(f, " AS {from_obj_alias}")?;
6412 }
6413 write!(f, ")")?;
6414 } else if let Some(from_obj) = from_obj {
6415 write!(f, " FROM {from_obj}{stage_params}")?;
6417 if let Some(from_obj_alias) = from_obj_alias {
6418 write!(f, " AS {from_obj_alias}")?;
6419 }
6420 } else if let Some(from_query) = from_query {
6421 write!(f, " FROM ({from_query})")?;
6423 }
6424
6425 if let Some(files) = files {
6426 write!(f, " FILES = ('{}')", display_separated(files, "', '"))?;
6427 }
6428 if let Some(pattern) = pattern {
6429 write!(f, " PATTERN = '{pattern}'")?;
6430 }
6431 if let Some(partition) = partition {
6432 write!(f, " PARTITION BY {partition}")?;
6433 }
6434 if !file_format.options.is_empty() {
6435 write!(f, " FILE_FORMAT=({file_format})")?;
6436 }
6437 if !copy_options.options.is_empty() {
6438 match kind {
6439 CopyIntoSnowflakeKind::Table => {
6440 write!(f, " COPY_OPTIONS=({copy_options})")?
6441 }
6442 CopyIntoSnowflakeKind::Location => write!(f, " {copy_options}")?,
6443 }
6444 }
6445 if let Some(validation_mode) = validation_mode {
6446 write!(f, " VALIDATION_MODE = {validation_mode}")?;
6447 }
6448 Ok(())
6449 }
6450 Statement::CreateType {
6451 name,
6452 representation,
6453 } => {
6454 write!(f, "CREATE TYPE {name}")?;
6455 if let Some(repr) = representation {
6456 write!(f, " {repr}")?;
6457 }
6458 Ok(())
6459 }
6460 Statement::Pragma { name, value, is_eq } => {
6461 write!(f, "PRAGMA {name}")?;
6462 if let Some(value) = value {
6463 if *is_eq {
6464 write!(f, " = {value}")?;
6465 } else {
6466 write!(f, "({value})")?;
6467 }
6468 }
6469 Ok(())
6470 }
6471 Statement::Lock(lock) => lock.fmt(f),
6472 Statement::LockTables { tables } => {
6473 write!(f, "LOCK TABLES {}", display_comma_separated(tables))
6474 }
6475 Statement::UnlockTables => {
6476 write!(f, "UNLOCK TABLES")
6477 }
6478 Statement::Unload {
6479 query,
6480 query_text,
6481 to,
6482 auth,
6483 with,
6484 options,
6485 } => {
6486 write!(f, "UNLOAD(")?;
6487 if let Some(query) = query {
6488 write!(f, "{query}")?;
6489 }
6490 if let Some(query_text) = query_text {
6491 write!(f, "'{query_text}'")?;
6492 }
6493 write!(f, ") TO {to}")?;
6494 if let Some(auth) = auth {
6495 write!(f, " IAM_ROLE {auth}")?;
6496 }
6497 if !with.is_empty() {
6498 write!(f, " WITH ({})", display_comma_separated(with))?;
6499 }
6500 if !options.is_empty() {
6501 write!(f, " {}", display_separated(options, " "))?;
6502 }
6503 Ok(())
6504 }
6505 Statement::OptimizeTable {
6506 name,
6507 has_table_keyword,
6508 on_cluster,
6509 partition,
6510 include_final,
6511 deduplicate,
6512 predicate,
6513 zorder,
6514 } => {
6515 write!(f, "OPTIMIZE")?;
6516 if *has_table_keyword {
6517 write!(f, " TABLE")?;
6518 }
6519 write!(f, " {name}")?;
6520 if let Some(on_cluster) = on_cluster {
6521 write!(f, " ON CLUSTER {on_cluster}")?;
6522 }
6523 if let Some(partition) = partition {
6524 write!(f, " {partition}")?;
6525 }
6526 if *include_final {
6527 write!(f, " FINAL")?;
6528 }
6529 if let Some(deduplicate) = deduplicate {
6530 write!(f, " {deduplicate}")?;
6531 }
6532 if let Some(predicate) = predicate {
6533 write!(f, " WHERE {predicate}")?;
6534 }
6535 if let Some(zorder) = zorder {
6536 write!(f, " ZORDER BY ({})", display_comma_separated(zorder))?;
6537 }
6538 Ok(())
6539 }
6540 Statement::LISTEN { channel } => {
6541 write!(f, "LISTEN {channel}")?;
6542 Ok(())
6543 }
6544 Statement::UNLISTEN { channel } => {
6545 write!(f, "UNLISTEN {channel}")?;
6546 Ok(())
6547 }
6548 Statement::NOTIFY { channel, payload } => {
6549 write!(f, "NOTIFY {channel}")?;
6550 if let Some(payload) = payload {
6551 write!(f, ", '{payload}'")?;
6552 }
6553 Ok(())
6554 }
6555 Statement::RenameTable(rename_tables) => {
6556 write!(f, "RENAME TABLE {}", display_comma_separated(rename_tables))
6557 }
6558 Statement::RaisError {
6559 message,
6560 severity,
6561 state,
6562 arguments,
6563 options,
6564 } => {
6565 write!(f, "RAISERROR({message}, {severity}, {state}")?;
6566 if !arguments.is_empty() {
6567 write!(f, ", {}", display_comma_separated(arguments))?;
6568 }
6569 write!(f, ")")?;
6570 if !options.is_empty() {
6571 write!(f, " WITH {}", display_comma_separated(options))?;
6572 }
6573 Ok(())
6574 }
6575 Statement::Throw(s) => write!(f, "{s}"),
6576 Statement::Print(s) => write!(f, "{s}"),
6577 Statement::WaitFor(s) => write!(f, "{s}"),
6578 Statement::Return(r) => write!(f, "{r}"),
6579 Statement::List(command) => write!(f, "LIST {command}"),
6580 Statement::Put {
6581 source,
6582 stage,
6583 options,
6584 } => {
6585 write!(f, "PUT '{source}' {stage}")?;
6586 if !options.options.is_empty() {
6587 write!(f, " {options}")?;
6588 }
6589 Ok(())
6590 }
6591 Statement::Remove(command) => write!(f, "REMOVE {command}"),
6592 Statement::ExportData(e) => write!(f, "{e}"),
6593 Statement::CreateUser(s) => write!(f, "{s}"),
6594 Statement::AlterSchema(s) => write!(f, "{s}"),
6595 Statement::Vacuum(s) => write!(f, "{s}"),
6596 Statement::AlterUser(s) => write!(f, "{s}"),
6597 Statement::Reset(s) => write!(f, "{s}"),
6598 }
6599 }
6600}
6601
6602#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6609#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6610#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6611pub enum SequenceOptions {
6612 IncrementBy(Expr, bool),
6614 MinValue(Option<Expr>),
6616 MaxValue(Option<Expr>),
6618 StartWith(Expr, bool),
6620 Cache(Expr),
6622 Cycle(bool),
6624}
6625
6626impl fmt::Display for SequenceOptions {
6627 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6628 match self {
6629 SequenceOptions::IncrementBy(increment, by) => {
6630 write!(
6631 f,
6632 " INCREMENT{by} {increment}",
6633 by = if *by { " BY" } else { "" },
6634 increment = increment
6635 )
6636 }
6637 SequenceOptions::MinValue(Some(expr)) => {
6638 write!(f, " MINVALUE {expr}")
6639 }
6640 SequenceOptions::MinValue(None) => {
6641 write!(f, " NO MINVALUE")
6642 }
6643 SequenceOptions::MaxValue(Some(expr)) => {
6644 write!(f, " MAXVALUE {expr}")
6645 }
6646 SequenceOptions::MaxValue(None) => {
6647 write!(f, " NO MAXVALUE")
6648 }
6649 SequenceOptions::StartWith(start, with) => {
6650 write!(
6651 f,
6652 " START{with} {start}",
6653 with = if *with { " WITH" } else { "" },
6654 start = start
6655 )
6656 }
6657 SequenceOptions::Cache(cache) => {
6658 write!(f, " CACHE {}", *cache)
6659 }
6660 SequenceOptions::Cycle(no) => {
6661 write!(f, " {}CYCLE", if *no { "NO " } else { "" })
6662 }
6663 }
6664 }
6665}
6666
6667#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6669#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6670#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6671pub struct SetAssignment {
6672 pub scope: Option<ContextModifier>,
6674 pub name: ObjectName,
6676 pub value: Expr,
6678}
6679
6680impl fmt::Display for SetAssignment {
6681 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6682 write!(
6683 f,
6684 "{}{} = {}",
6685 self.scope.map(|s| format!("{s}")).unwrap_or_default(),
6686 self.name,
6687 self.value
6688 )
6689 }
6690}
6691
6692#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6696#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6697#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6698pub struct TruncateTableTarget {
6699 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6701 pub name: ObjectName,
6702 pub only: bool,
6708 pub has_asterisk: bool,
6714}
6715
6716impl fmt::Display for TruncateTableTarget {
6717 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6718 if self.only {
6719 write!(f, "ONLY ")?;
6720 };
6721 write!(f, "{}", self.name)?;
6722 if self.has_asterisk {
6723 write!(f, " *")?;
6724 };
6725 Ok(())
6726 }
6727}
6728
6729#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6733#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6734#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6735pub struct Lock {
6736 pub tables: Vec<LockTableTarget>,
6738 pub lock_mode: Option<LockTableMode>,
6740 pub nowait: bool,
6742}
6743
6744impl fmt::Display for Lock {
6745 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6746 write!(f, "LOCK TABLE {}", display_comma_separated(&self.tables))?;
6747 if let Some(lock_mode) = &self.lock_mode {
6748 write!(f, " IN {lock_mode} MODE")?;
6749 }
6750 if self.nowait {
6751 write!(f, " NOWAIT")?;
6752 }
6753 Ok(())
6754 }
6755}
6756
6757#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6761#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6762#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6763pub struct LockTableTarget {
6764 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6766 pub name: ObjectName,
6767 pub only: bool,
6769 pub has_asterisk: bool,
6771}
6772
6773impl fmt::Display for LockTableTarget {
6774 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6775 if self.only {
6776 write!(f, "ONLY ")?;
6777 }
6778 write!(f, "{}", self.name)?;
6779 if self.has_asterisk {
6780 write!(f, " *")?;
6781 }
6782 Ok(())
6783 }
6784}
6785
6786#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6790#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6791#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6792pub enum LockTableMode {
6793 AccessShare,
6795 RowShare,
6797 RowExclusive,
6799 ShareUpdateExclusive,
6801 Share,
6803 ShareRowExclusive,
6805 Exclusive,
6807 AccessExclusive,
6809}
6810
6811impl fmt::Display for LockTableMode {
6812 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6813 let text = match self {
6814 Self::AccessShare => "ACCESS SHARE",
6815 Self::RowShare => "ROW SHARE",
6816 Self::RowExclusive => "ROW EXCLUSIVE",
6817 Self::ShareUpdateExclusive => "SHARE UPDATE EXCLUSIVE",
6818 Self::Share => "SHARE",
6819 Self::ShareRowExclusive => "SHARE ROW EXCLUSIVE",
6820 Self::Exclusive => "EXCLUSIVE",
6821 Self::AccessExclusive => "ACCESS EXCLUSIVE",
6822 };
6823 write!(f, "{text}")
6824 }
6825}
6826
6827#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6830#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6831#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6832pub enum TruncateIdentityOption {
6833 Restart,
6835 Continue,
6837}
6838
6839#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6842#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6843#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6844pub enum CascadeOption {
6845 Cascade,
6847 Restrict,
6849}
6850
6851impl Display for CascadeOption {
6852 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6853 match self {
6854 CascadeOption::Cascade => write!(f, "CASCADE"),
6855 CascadeOption::Restrict => write!(f, "RESTRICT"),
6856 }
6857 }
6858}
6859
6860#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6862#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6863#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6864pub enum BeginTransactionKind {
6865 Transaction,
6867 Work,
6869 Tran,
6872}
6873
6874impl Display for BeginTransactionKind {
6875 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6876 match self {
6877 BeginTransactionKind::Transaction => write!(f, "TRANSACTION"),
6878 BeginTransactionKind::Work => write!(f, "WORK"),
6879 BeginTransactionKind::Tran => write!(f, "TRAN"),
6880 }
6881 }
6882}
6883
6884#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6887#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6888#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6889pub enum MinMaxValue {
6890 Empty,
6892 None,
6894 Some(Expr),
6896}
6897
6898#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6899#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6900#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6901#[non_exhaustive]
6902pub enum OnInsert {
6904 DuplicateKeyUpdate(Vec<Assignment>),
6906 OnConflict(OnConflict),
6908}
6909
6910#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6911#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6912#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6913pub struct InsertAliases {
6915 pub row_alias: ObjectName,
6917 pub col_aliases: Option<Vec<Ident>>,
6919}
6920
6921#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6922#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6923#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6924pub struct TableAliasWithoutColumns {
6926 pub explicit: bool,
6928 pub alias: Ident,
6930}
6931
6932#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6933#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6934#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6935pub struct OnConflict {
6937 pub conflict_target: Option<ConflictTarget>,
6939 pub action: OnConflictAction,
6941}
6942#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6943#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6944#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6945pub enum ConflictTarget {
6947 Columns {
6949 columns: Vec<Ident>,
6951 predicate: Option<Expr>,
6953 },
6954 OnConstraint(ObjectName),
6956}
6957#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6958#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6959#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6960pub enum OnConflictAction {
6962 DoNothing,
6964 DoUpdate(DoUpdate),
6966}
6967
6968#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6969#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6970#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6971pub struct DoUpdate {
6973 pub assignments: Vec<Assignment>,
6975 pub selection: Option<Expr>,
6977}
6978
6979impl fmt::Display for OnInsert {
6980 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6981 match self {
6982 Self::DuplicateKeyUpdate(expr) => write!(
6983 f,
6984 " ON DUPLICATE KEY UPDATE {}",
6985 display_comma_separated(expr)
6986 ),
6987 Self::OnConflict(o) => write!(f, "{o}"),
6988 }
6989 }
6990}
6991impl fmt::Display for OnConflict {
6992 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6993 write!(f, " ON CONFLICT")?;
6994 if let Some(target) = &self.conflict_target {
6995 write!(f, "{target}")?;
6996 }
6997 write!(f, " {}", self.action)
6998 }
6999}
7000impl fmt::Display for ConflictTarget {
7001 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7002 match self {
7003 ConflictTarget::Columns { columns, predicate } => {
7004 write!(f, "({})", display_comma_separated(columns))?;
7005 if let Some(predicate) = predicate {
7006 write!(f, " WHERE {predicate}")?;
7007 }
7008 Ok(())
7009 }
7010 ConflictTarget::OnConstraint(name) => write!(f, " ON CONSTRAINT {name}"),
7011 }
7012 }
7013}
7014impl fmt::Display for OnConflictAction {
7015 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7016 match self {
7017 Self::DoNothing => write!(f, "DO NOTHING"),
7018 Self::DoUpdate(do_update) => {
7019 write!(f, "DO UPDATE")?;
7020 if !do_update.assignments.is_empty() {
7021 write!(
7022 f,
7023 " SET {}",
7024 display_comma_separated(&do_update.assignments)
7025 )?;
7026 }
7027 if let Some(selection) = &do_update.selection {
7028 write!(f, " WHERE {selection}")?;
7029 }
7030 Ok(())
7031 }
7032 }
7033 }
7034}
7035
7036#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7038#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7039#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7040pub enum Privileges {
7041 All {
7043 with_privileges_keyword: bool,
7045 },
7046 Actions(Vec<Action>),
7048}
7049
7050impl fmt::Display for Privileges {
7051 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7052 match self {
7053 Privileges::All {
7054 with_privileges_keyword,
7055 } => {
7056 write!(
7057 f,
7058 "ALL{}",
7059 if *with_privileges_keyword {
7060 " PRIVILEGES"
7061 } else {
7062 ""
7063 }
7064 )
7065 }
7066 Privileges::Actions(actions) => {
7067 write!(f, "{}", display_comma_separated(actions))
7068 }
7069 }
7070 }
7071}
7072
7073#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7075#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7076#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7077pub enum FetchDirection {
7078 Count {
7080 limit: ValueWithSpan,
7082 },
7083 Next,
7085 Prior,
7087 First,
7089 Last,
7091 Absolute {
7093 limit: ValueWithSpan,
7095 },
7096 Relative {
7098 limit: ValueWithSpan,
7100 },
7101 All,
7103 Forward {
7107 limit: Option<ValueWithSpan>,
7109 },
7110 ForwardAll,
7112 Backward {
7116 limit: Option<ValueWithSpan>,
7118 },
7119 BackwardAll,
7121}
7122
7123impl fmt::Display for FetchDirection {
7124 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7125 match self {
7126 FetchDirection::Count { limit } => f.write_str(&limit.to_string())?,
7127 FetchDirection::Next => f.write_str("NEXT")?,
7128 FetchDirection::Prior => f.write_str("PRIOR")?,
7129 FetchDirection::First => f.write_str("FIRST")?,
7130 FetchDirection::Last => f.write_str("LAST")?,
7131 FetchDirection::Absolute { limit } => {
7132 f.write_str("ABSOLUTE ")?;
7133 f.write_str(&limit.to_string())?;
7134 }
7135 FetchDirection::Relative { limit } => {
7136 f.write_str("RELATIVE ")?;
7137 f.write_str(&limit.to_string())?;
7138 }
7139 FetchDirection::All => f.write_str("ALL")?,
7140 FetchDirection::Forward { limit } => {
7141 f.write_str("FORWARD")?;
7142
7143 if let Some(l) = limit {
7144 f.write_str(" ")?;
7145 f.write_str(&l.to_string())?;
7146 }
7147 }
7148 FetchDirection::ForwardAll => f.write_str("FORWARD ALL")?,
7149 FetchDirection::Backward { limit } => {
7150 f.write_str("BACKWARD")?;
7151
7152 if let Some(l) = limit {
7153 f.write_str(" ")?;
7154 f.write_str(&l.to_string())?;
7155 }
7156 }
7157 FetchDirection::BackwardAll => f.write_str("BACKWARD ALL")?,
7158 };
7159
7160 Ok(())
7161 }
7162}
7163
7164#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7168#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7169#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7170pub enum FetchPosition {
7171 From,
7173 In,
7175}
7176
7177impl fmt::Display for FetchPosition {
7178 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7179 match self {
7180 FetchPosition::From => f.write_str("FROM")?,
7181 FetchPosition::In => f.write_str("IN")?,
7182 };
7183
7184 Ok(())
7185 }
7186}
7187
7188#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7190#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7191#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7192pub enum Action {
7193 AddSearchOptimization,
7195 Apply {
7197 apply_type: ActionApplyType,
7199 },
7200 ApplyBudget,
7202 AttachListing,
7204 AttachPolicy,
7206 Audit,
7208 BindServiceEndpoint,
7210 Connect,
7212 Create {
7214 obj_type: Option<ActionCreateObjectType>,
7216 },
7217 DatabaseRole {
7219 role: ObjectName,
7221 },
7222 Delete,
7224 Drop,
7226 EvolveSchema,
7228 Exec {
7230 obj_type: Option<ActionExecuteObjectType>,
7232 },
7233 Execute {
7235 obj_type: Option<ActionExecuteObjectType>,
7237 },
7238 Failover,
7240 ImportedPrivileges,
7242 ImportShare,
7244 Insert {
7246 columns: Option<Vec<Ident>>,
7248 },
7249 Manage {
7251 manage_type: ActionManageType,
7253 },
7254 ManageReleases,
7256 ManageVersions,
7258 Modify {
7260 modify_type: Option<ActionModifyType>,
7262 },
7263 Monitor {
7265 monitor_type: Option<ActionMonitorType>,
7267 },
7268 Operate,
7270 OverrideShareRestrictions,
7272 Ownership,
7274 PurchaseDataExchangeListing,
7276
7277 Read,
7279 ReadSession,
7281 References {
7283 columns: Option<Vec<Ident>>,
7285 },
7286 Replicate,
7288 ResolveAll,
7290 Role {
7292 role: ObjectName,
7294 },
7295 Select {
7297 columns: Option<Vec<Ident>>,
7299 },
7300 Temporary,
7302 Trigger,
7304 Truncate,
7306 Update {
7308 columns: Option<Vec<Ident>>,
7310 },
7311 Usage,
7313}
7314
7315impl fmt::Display for Action {
7316 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7317 match self {
7318 Action::AddSearchOptimization => f.write_str("ADD SEARCH OPTIMIZATION")?,
7319 Action::Apply { apply_type } => write!(f, "APPLY {apply_type}")?,
7320 Action::ApplyBudget => f.write_str("APPLYBUDGET")?,
7321 Action::AttachListing => f.write_str("ATTACH LISTING")?,
7322 Action::AttachPolicy => f.write_str("ATTACH POLICY")?,
7323 Action::Audit => f.write_str("AUDIT")?,
7324 Action::BindServiceEndpoint => f.write_str("BIND SERVICE ENDPOINT")?,
7325 Action::Connect => f.write_str("CONNECT")?,
7326 Action::Create { obj_type } => {
7327 f.write_str("CREATE")?;
7328 if let Some(obj_type) = obj_type {
7329 write!(f, " {obj_type}")?
7330 }
7331 }
7332 Action::DatabaseRole { role } => write!(f, "DATABASE ROLE {role}")?,
7333 Action::Delete => f.write_str("DELETE")?,
7334 Action::Drop => f.write_str("DROP")?,
7335 Action::EvolveSchema => f.write_str("EVOLVE SCHEMA")?,
7336 Action::Exec { obj_type } => {
7337 f.write_str("EXEC")?;
7338 if let Some(obj_type) = obj_type {
7339 write!(f, " {obj_type}")?
7340 }
7341 }
7342 Action::Execute { obj_type } => {
7343 f.write_str("EXECUTE")?;
7344 if let Some(obj_type) = obj_type {
7345 write!(f, " {obj_type}")?
7346 }
7347 }
7348 Action::Failover => f.write_str("FAILOVER")?,
7349 Action::ImportedPrivileges => f.write_str("IMPORTED PRIVILEGES")?,
7350 Action::ImportShare => f.write_str("IMPORT SHARE")?,
7351 Action::Insert { .. } => f.write_str("INSERT")?,
7352 Action::Manage { manage_type } => write!(f, "MANAGE {manage_type}")?,
7353 Action::ManageReleases => f.write_str("MANAGE RELEASES")?,
7354 Action::ManageVersions => f.write_str("MANAGE VERSIONS")?,
7355 Action::Modify { modify_type } => {
7356 write!(f, "MODIFY")?;
7357 if let Some(modify_type) = modify_type {
7358 write!(f, " {modify_type}")?;
7359 }
7360 }
7361 Action::Monitor { monitor_type } => {
7362 write!(f, "MONITOR")?;
7363 if let Some(monitor_type) = monitor_type {
7364 write!(f, " {monitor_type}")?
7365 }
7366 }
7367 Action::Operate => f.write_str("OPERATE")?,
7368 Action::OverrideShareRestrictions => f.write_str("OVERRIDE SHARE RESTRICTIONS")?,
7369 Action::Ownership => f.write_str("OWNERSHIP")?,
7370 Action::PurchaseDataExchangeListing => f.write_str("PURCHASE DATA EXCHANGE LISTING")?,
7371 Action::Read => f.write_str("READ")?,
7372 Action::ReadSession => f.write_str("READ SESSION")?,
7373 Action::References { .. } => f.write_str("REFERENCES")?,
7374 Action::Replicate => f.write_str("REPLICATE")?,
7375 Action::ResolveAll => f.write_str("RESOLVE ALL")?,
7376 Action::Role { role } => write!(f, "ROLE {role}")?,
7377 Action::Select { .. } => f.write_str("SELECT")?,
7378 Action::Temporary => f.write_str("TEMPORARY")?,
7379 Action::Trigger => f.write_str("TRIGGER")?,
7380 Action::Truncate => f.write_str("TRUNCATE")?,
7381 Action::Update { .. } => f.write_str("UPDATE")?,
7382 Action::Usage => f.write_str("USAGE")?,
7383 };
7384 match self {
7385 Action::Insert { columns }
7386 | Action::References { columns }
7387 | Action::Select { columns }
7388 | Action::Update { columns } => {
7389 if let Some(columns) = columns {
7390 write!(f, " ({})", display_comma_separated(columns))?;
7391 }
7392 }
7393 _ => (),
7394 };
7395 Ok(())
7396 }
7397}
7398
7399#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7400#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7401#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7402pub enum ActionCreateObjectType {
7405 Account,
7407 Application,
7409 ApplicationPackage,
7411 ComputePool,
7413 DataExchangeListing,
7415 Database,
7417 ExternalVolume,
7419 FailoverGroup,
7421 Integration,
7423 NetworkPolicy,
7425 OrganiationListing,
7427 ReplicationGroup,
7429 Role,
7431 Schema,
7433 Share,
7435 User,
7437 Warehouse,
7439}
7440
7441impl fmt::Display for ActionCreateObjectType {
7442 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7443 match self {
7444 ActionCreateObjectType::Account => write!(f, "ACCOUNT"),
7445 ActionCreateObjectType::Application => write!(f, "APPLICATION"),
7446 ActionCreateObjectType::ApplicationPackage => write!(f, "APPLICATION PACKAGE"),
7447 ActionCreateObjectType::ComputePool => write!(f, "COMPUTE POOL"),
7448 ActionCreateObjectType::DataExchangeListing => write!(f, "DATA EXCHANGE LISTING"),
7449 ActionCreateObjectType::Database => write!(f, "DATABASE"),
7450 ActionCreateObjectType::ExternalVolume => write!(f, "EXTERNAL VOLUME"),
7451 ActionCreateObjectType::FailoverGroup => write!(f, "FAILOVER GROUP"),
7452 ActionCreateObjectType::Integration => write!(f, "INTEGRATION"),
7453 ActionCreateObjectType::NetworkPolicy => write!(f, "NETWORK POLICY"),
7454 ActionCreateObjectType::OrganiationListing => write!(f, "ORGANIZATION LISTING"),
7455 ActionCreateObjectType::ReplicationGroup => write!(f, "REPLICATION GROUP"),
7456 ActionCreateObjectType::Role => write!(f, "ROLE"),
7457 ActionCreateObjectType::Schema => write!(f, "SCHEMA"),
7458 ActionCreateObjectType::Share => write!(f, "SHARE"),
7459 ActionCreateObjectType::User => write!(f, "USER"),
7460 ActionCreateObjectType::Warehouse => write!(f, "WAREHOUSE"),
7461 }
7462 }
7463}
7464
7465#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7466#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7467#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7468pub enum ActionApplyType {
7471 AggregationPolicy,
7473 AuthenticationPolicy,
7475 JoinPolicy,
7477 MaskingPolicy,
7479 PackagesPolicy,
7481 PasswordPolicy,
7483 ProjectionPolicy,
7485 RowAccessPolicy,
7487 SessionPolicy,
7489 Tag,
7491}
7492
7493impl fmt::Display for ActionApplyType {
7494 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7495 match self {
7496 ActionApplyType::AggregationPolicy => write!(f, "AGGREGATION POLICY"),
7497 ActionApplyType::AuthenticationPolicy => write!(f, "AUTHENTICATION POLICY"),
7498 ActionApplyType::JoinPolicy => write!(f, "JOIN POLICY"),
7499 ActionApplyType::MaskingPolicy => write!(f, "MASKING POLICY"),
7500 ActionApplyType::PackagesPolicy => write!(f, "PACKAGES POLICY"),
7501 ActionApplyType::PasswordPolicy => write!(f, "PASSWORD POLICY"),
7502 ActionApplyType::ProjectionPolicy => write!(f, "PROJECTION POLICY"),
7503 ActionApplyType::RowAccessPolicy => write!(f, "ROW ACCESS POLICY"),
7504 ActionApplyType::SessionPolicy => write!(f, "SESSION POLICY"),
7505 ActionApplyType::Tag => write!(f, "TAG"),
7506 }
7507 }
7508}
7509
7510#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7511#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7512#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7513pub enum ActionExecuteObjectType {
7516 Alert,
7518 DataMetricFunction,
7520 ManagedAlert,
7522 ManagedTask,
7524 Task,
7526}
7527
7528impl fmt::Display for ActionExecuteObjectType {
7529 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7530 match self {
7531 ActionExecuteObjectType::Alert => write!(f, "ALERT"),
7532 ActionExecuteObjectType::DataMetricFunction => write!(f, "DATA METRIC FUNCTION"),
7533 ActionExecuteObjectType::ManagedAlert => write!(f, "MANAGED ALERT"),
7534 ActionExecuteObjectType::ManagedTask => write!(f, "MANAGED TASK"),
7535 ActionExecuteObjectType::Task => write!(f, "TASK"),
7536 }
7537 }
7538}
7539
7540#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7541#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7542#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7543pub enum ActionManageType {
7546 AccountSupportCases,
7548 EventSharing,
7550 Grants,
7552 ListingAutoFulfillment,
7554 OrganizationSupportCases,
7556 UserSupportCases,
7558 Warehouses,
7560}
7561
7562impl fmt::Display for ActionManageType {
7563 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7564 match self {
7565 ActionManageType::AccountSupportCases => write!(f, "ACCOUNT SUPPORT CASES"),
7566 ActionManageType::EventSharing => write!(f, "EVENT SHARING"),
7567 ActionManageType::Grants => write!(f, "GRANTS"),
7568 ActionManageType::ListingAutoFulfillment => write!(f, "LISTING AUTO FULFILLMENT"),
7569 ActionManageType::OrganizationSupportCases => write!(f, "ORGANIZATION SUPPORT CASES"),
7570 ActionManageType::UserSupportCases => write!(f, "USER SUPPORT CASES"),
7571 ActionManageType::Warehouses => write!(f, "WAREHOUSES"),
7572 }
7573 }
7574}
7575
7576#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7577#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7578#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7579pub enum ActionModifyType {
7582 LogLevel,
7584 TraceLevel,
7586 SessionLogLevel,
7588 SessionTraceLevel,
7590}
7591
7592impl fmt::Display for ActionModifyType {
7593 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7594 match self {
7595 ActionModifyType::LogLevel => write!(f, "LOG LEVEL"),
7596 ActionModifyType::TraceLevel => write!(f, "TRACE LEVEL"),
7597 ActionModifyType::SessionLogLevel => write!(f, "SESSION LOG LEVEL"),
7598 ActionModifyType::SessionTraceLevel => write!(f, "SESSION TRACE LEVEL"),
7599 }
7600 }
7601}
7602
7603#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7604#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7605#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7606pub enum ActionMonitorType {
7609 Execution,
7611 Security,
7613 Usage,
7615}
7616
7617impl fmt::Display for ActionMonitorType {
7618 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7619 match self {
7620 ActionMonitorType::Execution => write!(f, "EXECUTION"),
7621 ActionMonitorType::Security => write!(f, "SECURITY"),
7622 ActionMonitorType::Usage => write!(f, "USAGE"),
7623 }
7624 }
7625}
7626
7627#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7629#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7630#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7631pub struct Grantee {
7632 pub grantee_type: GranteesType,
7634 pub name: Option<GranteeName>,
7636}
7637
7638impl fmt::Display for Grantee {
7639 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7640 let keyword = match self.grantee_type {
7641 GranteesType::Role => "ROLE",
7642 GranteesType::Share => "SHARE",
7643 GranteesType::User => "USER",
7644 GranteesType::Group => "GROUP",
7645 GranteesType::Public => "PUBLIC",
7646 GranteesType::DatabaseRole => "DATABASE ROLE",
7647 GranteesType::Application => "APPLICATION",
7648 GranteesType::ApplicationRole => "APPLICATION ROLE",
7649 GranteesType::None => "",
7650 };
7651 f.write_str(keyword)?;
7652 if let Some(name) = &self.name {
7653 if !keyword.is_empty() {
7654 f.write_str(" ")?;
7655 }
7656 name.fmt(f)?;
7657 }
7658 Ok(())
7659 }
7660}
7661
7662#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7663#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7664#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7665pub enum GranteesType {
7667 Role,
7669 Share,
7671 User,
7673 Group,
7675 Public,
7677 DatabaseRole,
7679 Application,
7681 ApplicationRole,
7683 None,
7685}
7686
7687#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7689#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7690#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7691pub enum GranteeName {
7692 ObjectName(ObjectName),
7694 UserHost {
7696 user: Ident,
7698 host: Ident,
7700 },
7701}
7702
7703impl fmt::Display for GranteeName {
7704 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7705 match self {
7706 GranteeName::ObjectName(name) => name.fmt(f),
7707 GranteeName::UserHost { user, host } => {
7708 write!(f, "{user}@{host}")
7709 }
7710 }
7711 }
7712}
7713
7714#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7716#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7717#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7718pub enum GrantObjects {
7719 AllSequencesInSchema {
7721 schemas: Vec<ObjectName>,
7723 },
7724 AllTablesInSchema {
7726 schemas: Vec<ObjectName>,
7728 },
7729 AllViewsInSchema {
7731 schemas: Vec<ObjectName>,
7733 },
7734 AllMaterializedViewsInSchema {
7736 schemas: Vec<ObjectName>,
7738 },
7739 AllExternalTablesInSchema {
7741 schemas: Vec<ObjectName>,
7743 },
7744 AllFunctionsInSchema {
7746 schemas: Vec<ObjectName>,
7748 },
7749 FutureSchemasInDatabase {
7751 databases: Vec<ObjectName>,
7753 },
7754 FutureTablesInSchema {
7756 schemas: Vec<ObjectName>,
7758 },
7759 FutureViewsInSchema {
7761 schemas: Vec<ObjectName>,
7763 },
7764 FutureExternalTablesInSchema {
7766 schemas: Vec<ObjectName>,
7768 },
7769 FutureMaterializedViewsInSchema {
7771 schemas: Vec<ObjectName>,
7773 },
7774 FutureSequencesInSchema {
7776 schemas: Vec<ObjectName>,
7778 },
7779 Databases(Vec<ObjectName>),
7781 Schemas(Vec<ObjectName>),
7783 Sequences(Vec<ObjectName>),
7785 Tables(Vec<ObjectName>),
7787 Views(Vec<ObjectName>),
7789 Warehouses(Vec<ObjectName>),
7791 Integrations(Vec<ObjectName>),
7793 ResourceMonitors(Vec<ObjectName>),
7795 Users(Vec<ObjectName>),
7797 ComputePools(Vec<ObjectName>),
7799 Connections(Vec<ObjectName>),
7801 FailoverGroup(Vec<ObjectName>),
7803 ReplicationGroup(Vec<ObjectName>),
7805 ExternalVolumes(Vec<ObjectName>),
7807 Procedure {
7813 name: ObjectName,
7815 arg_types: Vec<DataType>,
7817 },
7818
7819 Function {
7825 name: ObjectName,
7827 arg_types: Vec<DataType>,
7829 },
7830}
7831
7832impl fmt::Display for GrantObjects {
7833 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7834 match self {
7835 GrantObjects::Sequences(sequences) => {
7836 write!(f, "SEQUENCE {}", display_comma_separated(sequences))
7837 }
7838 GrantObjects::Databases(databases) => {
7839 write!(f, "DATABASE {}", display_comma_separated(databases))
7840 }
7841 GrantObjects::Schemas(schemas) => {
7842 write!(f, "SCHEMA {}", display_comma_separated(schemas))
7843 }
7844 GrantObjects::Tables(tables) => {
7845 write!(f, "{}", display_comma_separated(tables))
7846 }
7847 GrantObjects::Views(views) => {
7848 write!(f, "VIEW {}", display_comma_separated(views))
7849 }
7850 GrantObjects::Warehouses(warehouses) => {
7851 write!(f, "WAREHOUSE {}", display_comma_separated(warehouses))
7852 }
7853 GrantObjects::Integrations(integrations) => {
7854 write!(f, "INTEGRATION {}", display_comma_separated(integrations))
7855 }
7856 GrantObjects::AllSequencesInSchema { schemas } => {
7857 write!(
7858 f,
7859 "ALL SEQUENCES IN SCHEMA {}",
7860 display_comma_separated(schemas)
7861 )
7862 }
7863 GrantObjects::AllTablesInSchema { schemas } => {
7864 write!(
7865 f,
7866 "ALL TABLES IN SCHEMA {}",
7867 display_comma_separated(schemas)
7868 )
7869 }
7870 GrantObjects::AllExternalTablesInSchema { schemas } => {
7871 write!(
7872 f,
7873 "ALL EXTERNAL TABLES IN SCHEMA {}",
7874 display_comma_separated(schemas)
7875 )
7876 }
7877 GrantObjects::AllViewsInSchema { schemas } => {
7878 write!(
7879 f,
7880 "ALL VIEWS IN SCHEMA {}",
7881 display_comma_separated(schemas)
7882 )
7883 }
7884 GrantObjects::AllMaterializedViewsInSchema { schemas } => {
7885 write!(
7886 f,
7887 "ALL MATERIALIZED VIEWS IN SCHEMA {}",
7888 display_comma_separated(schemas)
7889 )
7890 }
7891 GrantObjects::AllFunctionsInSchema { schemas } => {
7892 write!(
7893 f,
7894 "ALL FUNCTIONS IN SCHEMA {}",
7895 display_comma_separated(schemas)
7896 )
7897 }
7898 GrantObjects::FutureSchemasInDatabase { databases } => {
7899 write!(
7900 f,
7901 "FUTURE SCHEMAS IN DATABASE {}",
7902 display_comma_separated(databases)
7903 )
7904 }
7905 GrantObjects::FutureTablesInSchema { schemas } => {
7906 write!(
7907 f,
7908 "FUTURE TABLES IN SCHEMA {}",
7909 display_comma_separated(schemas)
7910 )
7911 }
7912 GrantObjects::FutureExternalTablesInSchema { schemas } => {
7913 write!(
7914 f,
7915 "FUTURE EXTERNAL TABLES IN SCHEMA {}",
7916 display_comma_separated(schemas)
7917 )
7918 }
7919 GrantObjects::FutureViewsInSchema { schemas } => {
7920 write!(
7921 f,
7922 "FUTURE VIEWS IN SCHEMA {}",
7923 display_comma_separated(schemas)
7924 )
7925 }
7926 GrantObjects::FutureMaterializedViewsInSchema { schemas } => {
7927 write!(
7928 f,
7929 "FUTURE MATERIALIZED VIEWS IN SCHEMA {}",
7930 display_comma_separated(schemas)
7931 )
7932 }
7933 GrantObjects::FutureSequencesInSchema { schemas } => {
7934 write!(
7935 f,
7936 "FUTURE SEQUENCES IN SCHEMA {}",
7937 display_comma_separated(schemas)
7938 )
7939 }
7940 GrantObjects::ResourceMonitors(objects) => {
7941 write!(f, "RESOURCE MONITOR {}", display_comma_separated(objects))
7942 }
7943 GrantObjects::Users(objects) => {
7944 write!(f, "USER {}", display_comma_separated(objects))
7945 }
7946 GrantObjects::ComputePools(objects) => {
7947 write!(f, "COMPUTE POOL {}", display_comma_separated(objects))
7948 }
7949 GrantObjects::Connections(objects) => {
7950 write!(f, "CONNECTION {}", display_comma_separated(objects))
7951 }
7952 GrantObjects::FailoverGroup(objects) => {
7953 write!(f, "FAILOVER GROUP {}", display_comma_separated(objects))
7954 }
7955 GrantObjects::ReplicationGroup(objects) => {
7956 write!(f, "REPLICATION GROUP {}", display_comma_separated(objects))
7957 }
7958 GrantObjects::ExternalVolumes(objects) => {
7959 write!(f, "EXTERNAL VOLUME {}", display_comma_separated(objects))
7960 }
7961 GrantObjects::Procedure { name, arg_types } => {
7962 write!(f, "PROCEDURE {name}")?;
7963 if !arg_types.is_empty() {
7964 write!(f, "({})", display_comma_separated(arg_types))?;
7965 }
7966 Ok(())
7967 }
7968 GrantObjects::Function { name, arg_types } => {
7969 write!(f, "FUNCTION {name}")?;
7970 if !arg_types.is_empty() {
7971 write!(f, "({})", display_comma_separated(arg_types))?;
7972 }
7973 Ok(())
7974 }
7975 }
7976 }
7977}
7978
7979#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7983#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7984#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7985pub struct DenyStatement {
7986 pub privileges: Privileges,
7988 pub objects: GrantObjects,
7990 pub grantees: Vec<Grantee>,
7992 pub granted_by: Option<Ident>,
7994 pub cascade: Option<CascadeOption>,
7996}
7997
7998impl fmt::Display for DenyStatement {
7999 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8000 write!(f, "DENY {}", self.privileges)?;
8001 write!(f, " ON {}", self.objects)?;
8002 if !self.grantees.is_empty() {
8003 write!(f, " TO {}", display_comma_separated(&self.grantees))?;
8004 }
8005 if let Some(cascade) = &self.cascade {
8006 write!(f, " {cascade}")?;
8007 }
8008 if let Some(granted_by) = &self.granted_by {
8009 write!(f, " AS {granted_by}")?;
8010 }
8011 Ok(())
8012 }
8013}
8014
8015#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8017#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8018#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8019pub struct Assignment {
8020 pub target: AssignmentTarget,
8022 pub value: Expr,
8024}
8025
8026impl fmt::Display for Assignment {
8027 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8028 write!(f, "{} = {}", self.target, self.value)
8029 }
8030}
8031
8032#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8036#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8037#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8038pub enum AssignmentTarget {
8039 ColumnName(ObjectName),
8041 Subscript {
8043 column: ObjectName,
8045 subscripts: Vec<Subscript>,
8047 },
8048 Tuple(Vec<ObjectName>),
8050}
8051
8052impl fmt::Display for AssignmentTarget {
8053 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8054 match self {
8055 AssignmentTarget::ColumnName(column) => write!(f, "{column}"),
8056 AssignmentTarget::Subscript { column, subscripts } => {
8057 write!(f, "{column}")?;
8058 for subscript in subscripts {
8059 write!(f, "[{subscript}]")?;
8060 }
8061 Ok(())
8062 }
8063 AssignmentTarget::Tuple(columns) => write!(f, "({})", display_comma_separated(columns)),
8064 }
8065 }
8066}
8067
8068#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8069#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8070#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8071pub enum FunctionArgExpr {
8073 Expr(Expr),
8075 QualifiedWildcard(ObjectName),
8077 Wildcard,
8079 WildcardWithOptions(WildcardAdditionalOptions),
8083}
8084
8085impl From<Expr> for FunctionArgExpr {
8086 fn from(wildcard_expr: Expr) -> Self {
8087 match wildcard_expr {
8088 Expr::QualifiedWildcard(prefix, _) => Self::QualifiedWildcard(prefix),
8089 Expr::Wildcard(_) => Self::Wildcard,
8090 expr => Self::Expr(expr),
8091 }
8092 }
8093}
8094
8095impl fmt::Display for FunctionArgExpr {
8096 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8097 match self {
8098 FunctionArgExpr::Expr(expr) => write!(f, "{expr}"),
8099 FunctionArgExpr::QualifiedWildcard(prefix) => write!(f, "{prefix}.*"),
8100 FunctionArgExpr::Wildcard => f.write_str("*"),
8101 FunctionArgExpr::WildcardWithOptions(opts) => write!(f, "*{opts}"),
8102 }
8103 }
8104}
8105
8106#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8107#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8108#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8109pub enum FunctionArgOperator {
8111 Equals,
8113 RightArrow,
8115 Assignment,
8117 Colon,
8119 Value,
8121 Space,
8126}
8127
8128impl fmt::Display for FunctionArgOperator {
8129 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8130 match self {
8131 FunctionArgOperator::Equals => f.write_str("="),
8132 FunctionArgOperator::RightArrow => f.write_str("=>"),
8133 FunctionArgOperator::Assignment => f.write_str(":="),
8134 FunctionArgOperator::Colon => f.write_str(":"),
8135 FunctionArgOperator::Value => f.write_str("VALUE"),
8136 FunctionArgOperator::Space => Ok(()),
8137 }
8138 }
8139}
8140
8141#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8142#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8143#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8144pub enum FunctionArg {
8146 Named {
8150 name: Ident,
8152 arg: FunctionArgExpr,
8154 operator: FunctionArgOperator,
8156 },
8157 ExprNamed {
8161 name: Expr,
8163 arg: FunctionArgExpr,
8165 operator: FunctionArgOperator,
8167 },
8168 Unnamed(FunctionArgExpr),
8170}
8171
8172impl fmt::Display for FunctionArg {
8173 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8174 match self {
8175 FunctionArg::Named {
8176 name,
8177 arg,
8178 operator,
8179 } => fmt_named_function_arg(f, name, operator, arg),
8180 FunctionArg::ExprNamed {
8181 name,
8182 arg,
8183 operator,
8184 } => fmt_named_function_arg(f, name, operator, arg),
8185 FunctionArg::Unnamed(unnamed_arg) => write!(f, "{unnamed_arg}"),
8186 }
8187 }
8188}
8189
8190fn starts_with_operator_char(mut expr: &Expr) -> bool {
8194 loop {
8195 match expr {
8196 Expr::UnaryOp { op, .. } => return !matches!(op, UnaryOperator::Not),
8197 Expr::BinaryOp { left, .. } => expr = left,
8198 _ => return false,
8199 }
8200 }
8201}
8202
8203fn fmt_named_function_arg(
8206 f: &mut fmt::Formatter,
8207 name: &impl fmt::Display,
8208 operator: &FunctionArgOperator,
8209 arg: &FunctionArgExpr,
8210) -> fmt::Result {
8211 match operator {
8212 FunctionArgOperator::Space => write!(f, "{name} {arg}"),
8213 _ => write!(f, "{name} {operator} {arg}"),
8214 }
8215}
8216
8217#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8218#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8219#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8220pub enum CloseCursor {
8222 All,
8224 Specific {
8226 name: Ident,
8228 },
8229}
8230
8231impl fmt::Display for CloseCursor {
8232 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8233 match self {
8234 CloseCursor::All => write!(f, "ALL"),
8235 CloseCursor::Specific { name } => write!(f, "{name}"),
8236 }
8237 }
8238}
8239
8240#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8242#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8243#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8244pub struct DropDomain {
8245 pub if_exists: bool,
8247 pub name: ObjectName,
8249 pub drop_behavior: Option<DropBehavior>,
8251}
8252
8253#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8257#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8258#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8259pub struct TypedString {
8260 pub data_type: DataType,
8262 pub value: ValueWithSpan,
8265 pub uses_odbc_syntax: bool,
8276}
8277
8278impl fmt::Display for TypedString {
8279 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8280 let data_type = &self.data_type;
8281 let value = &self.value;
8282 match self.uses_odbc_syntax {
8283 false => {
8284 write!(f, "{data_type}")?;
8285 write!(f, " {value}")
8286 }
8287 true => {
8288 let prefix = match data_type {
8289 DataType::Date => "d",
8290 DataType::Time(..) => "t",
8291 DataType::Timestamp(..) => "ts",
8292 _ => "?",
8293 };
8294 write!(f, "{{{prefix} {value}}}")
8295 }
8296 }
8297 }
8298}
8299
8300#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8302#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8303#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8304pub struct Function {
8305 pub name: ObjectName,
8307 pub uses_odbc_syntax: bool,
8316 pub parameters: FunctionArguments,
8326 pub args: FunctionArguments,
8329 pub within_group: Vec<OrderByExpr>,
8337 pub filter: Option<Box<Expr>>,
8339 pub null_treatment: Option<NullTreatment>,
8348 pub over: Option<WindowType>,
8350}
8351
8352impl fmt::Display for Function {
8353 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8354 if self.uses_odbc_syntax {
8355 write!(f, "{{fn ")?;
8356 }
8357
8358 write!(f, "{}{}{}", self.name, self.parameters, self.args)?;
8359
8360 if !self.within_group.is_empty() {
8361 write!(
8362 f,
8363 " WITHIN GROUP (ORDER BY {})",
8364 display_comma_separated(&self.within_group)
8365 )?;
8366 }
8367
8368 if let Some(filter_cond) = &self.filter {
8369 write!(f, " FILTER (WHERE {filter_cond})")?;
8370 }
8371
8372 if let Some(null_treatment) = &self.null_treatment {
8373 write!(f, " {null_treatment}")?;
8374 }
8375
8376 if let Some(o) = &self.over {
8377 f.write_str(" OVER ")?;
8378 o.fmt(f)?;
8379 }
8380
8381 if self.uses_odbc_syntax {
8382 write!(f, "}}")?;
8383 }
8384
8385 Ok(())
8386 }
8387}
8388
8389#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8391#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8392#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8393pub enum FunctionArguments {
8394 None,
8397 Subquery(Box<Query>),
8400 List(FunctionArgumentList),
8403}
8404
8405impl fmt::Display for FunctionArguments {
8406 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8407 match self {
8408 FunctionArguments::None => Ok(()),
8409 FunctionArguments::Subquery(query) => write!(f, "({query})"),
8410 FunctionArguments::List(args) => write!(f, "({args})"),
8411 }
8412 }
8413}
8414
8415#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8417#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8418#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8419pub struct FunctionArgumentList {
8420 pub duplicate_treatment: Option<DuplicateTreatment>,
8422 pub args: Vec<FunctionArg>,
8424 pub clauses: Vec<FunctionArgumentClause>,
8426}
8427
8428impl fmt::Display for FunctionArgumentList {
8429 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8430 if let Some(duplicate_treatment) = self.duplicate_treatment {
8431 write!(f, "{duplicate_treatment} ")?;
8432 }
8433 write!(f, "{}", display_comma_separated(&self.args))?;
8434 if !self.clauses.is_empty() {
8435 if !self.args.is_empty() {
8436 write!(f, " ")?;
8437 }
8438 write!(f, "{}", display_separated(&self.clauses, " "))?;
8439 }
8440 Ok(())
8441 }
8442}
8443
8444#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8445#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8446#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8447pub enum FunctionArgumentClause {
8449 IgnoreOrRespectNulls(NullTreatment),
8458 Where(Expr),
8465 OrderBy(Vec<OrderByExpr>),
8469 Limit(Expr),
8471 OnOverflow(ListAggOnOverflow),
8475 Having(HavingBound),
8484 Separator(ValueWithSpan),
8488 JsonNullClause(JsonNullClause),
8494 JsonReturningClause(JsonReturningClause),
8498}
8499
8500impl fmt::Display for FunctionArgumentClause {
8501 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8502 match self {
8503 FunctionArgumentClause::IgnoreOrRespectNulls(null_treatment) => {
8504 write!(f, "{null_treatment}")
8505 }
8506 FunctionArgumentClause::Where(expr) => write!(f, "WHERE {expr}"),
8507 FunctionArgumentClause::OrderBy(order_by) => {
8508 write!(f, "ORDER BY {}", display_comma_separated(order_by))
8509 }
8510 FunctionArgumentClause::Limit(limit) => write!(f, "LIMIT {limit}"),
8511 FunctionArgumentClause::OnOverflow(on_overflow) => write!(f, "{on_overflow}"),
8512 FunctionArgumentClause::Having(bound) => write!(f, "{bound}"),
8513 FunctionArgumentClause::Separator(sep) => write!(f, "SEPARATOR {sep}"),
8514 FunctionArgumentClause::JsonNullClause(null_clause) => write!(f, "{null_clause}"),
8515 FunctionArgumentClause::JsonReturningClause(returning_clause) => {
8516 write!(f, "{returning_clause}")
8517 }
8518 }
8519 }
8520}
8521
8522#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8524#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8525#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8526pub struct Method {
8527 pub expr: Box<Expr>,
8529 pub method_chain: Vec<Function>,
8532}
8533
8534impl fmt::Display for Method {
8535 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8536 write!(
8537 f,
8538 "{}.{}",
8539 self.expr,
8540 display_separated(&self.method_chain, ".")
8541 )
8542 }
8543}
8544
8545#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8546#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8547#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8548pub enum DuplicateTreatment {
8550 Distinct,
8552 All,
8554}
8555
8556impl fmt::Display for DuplicateTreatment {
8557 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8558 match self {
8559 DuplicateTreatment::Distinct => write!(f, "DISTINCT"),
8560 DuplicateTreatment::All => write!(f, "ALL"),
8561 }
8562 }
8563}
8564
8565#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8566#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8567#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8568pub enum AnalyzeFormatKind {
8570 Keyword(AnalyzeFormat),
8572 Assignment(AnalyzeFormat),
8574}
8575
8576impl fmt::Display for AnalyzeFormatKind {
8577 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
8578 match self {
8579 AnalyzeFormatKind::Keyword(format) => write!(f, "FORMAT {format}"),
8580 AnalyzeFormatKind::Assignment(format) => write!(f, "FORMAT={format}"),
8581 }
8582 }
8583}
8584
8585#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8586#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8587#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8588pub enum AnalyzeFormat {
8590 TEXT,
8592 GRAPHVIZ,
8594 JSON,
8596 TRADITIONAL,
8598 TREE,
8600}
8601
8602#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
8604#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8605#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8606pub enum JsonPredicateType {
8607 Value,
8609 Scalar,
8611 Array,
8613 Object,
8615}
8616
8617impl fmt::Display for JsonPredicateType {
8618 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8619 match self {
8620 JsonPredicateType::Value => write!(f, "VALUE"),
8621 JsonPredicateType::Scalar => write!(f, "SCALAR"),
8622 JsonPredicateType::Array => write!(f, "ARRAY"),
8623 JsonPredicateType::Object => write!(f, "OBJECT"),
8624 }
8625 }
8626}
8627
8628#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
8630#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8631#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8632pub enum JsonKeyUniqueness {
8633 WithUniqueKeys,
8635 WithoutUniqueKeys,
8637}
8638
8639impl fmt::Display for JsonKeyUniqueness {
8640 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8641 match self {
8642 JsonKeyUniqueness::WithUniqueKeys => write!(f, "WITH UNIQUE KEYS"),
8643 JsonKeyUniqueness::WithoutUniqueKeys => write!(f, "WITHOUT UNIQUE KEYS"),
8644 }
8645 }
8646}
8647
8648impl fmt::Display for AnalyzeFormat {
8649 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
8650 f.write_str(match self {
8651 AnalyzeFormat::TEXT => "TEXT",
8652 AnalyzeFormat::GRAPHVIZ => "GRAPHVIZ",
8653 AnalyzeFormat::JSON => "JSON",
8654 AnalyzeFormat::TRADITIONAL => "TRADITIONAL",
8655 AnalyzeFormat::TREE => "TREE",
8656 })
8657 }
8658}
8659
8660#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8662#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8663#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8664pub enum FileFormat {
8665 TEXTFILE,
8667 SEQUENCEFILE,
8669 ORC,
8671 PARQUET,
8673 AVRO,
8675 RCFILE,
8677 JSONFILE,
8679}
8680
8681impl fmt::Display for FileFormat {
8682 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8683 use self::FileFormat::*;
8684 f.write_str(match self {
8685 TEXTFILE => "TEXTFILE",
8686 SEQUENCEFILE => "SEQUENCEFILE",
8687 ORC => "ORC",
8688 PARQUET => "PARQUET",
8689 AVRO => "AVRO",
8690 RCFILE => "RCFILE",
8691 JSONFILE => "JSONFILE",
8692 })
8693 }
8694}
8695
8696#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8698#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8699#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8700pub enum ListAggOnOverflow {
8701 Error,
8703
8704 Truncate {
8706 filler: Option<Box<Expr>>,
8708 with_count: bool,
8710 },
8711}
8712
8713impl fmt::Display for ListAggOnOverflow {
8714 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8715 write!(f, "ON OVERFLOW")?;
8716 match self {
8717 ListAggOnOverflow::Error => write!(f, " ERROR"),
8718 ListAggOnOverflow::Truncate { filler, with_count } => {
8719 write!(f, " TRUNCATE")?;
8720 if let Some(filler) = filler {
8721 write!(f, " {filler}")?;
8722 }
8723 if *with_count {
8724 write!(f, " WITH")?;
8725 } else {
8726 write!(f, " WITHOUT")?;
8727 }
8728 write!(f, " COUNT")
8729 }
8730 }
8731 }
8732}
8733
8734#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8736#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8737#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8738pub struct HavingBound(pub HavingBoundKind, pub Expr);
8739
8740impl fmt::Display for HavingBound {
8741 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8742 write!(f, "HAVING {} {}", self.0, self.1)
8743 }
8744}
8745
8746#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8747#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8748#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8749pub enum HavingBoundKind {
8751 Min,
8753 Max,
8755}
8756
8757impl fmt::Display for HavingBoundKind {
8758 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8759 match self {
8760 HavingBoundKind::Min => write!(f, "MIN"),
8761 HavingBoundKind::Max => write!(f, "MAX"),
8762 }
8763 }
8764}
8765
8766#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8767#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8768#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8769pub enum ObjectType {
8771 Collation,
8773 Table,
8775 View,
8777 MaterializedView,
8779 Index,
8781 Schema,
8783 Database,
8785 Role,
8787 Sequence,
8789 Stage,
8791 Type,
8793 User,
8795 Stream,
8797 Warehouse,
8799}
8800
8801impl fmt::Display for ObjectType {
8802 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8803 f.write_str(match self {
8804 ObjectType::Collation => "COLLATION",
8805 ObjectType::Table => "TABLE",
8806 ObjectType::View => "VIEW",
8807 ObjectType::MaterializedView => "MATERIALIZED VIEW",
8808 ObjectType::Index => "INDEX",
8809 ObjectType::Schema => "SCHEMA",
8810 ObjectType::Database => "DATABASE",
8811 ObjectType::Role => "ROLE",
8812 ObjectType::Sequence => "SEQUENCE",
8813 ObjectType::Stage => "STAGE",
8814 ObjectType::Type => "TYPE",
8815 ObjectType::User => "USER",
8816 ObjectType::Stream => "STREAM",
8817 ObjectType::Warehouse => "WAREHOUSE",
8818 })
8819 }
8820}
8821
8822#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8823#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8824#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8825pub enum KillType {
8827 Connection,
8829 Query,
8831 Mutation,
8833}
8834
8835impl fmt::Display for KillType {
8836 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8837 f.write_str(match self {
8838 KillType::Connection => "CONNECTION",
8840 KillType::Query => "QUERY",
8841 KillType::Mutation => "MUTATION",
8843 })
8844 }
8845}
8846
8847#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8848#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8849#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8850pub enum HiveDistributionStyle {
8852 PARTITIONED {
8854 columns: Vec<ColumnDef>,
8856 },
8857 SKEWED {
8859 columns: Vec<ColumnDef>,
8861 on: Vec<ColumnDef>,
8863 stored_as_directories: bool,
8865 },
8866 NONE,
8868}
8869
8870#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8871#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8872#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8873pub enum HiveRowFormat {
8875 SERDE {
8877 class: String,
8879 },
8880 DELIMITED {
8882 delimiters: Vec<HiveRowDelimiter>,
8884 },
8885}
8886
8887#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8888#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8889#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8890pub struct HiveLoadDataFormat {
8892 pub serde: Expr,
8894 pub input_format: Expr,
8896}
8897
8898#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8899#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8900#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8901pub struct HiveRowDelimiter {
8903 pub delimiter: HiveDelimiter,
8905 pub char: Ident,
8907}
8908
8909impl fmt::Display for HiveRowDelimiter {
8910 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8911 write!(f, "{} ", self.delimiter)?;
8912 write!(f, "{}", self.char)
8913 }
8914}
8915
8916#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8917#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8918#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8919pub enum HiveDelimiter {
8921 FieldsTerminatedBy,
8923 FieldsEscapedBy,
8925 CollectionItemsTerminatedBy,
8927 MapKeysTerminatedBy,
8929 LinesTerminatedBy,
8931 NullDefinedAs,
8933}
8934
8935impl fmt::Display for HiveDelimiter {
8936 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8937 use HiveDelimiter::*;
8938 f.write_str(match self {
8939 FieldsTerminatedBy => "FIELDS TERMINATED BY",
8940 FieldsEscapedBy => "ESCAPED BY",
8941 CollectionItemsTerminatedBy => "COLLECTION ITEMS TERMINATED BY",
8942 MapKeysTerminatedBy => "MAP KEYS TERMINATED BY",
8943 LinesTerminatedBy => "LINES TERMINATED BY",
8944 NullDefinedAs => "NULL DEFINED AS",
8945 })
8946 }
8947}
8948
8949#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8950#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8951#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8952pub enum HiveDescribeFormat {
8954 Extended,
8956 Formatted,
8958}
8959
8960impl fmt::Display for HiveDescribeFormat {
8961 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8962 use HiveDescribeFormat::*;
8963 f.write_str(match self {
8964 Extended => "EXTENDED",
8965 Formatted => "FORMATTED",
8966 })
8967 }
8968}
8969
8970#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8971#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8972#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8973pub enum DescribeAlias {
8975 Describe,
8977 Explain,
8979 Desc,
8981}
8982
8983impl fmt::Display for DescribeAlias {
8984 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8985 use DescribeAlias::*;
8986 f.write_str(match self {
8987 Describe => "DESCRIBE",
8988 Explain => "EXPLAIN",
8989 Desc => "DESC",
8990 })
8991 }
8992}
8993
8994#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8995#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8996#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8997#[allow(clippy::large_enum_variant)]
8998pub enum HiveIOFormat {
9000 IOF {
9002 input_format: Expr,
9004 output_format: Expr,
9006 },
9007 FileFormat {
9009 format: FileFormat,
9011 },
9012 Using {
9018 format: Ident,
9020 },
9021}
9022
9023#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Default)]
9024#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9025#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9026pub struct HiveFormat {
9028 pub row_format: Option<HiveRowFormat>,
9030 pub serde_properties: Option<Vec<SqlOption>>,
9032 pub storage: Option<HiveIOFormat>,
9034 pub location: Option<String>,
9036}
9037
9038#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9039#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9040#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9041pub struct ClusteredIndex {
9043 pub name: Ident,
9045 pub asc: Option<bool>,
9047}
9048
9049impl fmt::Display for ClusteredIndex {
9050 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9051 write!(f, "{}", self.name)?;
9052 match self.asc {
9053 Some(true) => write!(f, " ASC"),
9054 Some(false) => write!(f, " DESC"),
9055 _ => Ok(()),
9056 }
9057 }
9058}
9059
9060#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9061#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9062#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9063pub enum TableOptionsClustered {
9065 ColumnstoreIndex,
9067 ColumnstoreIndexOrder(Vec<Ident>),
9069 Index(Vec<ClusteredIndex>),
9071}
9072
9073impl fmt::Display for TableOptionsClustered {
9074 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9075 match self {
9076 TableOptionsClustered::ColumnstoreIndex => {
9077 write!(f, "CLUSTERED COLUMNSTORE INDEX")
9078 }
9079 TableOptionsClustered::ColumnstoreIndexOrder(values) => {
9080 write!(
9081 f,
9082 "CLUSTERED COLUMNSTORE INDEX ORDER ({})",
9083 display_comma_separated(values)
9084 )
9085 }
9086 TableOptionsClustered::Index(values) => {
9087 write!(f, "CLUSTERED INDEX ({})", display_comma_separated(values))
9088 }
9089 }
9090 }
9091}
9092
9093#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
9095#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9096#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9097pub enum PartitionRangeDirection {
9098 Left,
9100 Right,
9102}
9103
9104#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9105#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9106#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9107pub enum SqlOption {
9109 Clustered(TableOptionsClustered),
9113 Ident(Ident),
9117 KeyValue {
9121 key: Ident,
9123 value: Expr,
9125 },
9126 Partition {
9133 column_name: Ident,
9135 range_direction: Option<PartitionRangeDirection>,
9137 for_values: Vec<Expr>,
9139 },
9140 Comment(CommentDef),
9142 TableSpace(TablespaceOption),
9145 NamedParenthesizedList(NamedParenthesizedList),
9152}
9153
9154impl fmt::Display for SqlOption {
9155 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9156 match self {
9157 SqlOption::Clustered(c) => write!(f, "{c}"),
9158 SqlOption::Ident(ident) => {
9159 write!(f, "{ident}")
9160 }
9161 SqlOption::KeyValue { key: name, value } => {
9162 write!(f, "{name} = {value}")
9163 }
9164 SqlOption::Partition {
9165 column_name,
9166 range_direction,
9167 for_values,
9168 } => {
9169 let direction = match range_direction {
9170 Some(PartitionRangeDirection::Left) => " LEFT",
9171 Some(PartitionRangeDirection::Right) => " RIGHT",
9172 None => "",
9173 };
9174
9175 write!(
9176 f,
9177 "PARTITION ({} RANGE{} FOR VALUES ({}))",
9178 column_name,
9179 direction,
9180 display_comma_separated(for_values)
9181 )
9182 }
9183 SqlOption::TableSpace(tablespace_option) => {
9184 write!(f, "TABLESPACE {}", tablespace_option.name)?;
9185 match tablespace_option.storage {
9186 Some(StorageType::Disk) => write!(f, " STORAGE DISK"),
9187 Some(StorageType::Memory) => write!(f, " STORAGE MEMORY"),
9188 None => Ok(()),
9189 }
9190 }
9191 SqlOption::Comment(comment) => match comment {
9192 CommentDef::WithEq(comment) => {
9193 write!(f, "COMMENT = '{comment}'")
9194 }
9195 CommentDef::WithoutEq(comment) => {
9196 write!(f, "COMMENT '{comment}'")
9197 }
9198 },
9199 SqlOption::NamedParenthesizedList(value) => {
9200 write!(f, "{} = ", value.key)?;
9201 if let Some(key) = &value.name {
9202 write!(f, "{key}")?;
9203 }
9204 if !value.values.is_empty() {
9205 write!(f, "({})", display_comma_separated(&value.values))?
9206 }
9207 Ok(())
9208 }
9209 }
9210 }
9211}
9212
9213#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
9214#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9215#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9216pub enum StorageType {
9218 Disk,
9220 Memory,
9222}
9223
9224#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
9225#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9226#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9227pub struct TablespaceOption {
9230 pub name: String,
9232 pub storage: Option<StorageType>,
9234}
9235
9236#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9237#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9238#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9239pub struct SecretOption {
9241 pub key: Ident,
9243 pub value: Ident,
9245}
9246
9247impl fmt::Display for SecretOption {
9248 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9249 write!(f, "{} {}", self.key, self.value)
9250 }
9251}
9252
9253#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9257#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9258#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9259pub struct CreateServerStatement {
9260 pub name: ObjectName,
9262 pub if_not_exists: bool,
9264 pub server_type: Option<Ident>,
9266 pub version: Option<Ident>,
9268 pub foreign_data_wrapper: ObjectName,
9270 pub options: Option<Vec<CreateServerOption>>,
9272}
9273
9274impl fmt::Display for CreateServerStatement {
9275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9276 let CreateServerStatement {
9277 name,
9278 if_not_exists,
9279 server_type,
9280 version,
9281 foreign_data_wrapper,
9282 options,
9283 } = self;
9284
9285 write!(
9286 f,
9287 "CREATE SERVER {if_not_exists}{name} ",
9288 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
9289 )?;
9290
9291 if let Some(st) = server_type {
9292 write!(f, "TYPE {st} ")?;
9293 }
9294
9295 if let Some(v) = version {
9296 write!(f, "VERSION {v} ")?;
9297 }
9298
9299 write!(f, "FOREIGN DATA WRAPPER {foreign_data_wrapper}")?;
9300
9301 if let Some(o) = options {
9302 write!(f, " OPTIONS ({o})", o = display_comma_separated(o))?;
9303 }
9304
9305 Ok(())
9306 }
9307}
9308
9309#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9311#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9312#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9313pub struct CreateServerOption {
9314 pub key: Ident,
9316 pub value: Ident,
9318}
9319
9320impl fmt::Display for CreateServerOption {
9321 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9322 write!(f, "{} {}", self.key, self.value)
9323 }
9324}
9325
9326#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9327#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9328#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9329pub enum AttachDuckDBDatabaseOption {
9331 ReadOnly(Option<bool>),
9333 Type(Ident),
9335}
9336
9337impl fmt::Display for AttachDuckDBDatabaseOption {
9338 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9339 match self {
9340 AttachDuckDBDatabaseOption::ReadOnly(Some(true)) => write!(f, "READ_ONLY true"),
9341 AttachDuckDBDatabaseOption::ReadOnly(Some(false)) => write!(f, "READ_ONLY false"),
9342 AttachDuckDBDatabaseOption::ReadOnly(None) => write!(f, "READ_ONLY"),
9343 AttachDuckDBDatabaseOption::Type(t) => write!(f, "TYPE {t}"),
9344 }
9345 }
9346}
9347
9348#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9349#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9350#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9351pub enum TransactionMode {
9353 AccessMode(TransactionAccessMode),
9355 IsolationLevel(TransactionIsolationLevel),
9357}
9358
9359impl fmt::Display for TransactionMode {
9360 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9361 use TransactionMode::*;
9362 match self {
9363 AccessMode(access_mode) => write!(f, "{access_mode}"),
9364 IsolationLevel(iso_level) => write!(f, "ISOLATION LEVEL {iso_level}"),
9365 }
9366 }
9367}
9368
9369#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9370#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9371#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9372pub enum TransactionAccessMode {
9374 ReadOnly,
9376 ReadWrite,
9378}
9379
9380impl fmt::Display for TransactionAccessMode {
9381 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9382 use TransactionAccessMode::*;
9383 f.write_str(match self {
9384 ReadOnly => "READ ONLY",
9385 ReadWrite => "READ WRITE",
9386 })
9387 }
9388}
9389
9390#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9391#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9392#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9393pub enum TransactionIsolationLevel {
9395 ReadUncommitted,
9397 ReadCommitted,
9399 RepeatableRead,
9401 Serializable,
9403 Snapshot,
9405}
9406
9407impl fmt::Display for TransactionIsolationLevel {
9408 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9409 use TransactionIsolationLevel::*;
9410 f.write_str(match self {
9411 ReadUncommitted => "READ UNCOMMITTED",
9412 ReadCommitted => "READ COMMITTED",
9413 RepeatableRead => "REPEATABLE READ",
9414 Serializable => "SERIALIZABLE",
9415 Snapshot => "SNAPSHOT",
9416 })
9417 }
9418}
9419
9420#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9425#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9426#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9427pub enum TransactionModifier {
9428 Deferred,
9430 Immediate,
9432 Exclusive,
9434 Try,
9436 Catch,
9438}
9439
9440impl fmt::Display for TransactionModifier {
9441 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9442 use TransactionModifier::*;
9443 f.write_str(match self {
9444 Deferred => "DEFERRED",
9445 Immediate => "IMMEDIATE",
9446 Exclusive => "EXCLUSIVE",
9447 Try => "TRY",
9448 Catch => "CATCH",
9449 })
9450 }
9451}
9452
9453#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9454#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9455#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9456pub enum ShowStatementFilter {
9458 Like(String),
9460 ILike(String),
9462 Where(Expr),
9464 NoKeyword(String),
9466}
9467
9468impl fmt::Display for ShowStatementFilter {
9469 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9470 use ShowStatementFilter::*;
9471 match self {
9472 Like(pattern) => write!(f, "LIKE '{}'", value::escape_single_quote_string(pattern)),
9473 ILike(pattern) => write!(f, "ILIKE {}", value::escape_single_quote_string(pattern)),
9474 Where(expr) => write!(f, "WHERE {expr}"),
9475 NoKeyword(pattern) => write!(f, "'{}'", value::escape_single_quote_string(pattern)),
9476 }
9477 }
9478}
9479
9480#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9481#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9482#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9483pub enum ShowStatementInClause {
9485 IN,
9487 FROM,
9489}
9490
9491impl fmt::Display for ShowStatementInClause {
9492 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9493 use ShowStatementInClause::*;
9494 match self {
9495 FROM => write!(f, "FROM"),
9496 IN => write!(f, "IN"),
9497 }
9498 }
9499}
9500
9501#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9506#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9507#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9508pub enum SqliteOnConflict {
9509 Rollback,
9511 Abort,
9513 Fail,
9515 Ignore,
9517 Replace,
9519}
9520
9521impl fmt::Display for SqliteOnConflict {
9522 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9523 use SqliteOnConflict::*;
9524 match self {
9525 Rollback => write!(f, "OR ROLLBACK"),
9526 Abort => write!(f, "OR ABORT"),
9527 Fail => write!(f, "OR FAIL"),
9528 Ignore => write!(f, "OR IGNORE"),
9529 Replace => write!(f, "OR REPLACE"),
9530 }
9531 }
9532}
9533
9534#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9540#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9541#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9542pub enum MysqlInsertPriority {
9543 LowPriority,
9545 Delayed,
9547 HighPriority,
9549}
9550
9551impl fmt::Display for crate::ast::MysqlInsertPriority {
9552 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9553 use MysqlInsertPriority::*;
9554 match self {
9555 LowPriority => write!(f, "LOW_PRIORITY"),
9556 Delayed => write!(f, "DELAYED"),
9557 HighPriority => write!(f, "HIGH_PRIORITY"),
9558 }
9559 }
9560}
9561
9562#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9563#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9564#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9565pub enum CopySource {
9567 Table {
9569 table_name: ObjectName,
9571 columns: Vec<Ident>,
9574 },
9575 Query(Box<Query>),
9577}
9578
9579#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9580#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9581#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9582pub enum CopyTarget {
9584 Stdin,
9586 Stdout,
9588 File {
9590 filename: String,
9592 },
9593 Program {
9595 command: String,
9597 },
9598}
9599
9600impl fmt::Display for CopyTarget {
9601 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9602 use CopyTarget::*;
9603 match self {
9604 Stdin => write!(f, "STDIN"),
9605 Stdout => write!(f, "STDOUT"),
9606 File { filename } => write!(f, "'{}'", value::escape_single_quote_string(filename)),
9607 Program { command } => write!(
9608 f,
9609 "PROGRAM '{}'",
9610 value::escape_single_quote_string(command)
9611 ),
9612 }
9613 }
9614}
9615
9616#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9617#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9618#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9619pub enum OnCommit {
9621 DeleteRows,
9623 PreserveRows,
9625 Drop,
9627}
9628
9629#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9633#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9634#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9635pub enum CopyOption {
9636 Format(Ident),
9638 Freeze(bool),
9640 Delimiter(char),
9642 Null(String),
9644 Header(bool),
9646 Quote(char),
9648 Escape(char),
9650 ForceQuote(Vec<Ident>),
9652 ForceNotNull(Vec<Ident>),
9654 ForceNull(Vec<Ident>),
9656 Encoding(String),
9658}
9659
9660impl fmt::Display for CopyOption {
9661 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9662 use CopyOption::*;
9663 match self {
9664 Format(name) => write!(f, "FORMAT {name}"),
9665 Freeze(true) => write!(f, "FREEZE"),
9666 Freeze(false) => write!(f, "FREEZE FALSE"),
9667 Delimiter(char) => write!(f, "DELIMITER '{char}'"),
9668 Null(string) => write!(f, "NULL '{}'", value::escape_single_quote_string(string)),
9669 Header(true) => write!(f, "HEADER"),
9670 Header(false) => write!(f, "HEADER FALSE"),
9671 Quote(char) => write!(f, "QUOTE '{char}'"),
9672 Escape(char) => write!(f, "ESCAPE '{char}'"),
9673 ForceQuote(columns) => write!(f, "FORCE_QUOTE ({})", display_comma_separated(columns)),
9674 ForceNotNull(columns) => {
9675 write!(f, "FORCE_NOT_NULL ({})", display_comma_separated(columns))
9676 }
9677 ForceNull(columns) => write!(f, "FORCE_NULL ({})", display_comma_separated(columns)),
9678 Encoding(name) => write!(f, "ENCODING '{}'", value::escape_single_quote_string(name)),
9679 }
9680 }
9681}
9682
9683#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9688#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9689#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9690pub enum CopyLegacyOption {
9691 AcceptAnyDate,
9693 AcceptInvChars(Option<String>),
9695 AddQuotes,
9697 AllowOverwrite,
9699 Binary,
9701 BlankAsNull,
9703 Bzip2,
9705 CleanPath,
9707 CompUpdate {
9709 preset: bool,
9711 enabled: Option<bool>,
9713 },
9714 Csv(Vec<CopyLegacyCsvOption>),
9716 DateFormat(Option<String>),
9718 Delimiter(char),
9720 EmptyAsNull,
9722 Encrypted {
9724 auto: bool,
9726 },
9727 Escape,
9729 Extension(String),
9731 FixedWidth(String),
9733 Gzip,
9735 Header,
9737 IamRole(IamRoleKind),
9739 IgnoreHeader(u64),
9741 Json(Option<String>),
9743 Manifest {
9745 verbose: bool,
9747 },
9748 MaxFileSize(FileSize),
9750 Null(String),
9752 Parallel(Option<bool>),
9754 Parquet,
9756 PartitionBy(UnloadPartitionBy),
9758 Region(String),
9760 RemoveQuotes,
9762 RowGroupSize(FileSize),
9764 StatUpdate(Option<bool>),
9766 TimeFormat(Option<String>),
9768 TruncateColumns,
9770 Zstd,
9772 Credentials(String),
9775}
9776
9777impl fmt::Display for CopyLegacyOption {
9778 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9779 use CopyLegacyOption::*;
9780 match self {
9781 AcceptAnyDate => write!(f, "ACCEPTANYDATE"),
9782 AcceptInvChars(ch) => {
9783 write!(f, "ACCEPTINVCHARS")?;
9784 if let Some(ch) = ch {
9785 write!(f, " '{}'", value::escape_single_quote_string(ch))?;
9786 }
9787 Ok(())
9788 }
9789 AddQuotes => write!(f, "ADDQUOTES"),
9790 AllowOverwrite => write!(f, "ALLOWOVERWRITE"),
9791 Binary => write!(f, "BINARY"),
9792 BlankAsNull => write!(f, "BLANKSASNULL"),
9793 Bzip2 => write!(f, "BZIP2"),
9794 CleanPath => write!(f, "CLEANPATH"),
9795 CompUpdate { preset, enabled } => {
9796 write!(f, "COMPUPDATE")?;
9797 if *preset {
9798 write!(f, " PRESET")?;
9799 } else if let Some(enabled) = enabled {
9800 write!(
9801 f,
9802 "{}",
9803 match enabled {
9804 true => " TRUE",
9805 false => " FALSE",
9806 }
9807 )?;
9808 }
9809 Ok(())
9810 }
9811 Csv(opts) => {
9812 write!(f, "CSV")?;
9813 if !opts.is_empty() {
9814 write!(f, " {}", display_separated(opts, " "))?;
9815 }
9816 Ok(())
9817 }
9818 DateFormat(fmt) => {
9819 write!(f, "DATEFORMAT")?;
9820 if let Some(fmt) = fmt {
9821 write!(f, " '{}'", value::escape_single_quote_string(fmt))?;
9822 }
9823 Ok(())
9824 }
9825 Delimiter(char) => write!(f, "DELIMITER '{char}'"),
9826 EmptyAsNull => write!(f, "EMPTYASNULL"),
9827 Encrypted { auto } => write!(f, "ENCRYPTED{}", if *auto { " AUTO" } else { "" }),
9828 Escape => write!(f, "ESCAPE"),
9829 Extension(ext) => write!(f, "EXTENSION '{}'", value::escape_single_quote_string(ext)),
9830 FixedWidth(spec) => write!(
9831 f,
9832 "FIXEDWIDTH '{}'",
9833 value::escape_single_quote_string(spec)
9834 ),
9835 Gzip => write!(f, "GZIP"),
9836 Header => write!(f, "HEADER"),
9837 IamRole(role) => write!(f, "IAM_ROLE {role}"),
9838 IgnoreHeader(num_rows) => write!(f, "IGNOREHEADER {num_rows}"),
9839 Json(opt) => {
9840 write!(f, "JSON")?;
9841 if let Some(opt) = opt {
9842 write!(f, " AS '{}'", value::escape_single_quote_string(opt))?;
9843 }
9844 Ok(())
9845 }
9846 Manifest { verbose } => write!(f, "MANIFEST{}", if *verbose { " VERBOSE" } else { "" }),
9847 MaxFileSize(file_size) => write!(f, "MAXFILESIZE {file_size}"),
9848 Null(string) => write!(f, "NULL '{}'", value::escape_single_quote_string(string)),
9849 Parallel(enabled) => {
9850 write!(
9851 f,
9852 "PARALLEL{}",
9853 match enabled {
9854 Some(true) => " TRUE",
9855 Some(false) => " FALSE",
9856 _ => "",
9857 }
9858 )
9859 }
9860 Parquet => write!(f, "PARQUET"),
9861 PartitionBy(p) => write!(f, "{p}"),
9862 Region(region) => write!(f, "REGION '{}'", value::escape_single_quote_string(region)),
9863 RemoveQuotes => write!(f, "REMOVEQUOTES"),
9864 RowGroupSize(file_size) => write!(f, "ROWGROUPSIZE {file_size}"),
9865 StatUpdate(enabled) => {
9866 write!(
9867 f,
9868 "STATUPDATE{}",
9869 match enabled {
9870 Some(true) => " TRUE",
9871 Some(false) => " FALSE",
9872 _ => "",
9873 }
9874 )
9875 }
9876 TimeFormat(fmt) => {
9877 write!(f, "TIMEFORMAT")?;
9878 if let Some(fmt) = fmt {
9879 write!(f, " '{}'", value::escape_single_quote_string(fmt))?;
9880 }
9881 Ok(())
9882 }
9883 TruncateColumns => write!(f, "TRUNCATECOLUMNS"),
9884 Zstd => write!(f, "ZSTD"),
9885 Credentials(s) => write!(f, "CREDENTIALS '{}'", value::escape_single_quote_string(s)),
9886 }
9887 }
9888}
9889
9890#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9894#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9895#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9896pub struct FileSize {
9897 pub size: ValueWithSpan,
9899 pub unit: Option<FileSizeUnit>,
9901}
9902
9903impl fmt::Display for FileSize {
9904 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9905 write!(f, "{}", self.size)?;
9906 if let Some(unit) = &self.unit {
9907 write!(f, " {unit}")?;
9908 }
9909 Ok(())
9910 }
9911}
9912
9913#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9915#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9916#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9917pub enum FileSizeUnit {
9918 MB,
9920 GB,
9922}
9923
9924impl fmt::Display for FileSizeUnit {
9925 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9926 match self {
9927 FileSizeUnit::MB => write!(f, "MB"),
9928 FileSizeUnit::GB => write!(f, "GB"),
9929 }
9930 }
9931}
9932
9933#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9939#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9940#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9941pub struct UnloadPartitionBy {
9942 pub columns: Vec<Ident>,
9944 pub include: bool,
9946}
9947
9948impl fmt::Display for UnloadPartitionBy {
9949 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9950 write!(
9951 f,
9952 "PARTITION BY ({}){}",
9953 display_comma_separated(&self.columns),
9954 if self.include { " INCLUDE" } else { "" }
9955 )
9956 }
9957}
9958
9959#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9963#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9964#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9965pub enum IamRoleKind {
9966 Default,
9968 Arn(String),
9970}
9971
9972impl fmt::Display for IamRoleKind {
9973 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9974 match self {
9975 IamRoleKind::Default => write!(f, "DEFAULT"),
9976 IamRoleKind::Arn(arn) => write!(f, "'{arn}'"),
9977 }
9978 }
9979}
9980
9981#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9985#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9986#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9987pub enum CopyLegacyCsvOption {
9988 Header,
9990 Quote(char),
9992 Escape(char),
9994 ForceQuote(Vec<Ident>),
9996 ForceNotNull(Vec<Ident>),
9998}
9999
10000impl fmt::Display for CopyLegacyCsvOption {
10001 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10002 use CopyLegacyCsvOption::*;
10003 match self {
10004 Header => write!(f, "HEADER"),
10005 Quote(char) => write!(f, "QUOTE '{char}'"),
10006 Escape(char) => write!(f, "ESCAPE '{char}'"),
10007 ForceQuote(columns) => write!(f, "FORCE QUOTE {}", display_comma_separated(columns)),
10008 ForceNotNull(columns) => {
10009 write!(f, "FORCE NOT NULL {}", display_comma_separated(columns))
10010 }
10011 }
10012 }
10013}
10014
10015#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10017#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10018#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10019pub enum DiscardObject {
10020 ALL,
10022 PLANS,
10024 SEQUENCES,
10026 TEMP,
10028}
10029
10030impl fmt::Display for DiscardObject {
10031 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10032 match self {
10033 DiscardObject::ALL => f.write_str("ALL"),
10034 DiscardObject::PLANS => f.write_str("PLANS"),
10035 DiscardObject::SEQUENCES => f.write_str("SEQUENCES"),
10036 DiscardObject::TEMP => f.write_str("TEMP"),
10037 }
10038 }
10039}
10040
10041#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10043#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10044#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10045pub enum FlushType {
10046 BinaryLogs,
10048 EngineLogs,
10050 ErrorLogs,
10052 GeneralLogs,
10054 Hosts,
10056 Logs,
10058 Privileges,
10060 OptimizerCosts,
10062 RelayLogs,
10064 SlowLogs,
10066 Status,
10068 UserResources,
10070 Tables,
10072}
10073
10074impl fmt::Display for FlushType {
10075 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10076 match self {
10077 FlushType::BinaryLogs => f.write_str("BINARY LOGS"),
10078 FlushType::EngineLogs => f.write_str("ENGINE LOGS"),
10079 FlushType::ErrorLogs => f.write_str("ERROR LOGS"),
10080 FlushType::GeneralLogs => f.write_str("GENERAL LOGS"),
10081 FlushType::Hosts => f.write_str("HOSTS"),
10082 FlushType::Logs => f.write_str("LOGS"),
10083 FlushType::Privileges => f.write_str("PRIVILEGES"),
10084 FlushType::OptimizerCosts => f.write_str("OPTIMIZER_COSTS"),
10085 FlushType::RelayLogs => f.write_str("RELAY LOGS"),
10086 FlushType::SlowLogs => f.write_str("SLOW LOGS"),
10087 FlushType::Status => f.write_str("STATUS"),
10088 FlushType::UserResources => f.write_str("USER_RESOURCES"),
10089 FlushType::Tables => f.write_str("TABLES"),
10090 }
10091 }
10092}
10093
10094#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10096#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10097#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10098pub enum FlushLocation {
10099 NoWriteToBinlog,
10101 Local,
10103}
10104
10105impl fmt::Display for FlushLocation {
10106 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10107 match self {
10108 FlushLocation::NoWriteToBinlog => f.write_str("NO_WRITE_TO_BINLOG"),
10109 FlushLocation::Local => f.write_str("LOCAL"),
10110 }
10111 }
10112}
10113
10114#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10116#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10117#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10118pub enum ContextModifier {
10119 Local,
10121 Session,
10123 Global,
10125}
10126
10127impl fmt::Display for ContextModifier {
10128 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10129 match self {
10130 Self::Local => {
10131 write!(f, "LOCAL ")
10132 }
10133 Self::Session => {
10134 write!(f, "SESSION ")
10135 }
10136 Self::Global => {
10137 write!(f, "GLOBAL ")
10138 }
10139 }
10140 }
10141}
10142
10143#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10145#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10146pub enum DropFunctionOption {
10147 Restrict,
10149 Cascade,
10151}
10152
10153impl fmt::Display for DropFunctionOption {
10154 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10155 match self {
10156 DropFunctionOption::Restrict => write!(f, "RESTRICT "),
10157 DropFunctionOption::Cascade => write!(f, "CASCADE "),
10158 }
10159 }
10160}
10161
10162#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10164#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10165#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10166pub struct FunctionDesc {
10167 pub name: ObjectName,
10169 pub args: Option<Vec<OperateFunctionArg>>,
10171}
10172
10173impl fmt::Display for FunctionDesc {
10174 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10175 write!(f, "{}", self.name)?;
10176 if let Some(args) = &self.args {
10177 write!(f, "({})", display_comma_separated(args))?;
10178 }
10179 Ok(())
10180 }
10181}
10182
10183#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10185#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10186#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10187pub struct OperateFunctionArg {
10188 pub mode: Option<ArgMode>,
10190 pub name: Option<Ident>,
10192 pub data_type: DataType,
10194 pub default_expr: Option<Expr>,
10196}
10197
10198impl OperateFunctionArg {
10199 pub fn unnamed(data_type: DataType) -> Self {
10201 Self {
10202 mode: None,
10203 name: None,
10204 data_type,
10205 default_expr: None,
10206 }
10207 }
10208
10209 pub fn with_name(name: &str, data_type: DataType) -> Self {
10211 Self {
10212 mode: None,
10213 name: Some(name.into()),
10214 data_type,
10215 default_expr: None,
10216 }
10217 }
10218}
10219
10220impl fmt::Display for OperateFunctionArg {
10221 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10222 if let Some(mode) = &self.mode {
10223 write!(f, "{mode} ")?;
10224 }
10225 if let Some(name) = &self.name {
10226 write!(f, "{name} ")?;
10227 }
10228 write!(f, "{}", self.data_type)?;
10229 if let Some(default_expr) = &self.default_expr {
10230 write!(f, " = {default_expr}")?;
10231 }
10232 Ok(())
10233 }
10234}
10235
10236#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10238#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10239#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10240pub enum ArgMode {
10241 In,
10243 Out,
10245 InOut,
10247 Variadic,
10249}
10250
10251impl fmt::Display for ArgMode {
10252 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10253 match self {
10254 ArgMode::In => write!(f, "IN"),
10255 ArgMode::Out => write!(f, "OUT"),
10256 ArgMode::InOut => write!(f, "INOUT"),
10257 ArgMode::Variadic => write!(f, "VARIADIC"),
10258 }
10259 }
10260}
10261
10262#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10264#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10265#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10266pub enum FunctionBehavior {
10267 Immutable,
10269 Stable,
10271 Volatile,
10273}
10274
10275impl fmt::Display for FunctionBehavior {
10276 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10277 match self {
10278 FunctionBehavior::Immutable => write!(f, "IMMUTABLE"),
10279 FunctionBehavior::Stable => write!(f, "STABLE"),
10280 FunctionBehavior::Volatile => write!(f, "VOLATILE"),
10281 }
10282 }
10283}
10284
10285#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10289#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10290#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10291pub enum FunctionSecurity {
10292 Definer,
10294 Invoker,
10296}
10297
10298impl fmt::Display for FunctionSecurity {
10299 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10300 match self {
10301 FunctionSecurity::Definer => write!(f, "SECURITY DEFINER"),
10302 FunctionSecurity::Invoker => write!(f, "SECURITY INVOKER"),
10303 }
10304 }
10305}
10306
10307#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10311#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10312#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10313pub enum FunctionSetValue {
10314 Default,
10316 Values(Vec<Expr>),
10318 FromCurrent,
10320}
10321
10322#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10326#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10327#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10328pub struct FunctionDefinitionSetParam {
10329 pub name: ObjectName,
10331 pub value: FunctionSetValue,
10333}
10334
10335impl fmt::Display for FunctionDefinitionSetParam {
10336 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10337 write!(f, "SET {} ", self.name)?;
10338 match &self.value {
10339 FunctionSetValue::Default => write!(f, "= DEFAULT"),
10340 FunctionSetValue::Values(values) => {
10341 write!(f, "= {}", display_comma_separated(values))
10342 }
10343 FunctionSetValue::FromCurrent => write!(f, "FROM CURRENT"),
10344 }
10345 }
10346}
10347
10348#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10350#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10351#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10352pub enum FunctionCalledOnNull {
10353 CalledOnNullInput,
10355 ReturnsNullOnNullInput,
10357 Strict,
10359}
10360
10361impl fmt::Display for FunctionCalledOnNull {
10362 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10363 match self {
10364 FunctionCalledOnNull::CalledOnNullInput => write!(f, "CALLED ON NULL INPUT"),
10365 FunctionCalledOnNull::ReturnsNullOnNullInput => write!(f, "RETURNS NULL ON NULL INPUT"),
10366 FunctionCalledOnNull::Strict => write!(f, "STRICT"),
10367 }
10368 }
10369}
10370
10371#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10373#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10374#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10375pub enum FunctionParallel {
10376 Unsafe,
10378 Restricted,
10380 Safe,
10382}
10383
10384impl fmt::Display for FunctionParallel {
10385 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10386 match self {
10387 FunctionParallel::Unsafe => write!(f, "PARALLEL UNSAFE"),
10388 FunctionParallel::Restricted => write!(f, "PARALLEL RESTRICTED"),
10389 FunctionParallel::Safe => write!(f, "PARALLEL SAFE"),
10390 }
10391 }
10392}
10393
10394#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10398#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10399#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10400pub enum FunctionDeterminismSpecifier {
10401 Deterministic,
10403 NotDeterministic,
10405}
10406
10407impl fmt::Display for FunctionDeterminismSpecifier {
10408 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10409 match self {
10410 FunctionDeterminismSpecifier::Deterministic => {
10411 write!(f, "DETERMINISTIC")
10412 }
10413 FunctionDeterminismSpecifier::NotDeterministic => {
10414 write!(f, "NOT DETERMINISTIC")
10415 }
10416 }
10417 }
10418}
10419
10420#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10427#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10428#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10429pub enum CreateFunctionBody {
10430 AsBeforeOptions {
10443 body: Expr,
10445 link_symbol: Option<Expr>,
10454 },
10455 AsAfterOptions(Expr),
10467 AsBeginEnd(BeginEndStatements),
10483 Return(Expr),
10494
10495 AsReturnExpr(Expr),
10506
10507 AsReturnSelect(Select),
10518}
10519
10520#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10521#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10522#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10523pub enum CreateFunctionUsing {
10525 Jar(String),
10527 File(String),
10529 Archive(String),
10531}
10532
10533impl fmt::Display for CreateFunctionUsing {
10534 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10535 write!(f, "USING ")?;
10536 match self {
10537 CreateFunctionUsing::Jar(uri) => write!(f, "JAR '{uri}'"),
10538 CreateFunctionUsing::File(uri) => write!(f, "FILE '{uri}'"),
10539 CreateFunctionUsing::Archive(uri) => write!(f, "ARCHIVE '{uri}'"),
10540 }
10541 }
10542}
10543
10544#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10549#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10550#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10551pub struct MacroArg {
10552 pub name: Ident,
10554 pub default_expr: Option<Expr>,
10556}
10557
10558impl MacroArg {
10559 pub fn new(name: &str) -> Self {
10561 Self {
10562 name: name.into(),
10563 default_expr: None,
10564 }
10565 }
10566}
10567
10568impl fmt::Display for MacroArg {
10569 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10570 write!(f, "{}", self.name)?;
10571 if let Some(default_expr) = &self.default_expr {
10572 write!(f, " := {default_expr}")?;
10573 }
10574 Ok(())
10575 }
10576}
10577
10578#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10579#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10580#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10581pub enum MacroDefinition {
10583 Expr(Expr),
10585 Table(Box<Query>),
10587}
10588
10589impl fmt::Display for MacroDefinition {
10590 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10591 match self {
10592 MacroDefinition::Expr(expr) => write!(f, "{expr}")?,
10593 MacroDefinition::Table(query) => write!(f, "{query}")?,
10594 }
10595 Ok(())
10596 }
10597}
10598
10599#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10603#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10604#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10605pub enum SchemaName {
10606 Simple(ObjectName),
10608 UnnamedAuthorization(Ident),
10610 NamedAuthorization(ObjectName, Ident),
10612}
10613
10614impl fmt::Display for SchemaName {
10615 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10616 match self {
10617 SchemaName::Simple(name) => {
10618 write!(f, "{name}")
10619 }
10620 SchemaName::UnnamedAuthorization(authorization) => {
10621 write!(f, "AUTHORIZATION {authorization}")
10622 }
10623 SchemaName::NamedAuthorization(name, authorization) => {
10624 write!(f, "{name} AUTHORIZATION {authorization}")
10625 }
10626 }
10627 }
10628}
10629
10630#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10634#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10635#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10636pub enum SearchModifier {
10637 InNaturalLanguageMode,
10639 InNaturalLanguageModeWithQueryExpansion,
10641 InBooleanMode,
10643 WithQueryExpansion,
10645}
10646
10647impl fmt::Display for SearchModifier {
10648 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10649 match self {
10650 Self::InNaturalLanguageMode => {
10651 write!(f, "IN NATURAL LANGUAGE MODE")?;
10652 }
10653 Self::InNaturalLanguageModeWithQueryExpansion => {
10654 write!(f, "IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION")?;
10655 }
10656 Self::InBooleanMode => {
10657 write!(f, "IN BOOLEAN MODE")?;
10658 }
10659 Self::WithQueryExpansion => {
10660 write!(f, "WITH QUERY EXPANSION")?;
10661 }
10662 }
10663
10664 Ok(())
10665 }
10666}
10667
10668#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10670#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10671#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10672pub struct LockTable {
10673 pub table: Ident,
10675 pub alias: Option<Ident>,
10677 pub lock_type: LockTableType,
10679}
10680
10681impl fmt::Display for LockTable {
10682 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10683 let Self {
10684 table: tbl_name,
10685 alias,
10686 lock_type,
10687 } = self;
10688
10689 write!(f, "{tbl_name} ")?;
10690 if let Some(alias) = alias {
10691 write!(f, "AS {alias} ")?;
10692 }
10693 write!(f, "{lock_type}")?;
10694 Ok(())
10695 }
10696}
10697
10698#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10699#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10700#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10701pub enum LockTableType {
10703 Read {
10705 local: bool,
10707 },
10708 Write {
10710 low_priority: bool,
10712 },
10713}
10714
10715impl fmt::Display for LockTableType {
10716 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10717 match self {
10718 Self::Read { local } => {
10719 write!(f, "READ")?;
10720 if *local {
10721 write!(f, " LOCAL")?;
10722 }
10723 }
10724 Self::Write { low_priority } => {
10725 if *low_priority {
10726 write!(f, "LOW_PRIORITY ")?;
10727 }
10728 write!(f, "WRITE")?;
10729 }
10730 }
10731
10732 Ok(())
10733 }
10734}
10735
10736#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10737#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10738#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10739pub struct HiveSetLocation {
10741 pub has_set: bool,
10743 pub location: Ident,
10745}
10746
10747impl fmt::Display for HiveSetLocation {
10748 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10749 if self.has_set {
10750 write!(f, "SET ")?;
10751 }
10752 write!(f, "LOCATION {}", self.location)
10753 }
10754}
10755
10756#[allow(clippy::large_enum_variant)]
10758#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10759#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10760#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10761pub enum MySQLColumnPosition {
10763 First,
10765 After(Ident),
10767}
10768
10769impl Display for MySQLColumnPosition {
10770 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10771 match self {
10772 MySQLColumnPosition::First => write!(f, "FIRST"),
10773 MySQLColumnPosition::After(ident) => write!(f, "AFTER {ident}"),
10774 }
10775 }
10776}
10777
10778#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10780#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10781#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10782pub enum CreateViewAlgorithm {
10784 Undefined,
10786 Merge,
10788 TempTable,
10790}
10791
10792impl Display for CreateViewAlgorithm {
10793 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10794 match self {
10795 CreateViewAlgorithm::Undefined => write!(f, "UNDEFINED"),
10796 CreateViewAlgorithm::Merge => write!(f, "MERGE"),
10797 CreateViewAlgorithm::TempTable => write!(f, "TEMPTABLE"),
10798 }
10799 }
10800}
10801#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10803#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10804#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10805pub enum CreateViewSecurity {
10807 Definer,
10809 Invoker,
10811}
10812
10813impl Display for CreateViewSecurity {
10814 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10815 match self {
10816 CreateViewSecurity::Definer => write!(f, "DEFINER"),
10817 CreateViewSecurity::Invoker => write!(f, "INVOKER"),
10818 }
10819 }
10820}
10821
10822#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10826#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10827#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10828pub struct CreateViewParams {
10829 pub algorithm: Option<CreateViewAlgorithm>,
10831 pub definer: Option<GranteeName>,
10833 pub security: Option<CreateViewSecurity>,
10835}
10836
10837impl Display for CreateViewParams {
10838 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10839 let CreateViewParams {
10840 algorithm,
10841 definer,
10842 security,
10843 } = self;
10844 if let Some(algorithm) = algorithm {
10845 write!(f, "ALGORITHM = {algorithm} ")?;
10846 }
10847 if let Some(definers) = definer {
10848 write!(f, "DEFINER = {definers} ")?;
10849 }
10850 if let Some(security) = security {
10851 write!(f, "SQL SECURITY {security} ")?;
10852 }
10853 Ok(())
10854 }
10855}
10856
10857#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10858#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10859#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10860pub struct NamedParenthesizedList {
10868 pub key: Ident,
10870 pub name: Option<Ident>,
10872 pub values: Vec<Ident>,
10874}
10875
10876#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10881#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10882#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10883pub struct RowAccessPolicy {
10884 pub policy: ObjectName,
10886 pub on: Vec<Ident>,
10888}
10889
10890impl RowAccessPolicy {
10891 pub fn new(policy: ObjectName, on: Vec<Ident>) -> Self {
10893 Self { policy, on }
10894 }
10895}
10896
10897impl Display for RowAccessPolicy {
10898 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10899 write!(
10900 f,
10901 "WITH ROW ACCESS POLICY {} ON ({})",
10902 self.policy,
10903 display_comma_separated(self.on.as_slice())
10904 )
10905 }
10906}
10907
10908#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10912#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10913#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10914pub struct StorageLifecyclePolicy {
10915 pub policy: ObjectName,
10917 pub on: Vec<Ident>,
10919}
10920
10921impl Display for StorageLifecyclePolicy {
10922 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10923 write!(
10924 f,
10925 "WITH STORAGE LIFECYCLE POLICY {} ON ({})",
10926 self.policy,
10927 display_comma_separated(self.on.as_slice())
10928 )
10929 }
10930}
10931
10932#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10936#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10937#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10938pub struct Tag {
10939 pub key: ObjectName,
10941 pub value: String,
10943}
10944
10945impl Tag {
10946 pub fn new(key: ObjectName, value: String) -> Self {
10948 Self { key, value }
10949 }
10950}
10951
10952impl Display for Tag {
10953 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10954 write!(f, "{}='{}'", self.key, self.value)
10955 }
10956}
10957
10958#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10962#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10963#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10964pub struct ContactEntry {
10965 pub purpose: String,
10967 pub contact: String,
10969}
10970
10971impl Display for ContactEntry {
10972 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10973 write!(f, "{} = {}", self.purpose, self.contact)
10974 }
10975}
10976
10977#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10979#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10980#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10981pub enum CommentDef {
10982 WithEq(String),
10985 WithoutEq(String),
10987}
10988
10989impl Display for CommentDef {
10990 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10991 match self {
10992 CommentDef::WithEq(comment) | CommentDef::WithoutEq(comment) => write!(f, "{comment}"),
10993 }
10994 }
10995}
10996
10997#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11012#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11013#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11014pub enum WrappedCollection<T> {
11015 NoWrapping(T),
11017 Parentheses(T),
11019}
11020
11021impl<T> Display for WrappedCollection<Vec<T>>
11022where
11023 T: Display,
11024{
11025 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11026 match self {
11027 WrappedCollection::NoWrapping(inner) => {
11028 write!(f, "{}", display_comma_separated(inner.as_slice()))
11029 }
11030 WrappedCollection::Parentheses(inner) => {
11031 write!(f, "({})", display_comma_separated(inner.as_slice()))
11032 }
11033 }
11034 }
11035}
11036
11037#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11061#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11062#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11063pub struct UtilityOption {
11064 pub name: Ident,
11066 pub arg: Option<Expr>,
11068}
11069
11070impl Display for UtilityOption {
11071 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11072 if let Some(ref arg) = self.arg {
11073 write!(f, "{} {}", self.name, arg)
11074 } else {
11075 write!(f, "{}", self.name)
11076 }
11077 }
11078}
11079
11080#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11084#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11085#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11086pub struct ShowStatementOptions {
11087 pub show_in: Option<ShowStatementIn>,
11089 pub starts_with: Option<ValueWithSpan>,
11091 pub limit: Option<Expr>,
11093 pub limit_from: Option<ValueWithSpan>,
11095 pub filter_position: Option<ShowStatementFilterPosition>,
11097}
11098
11099impl Display for ShowStatementOptions {
11100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11101 let (like_in_infix, like_in_suffix) = match &self.filter_position {
11102 Some(ShowStatementFilterPosition::Infix(filter)) => {
11103 (format!(" {filter}"), "".to_string())
11104 }
11105 Some(ShowStatementFilterPosition::Suffix(filter)) => {
11106 ("".to_string(), format!(" {filter}"))
11107 }
11108 None => ("".to_string(), "".to_string()),
11109 };
11110 write!(
11111 f,
11112 "{like_in_infix}{show_in}{starts_with}{limit}{from}{like_in_suffix}",
11113 show_in = match &self.show_in {
11114 Some(i) => format!(" {i}"),
11115 None => String::new(),
11116 },
11117 starts_with = match &self.starts_with {
11118 Some(s) => format!(" STARTS WITH {s}"),
11119 None => String::new(),
11120 },
11121 limit = match &self.limit {
11122 Some(l) => format!(" LIMIT {l}"),
11123 None => String::new(),
11124 },
11125 from = match &self.limit_from {
11126 Some(f) => format!(" FROM {f}"),
11127 None => String::new(),
11128 }
11129 )?;
11130 Ok(())
11131 }
11132}
11133
11134#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11135#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11136#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11137pub enum ShowStatementFilterPosition {
11139 Infix(ShowStatementFilter), Suffix(ShowStatementFilter), }
11144
11145#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11146#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11147#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11148pub enum ShowStatementInParentType {
11150 Account,
11152 Database,
11154 Schema,
11156 Table,
11158 View,
11160}
11161
11162impl fmt::Display for ShowStatementInParentType {
11163 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11164 match self {
11165 ShowStatementInParentType::Account => write!(f, "ACCOUNT"),
11166 ShowStatementInParentType::Database => write!(f, "DATABASE"),
11167 ShowStatementInParentType::Schema => write!(f, "SCHEMA"),
11168 ShowStatementInParentType::Table => write!(f, "TABLE"),
11169 ShowStatementInParentType::View => write!(f, "VIEW"),
11170 }
11171 }
11172}
11173
11174#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11175#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11176#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11177pub struct ShowStatementIn {
11179 pub clause: ShowStatementInClause,
11181 pub parent_type: Option<ShowStatementInParentType>,
11183 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
11185 pub parent_name: Option<ObjectName>,
11186}
11187
11188impl fmt::Display for ShowStatementIn {
11189 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11190 write!(f, "{}", self.clause)?;
11191 if let Some(parent_type) = &self.parent_type {
11192 write!(f, " {parent_type}")?;
11193 }
11194 if let Some(parent_name) = &self.parent_name {
11195 write!(f, " {parent_name}")?;
11196 }
11197 Ok(())
11198 }
11199}
11200
11201#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11203#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11204#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11205pub struct ShowCharset {
11206 pub is_shorthand: bool,
11209 pub filter: Option<ShowStatementFilter>,
11211}
11212
11213impl fmt::Display for ShowCharset {
11214 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11215 write!(f, "SHOW")?;
11216 if self.is_shorthand {
11217 write!(f, " CHARSET")?;
11218 } else {
11219 write!(f, " CHARACTER SET")?;
11220 }
11221 if let Some(filter) = &self.filter {
11222 write!(f, " {filter}")?;
11223 }
11224 Ok(())
11225 }
11226}
11227
11228#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11229#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11230#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11231pub struct ShowObjects {
11233 pub terse: bool,
11235 pub show_options: ShowStatementOptions,
11237}
11238
11239#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11249#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11250#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11251pub enum JsonNullClause {
11252 NullOnNull,
11254 AbsentOnNull,
11256}
11257
11258impl Display for JsonNullClause {
11259 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11260 match self {
11261 JsonNullClause::NullOnNull => write!(f, "NULL ON NULL"),
11262 JsonNullClause::AbsentOnNull => write!(f, "ABSENT ON NULL"),
11263 }
11264 }
11265}
11266
11267#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11274#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11275#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11276pub struct JsonReturningClause {
11277 pub data_type: DataType,
11279}
11280
11281impl Display for JsonReturningClause {
11282 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11283 write!(f, "RETURNING {}", self.data_type)
11284 }
11285}
11286
11287#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11289#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11290#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11291pub struct RenameTable {
11292 pub old_name: ObjectName,
11294 pub new_name: ObjectName,
11296}
11297
11298impl fmt::Display for RenameTable {
11299 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11300 write!(f, "{} TO {}", self.old_name, self.new_name)?;
11301 Ok(())
11302 }
11303}
11304
11305#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11307#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11308#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11309pub enum TableObject {
11310 TableName(#[cfg_attr(feature = "visitor", visit(with = "visit_relation"))] ObjectName),
11316
11317 TableFunction(Function),
11324
11325 TableQuery(Box<Query>),
11334}
11335
11336impl fmt::Display for TableObject {
11337 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11338 match self {
11339 Self::TableName(table_name) => write!(f, "{table_name}"),
11340 Self::TableFunction(func) => write!(f, "FUNCTION {func}"),
11341 Self::TableQuery(table_query) => write!(f, "({table_query})"),
11342 }
11343 }
11344}
11345
11346#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11348#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11349#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11350pub struct SetSessionAuthorizationParam {
11351 pub scope: ContextModifier,
11353 pub kind: SetSessionAuthorizationParamKind,
11355}
11356
11357impl fmt::Display for SetSessionAuthorizationParam {
11358 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11359 write!(f, "{}", self.kind)
11360 }
11361}
11362
11363#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11365#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11366#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11367pub enum SetSessionAuthorizationParamKind {
11368 Default,
11370
11371 User(Ident),
11373}
11374
11375impl fmt::Display for SetSessionAuthorizationParamKind {
11376 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11377 match self {
11378 SetSessionAuthorizationParamKind::Default => write!(f, "DEFAULT"),
11379 SetSessionAuthorizationParamKind::User(name) => write!(f, "{}", name),
11380 }
11381 }
11382}
11383
11384#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11385#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11386#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11387pub enum SetSessionParamKind {
11389 Generic(SetSessionParamGeneric),
11391 IdentityInsert(SetSessionParamIdentityInsert),
11393 Offsets(SetSessionParamOffsets),
11395 Statistics(SetSessionParamStatistics),
11397}
11398
11399impl fmt::Display for SetSessionParamKind {
11400 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11401 match self {
11402 SetSessionParamKind::Generic(x) => write!(f, "{x}"),
11403 SetSessionParamKind::IdentityInsert(x) => write!(f, "{x}"),
11404 SetSessionParamKind::Offsets(x) => write!(f, "{x}"),
11405 SetSessionParamKind::Statistics(x) => write!(f, "{x}"),
11406 }
11407 }
11408}
11409
11410#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11411#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11412#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11413pub struct SetSessionParamGeneric {
11415 pub names: Vec<String>,
11417 pub value: String,
11419}
11420
11421impl fmt::Display for SetSessionParamGeneric {
11422 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11423 write!(f, "{} {}", display_comma_separated(&self.names), self.value)
11424 }
11425}
11426
11427#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11428#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11429#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11430pub struct SetSessionParamIdentityInsert {
11432 pub obj: ObjectName,
11434 pub value: SessionParamValue,
11436}
11437
11438impl fmt::Display for SetSessionParamIdentityInsert {
11439 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11440 write!(f, "IDENTITY_INSERT {} {}", self.obj, self.value)
11441 }
11442}
11443
11444#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11445#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11446#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11447pub struct SetSessionParamOffsets {
11449 pub keywords: Vec<String>,
11451 pub value: SessionParamValue,
11453}
11454
11455impl fmt::Display for SetSessionParamOffsets {
11456 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11457 write!(
11458 f,
11459 "OFFSETS {} {}",
11460 display_comma_separated(&self.keywords),
11461 self.value
11462 )
11463 }
11464}
11465
11466#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11467#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11468#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11469pub struct SetSessionParamStatistics {
11471 pub topic: SessionParamStatsTopic,
11473 pub value: SessionParamValue,
11475}
11476
11477impl fmt::Display for SetSessionParamStatistics {
11478 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11479 write!(f, "STATISTICS {} {}", self.topic, self.value)
11480 }
11481}
11482
11483#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11484#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11485#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11486pub enum SessionParamStatsTopic {
11488 IO,
11490 Profile,
11492 Time,
11494 Xml,
11496}
11497
11498impl fmt::Display for SessionParamStatsTopic {
11499 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11500 match self {
11501 SessionParamStatsTopic::IO => write!(f, "IO"),
11502 SessionParamStatsTopic::Profile => write!(f, "PROFILE"),
11503 SessionParamStatsTopic::Time => write!(f, "TIME"),
11504 SessionParamStatsTopic::Xml => write!(f, "XML"),
11505 }
11506 }
11507}
11508
11509#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11510#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11511#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11512pub enum SessionParamValue {
11514 On,
11516 Off,
11518}
11519
11520impl fmt::Display for SessionParamValue {
11521 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11522 match self {
11523 SessionParamValue::On => write!(f, "ON"),
11524 SessionParamValue::Off => write!(f, "OFF"),
11525 }
11526 }
11527}
11528
11529#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11536#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11537#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11538pub enum StorageSerializationPolicy {
11539 Compatible,
11541 Optimized,
11543}
11544
11545impl Display for StorageSerializationPolicy {
11546 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11547 match self {
11548 StorageSerializationPolicy::Compatible => write!(f, "COMPATIBLE"),
11549 StorageSerializationPolicy::Optimized => write!(f, "OPTIMIZED"),
11550 }
11551 }
11552}
11553
11554#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11561#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11562#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11563pub enum CatalogSyncNamespaceMode {
11564 Nest,
11566 Flatten,
11568}
11569
11570impl Display for CatalogSyncNamespaceMode {
11571 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11572 match self {
11573 CatalogSyncNamespaceMode::Nest => write!(f, "NEST"),
11574 CatalogSyncNamespaceMode::Flatten => write!(f, "FLATTEN"),
11575 }
11576 }
11577}
11578
11579#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11581#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11582#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11583pub enum CopyIntoSnowflakeKind {
11584 Table,
11587 Location,
11590}
11591
11592#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11593#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11594#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11595pub struct PrintStatement {
11597 pub message: Box<Expr>,
11599}
11600
11601impl fmt::Display for PrintStatement {
11602 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11603 write!(f, "PRINT {}", self.message)
11604 }
11605}
11606
11607#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11611#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11612#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11613pub enum WaitForType {
11614 Delay,
11616 Time,
11618}
11619
11620impl fmt::Display for WaitForType {
11621 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11622 match self {
11623 WaitForType::Delay => write!(f, "DELAY"),
11624 WaitForType::Time => write!(f, "TIME"),
11625 }
11626 }
11627}
11628
11629#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11633#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11634#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11635pub struct WaitForStatement {
11636 pub wait_type: WaitForType,
11638 pub expr: Expr,
11640}
11641
11642impl fmt::Display for WaitForStatement {
11643 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11644 write!(f, "WAITFOR {} {}", self.wait_type, self.expr)
11645 }
11646}
11647
11648#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11653#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11654#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11655pub struct ReturnStatement {
11656 pub value: Option<ReturnStatementValue>,
11658}
11659
11660impl fmt::Display for ReturnStatement {
11661 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11662 match &self.value {
11663 Some(ReturnStatementValue::Expr(expr)) => write!(f, "RETURN {expr}"),
11664 None => write!(f, "RETURN"),
11665 }
11666 }
11667}
11668
11669#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11671#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11672#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11673pub enum ReturnStatementValue {
11674 Expr(Expr),
11676}
11677
11678#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11680#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11681#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11682pub struct OpenStatement {
11683 pub cursor_name: Ident,
11685}
11686
11687impl fmt::Display for OpenStatement {
11688 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11689 write!(f, "OPEN {}", self.cursor_name)
11690 }
11691}
11692
11693#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11697#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11698#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11699pub enum NullInclusion {
11700 IncludeNulls,
11702 ExcludeNulls,
11704}
11705
11706impl fmt::Display for NullInclusion {
11707 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11708 match self {
11709 NullInclusion::IncludeNulls => write!(f, "INCLUDE NULLS"),
11710 NullInclusion::ExcludeNulls => write!(f, "EXCLUDE NULLS"),
11711 }
11712 }
11713}
11714
11715#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11723#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11724#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11725pub struct MemberOf {
11726 pub value: Box<Expr>,
11728 pub array: Box<Expr>,
11730}
11731
11732impl fmt::Display for MemberOf {
11733 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11734 write!(f, "{} MEMBER OF({})", self.value, self.array)
11735 }
11736}
11737
11738#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11739#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11740#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11741pub struct ExportData {
11743 pub options: Vec<SqlOption>,
11745 pub query: Box<Query>,
11747 pub connection: Option<ObjectName>,
11749}
11750
11751impl fmt::Display for ExportData {
11752 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11753 if let Some(connection) = &self.connection {
11754 write!(
11755 f,
11756 "EXPORT DATA WITH CONNECTION {connection} OPTIONS({}) AS {}",
11757 display_comma_separated(&self.options),
11758 self.query
11759 )
11760 } else {
11761 write!(
11762 f,
11763 "EXPORT DATA OPTIONS({}) AS {}",
11764 display_comma_separated(&self.options),
11765 self.query
11766 )
11767 }
11768 }
11769}
11770#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11779#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11780#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11781pub struct CreateUser {
11782 pub or_replace: bool,
11784 pub if_not_exists: bool,
11786 pub name: Ident,
11788 pub options: KeyValueOptions,
11790 pub with_tags: bool,
11792 pub tags: KeyValueOptions,
11794}
11795
11796impl fmt::Display for CreateUser {
11797 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11798 write!(f, "CREATE")?;
11799 if self.or_replace {
11800 write!(f, " OR REPLACE")?;
11801 }
11802 write!(f, " USER")?;
11803 if self.if_not_exists {
11804 write!(f, " IF NOT EXISTS")?;
11805 }
11806 write!(f, " {}", self.name)?;
11807 if !self.options.options.is_empty() {
11808 write!(f, " {}", self.options)?;
11809 }
11810 if !self.tags.options.is_empty() {
11811 if self.with_tags {
11812 write!(f, " WITH")?;
11813 }
11814 write!(f, " TAG ({})", self.tags)?;
11815 }
11816 Ok(())
11817 }
11818}
11819
11820#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11828#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11829#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11830pub struct CreateWarehouse {
11831 pub or_replace: bool,
11833 pub if_not_exists: bool,
11835 pub name: ObjectName,
11837 pub options: KeyValueOptions,
11839}
11840
11841impl fmt::Display for CreateWarehouse {
11842 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11843 write!(f, "CREATE")?;
11844 if self.or_replace {
11845 write!(f, " OR REPLACE")?;
11846 }
11847 write!(f, " WAREHOUSE")?;
11848 if self.if_not_exists {
11849 write!(f, " IF NOT EXISTS")?;
11850 }
11851 write!(f, " {}", self.name)?;
11852 if !self.options.options.is_empty() {
11853 write!(f, " {}", self.options)?;
11854 }
11855 Ok(())
11856 }
11857}
11858
11859#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11871#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11872#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11873pub struct AlterUser {
11874 pub if_exists: bool,
11876 pub name: Ident,
11878 pub rename_to: Option<Ident>,
11881 pub reset_password: bool,
11883 pub abort_all_queries: bool,
11885 pub add_role_delegation: Option<AlterUserAddRoleDelegation>,
11887 pub remove_role_delegation: Option<AlterUserRemoveRoleDelegation>,
11889 pub enroll_mfa: bool,
11891 pub set_default_mfa_method: Option<MfaMethodKind>,
11893 pub remove_mfa_method: Option<MfaMethodKind>,
11895 pub modify_mfa_method: Option<AlterUserModifyMfaMethod>,
11897 pub add_mfa_method_otp: Option<AlterUserAddMfaMethodOtp>,
11899 pub set_policy: Option<AlterUserSetPolicy>,
11901 pub unset_policy: Option<UserPolicyKind>,
11903 pub set_tag: KeyValueOptions,
11905 pub unset_tag: Vec<String>,
11907 pub set_props: KeyValueOptions,
11909 pub unset_props: Vec<String>,
11911 pub password: Option<AlterUserPassword>,
11913}
11914
11915#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11919#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11920#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11921pub struct AlterUserAddRoleDelegation {
11922 pub role: Ident,
11924 pub integration: Ident,
11926}
11927
11928#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11932#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11933#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11934pub struct AlterUserRemoveRoleDelegation {
11935 pub role: Option<Ident>,
11937 pub integration: Ident,
11939}
11940
11941#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11945#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11946#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11947pub struct AlterUserAddMfaMethodOtp {
11948 pub count: Option<ValueWithSpan>,
11950}
11951
11952#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11956#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11957#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11958pub struct AlterUserModifyMfaMethod {
11959 pub method: MfaMethodKind,
11961 pub comment: String,
11963}
11964
11965#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11967#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11968#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11969pub enum MfaMethodKind {
11970 PassKey,
11972 Totp,
11974 Duo,
11976}
11977
11978impl fmt::Display for MfaMethodKind {
11979 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11980 match self {
11981 MfaMethodKind::PassKey => write!(f, "PASSKEY"),
11982 MfaMethodKind::Totp => write!(f, "TOTP"),
11983 MfaMethodKind::Duo => write!(f, "DUO"),
11984 }
11985 }
11986}
11987
11988#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11992#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11993#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11994pub struct AlterUserSetPolicy {
11995 pub policy_kind: UserPolicyKind,
11997 pub policy: Ident,
11999}
12000
12001#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12003#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12004#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12005pub enum UserPolicyKind {
12006 Authentication,
12008 Password,
12010 Session,
12012}
12013
12014impl fmt::Display for UserPolicyKind {
12015 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12016 match self {
12017 UserPolicyKind::Authentication => write!(f, "AUTHENTICATION"),
12018 UserPolicyKind::Password => write!(f, "PASSWORD"),
12019 UserPolicyKind::Session => write!(f, "SESSION"),
12020 }
12021 }
12022}
12023
12024impl fmt::Display for AlterUser {
12025 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12026 write!(f, "ALTER")?;
12027 write!(f, " USER")?;
12028 if self.if_exists {
12029 write!(f, " IF EXISTS")?;
12030 }
12031 write!(f, " {}", self.name)?;
12032 if let Some(new_name) = &self.rename_to {
12033 write!(f, " RENAME TO {new_name}")?;
12034 }
12035 if self.reset_password {
12036 write!(f, " RESET PASSWORD")?;
12037 }
12038 if self.abort_all_queries {
12039 write!(f, " ABORT ALL QUERIES")?;
12040 }
12041 if let Some(role_delegation) = &self.add_role_delegation {
12042 let role = &role_delegation.role;
12043 let integration = &role_delegation.integration;
12044 write!(
12045 f,
12046 " ADD DELEGATED AUTHORIZATION OF ROLE {role} TO SECURITY INTEGRATION {integration}"
12047 )?;
12048 }
12049 if let Some(role_delegation) = &self.remove_role_delegation {
12050 write!(f, " REMOVE DELEGATED")?;
12051 match &role_delegation.role {
12052 Some(role) => write!(f, " AUTHORIZATION OF ROLE {role}")?,
12053 None => write!(f, " AUTHORIZATIONS")?,
12054 }
12055 let integration = &role_delegation.integration;
12056 write!(f, " FROM SECURITY INTEGRATION {integration}")?;
12057 }
12058 if self.enroll_mfa {
12059 write!(f, " ENROLL MFA")?;
12060 }
12061 if let Some(method) = &self.set_default_mfa_method {
12062 write!(f, " SET DEFAULT_MFA_METHOD {method}")?
12063 }
12064 if let Some(method) = &self.remove_mfa_method {
12065 write!(f, " REMOVE MFA METHOD {method}")?;
12066 }
12067 if let Some(modify) = &self.modify_mfa_method {
12068 let method = &modify.method;
12069 let comment = &modify.comment;
12070 write!(
12071 f,
12072 " MODIFY MFA METHOD {method} SET COMMENT '{}'",
12073 value::escape_single_quote_string(comment)
12074 )?;
12075 }
12076 if let Some(add_mfa_method_otp) = &self.add_mfa_method_otp {
12077 write!(f, " ADD MFA METHOD OTP")?;
12078 if let Some(count) = &add_mfa_method_otp.count {
12079 write!(f, " COUNT = {count}")?;
12080 }
12081 }
12082 if let Some(policy) = &self.set_policy {
12083 let policy_kind = &policy.policy_kind;
12084 let name = &policy.policy;
12085 write!(f, " SET {policy_kind} POLICY {name}")?;
12086 }
12087 if let Some(policy_kind) = &self.unset_policy {
12088 write!(f, " UNSET {policy_kind} POLICY")?;
12089 }
12090 if !self.set_tag.options.is_empty() {
12091 write!(f, " SET TAG {}", self.set_tag)?;
12092 }
12093 if !self.unset_tag.is_empty() {
12094 write!(f, " UNSET TAG {}", display_comma_separated(&self.unset_tag))?;
12095 }
12096 let has_props = !self.set_props.options.is_empty();
12097 if has_props {
12098 write!(f, " SET")?;
12099 write!(f, " {}", self.set_props)?;
12100 }
12101 if !self.unset_props.is_empty() {
12102 write!(f, " UNSET {}", display_comma_separated(&self.unset_props))?;
12103 }
12104 if let Some(password) = &self.password {
12105 write!(f, " {}", password)?;
12106 }
12107 Ok(())
12108 }
12109}
12110
12111#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12115#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12116#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12117pub struct AlterUserPassword {
12118 pub encrypted: bool,
12120 pub password: Option<String>,
12122}
12123
12124impl Display for AlterUserPassword {
12125 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12126 if self.encrypted {
12127 write!(f, "ENCRYPTED ")?;
12128 }
12129 write!(f, "PASSWORD")?;
12130 match &self.password {
12131 None => write!(f, " NULL")?,
12132 Some(password) => write!(f, " '{}'", value::escape_single_quote_string(password))?,
12133 }
12134 Ok(())
12135 }
12136}
12137
12138#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12143#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12144#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12145pub enum CreateTableLikeKind {
12146 Parenthesized(CreateTableLike),
12151 Plain(CreateTableLike),
12157}
12158
12159#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12160#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12161#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12162pub enum CreateTableLikeDefaults {
12164 Including,
12166 Excluding,
12168}
12169
12170impl fmt::Display for CreateTableLikeDefaults {
12171 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12172 match self {
12173 CreateTableLikeDefaults::Including => write!(f, "INCLUDING DEFAULTS"),
12174 CreateTableLikeDefaults::Excluding => write!(f, "EXCLUDING DEFAULTS"),
12175 }
12176 }
12177}
12178
12179#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12180#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12181#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12182pub struct CreateTableLike {
12184 pub name: ObjectName,
12186 pub defaults: Option<CreateTableLikeDefaults>,
12188}
12189
12190impl fmt::Display for CreateTableLike {
12191 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12192 write!(f, "LIKE {}", self.name)?;
12193 if let Some(defaults) = &self.defaults {
12194 write!(f, " {defaults}")?;
12195 }
12196 Ok(())
12197 }
12198}
12199
12200#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12204#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12205#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12206pub enum RefreshModeKind {
12207 Auto,
12209 Full,
12211 Incremental,
12213}
12214
12215impl fmt::Display for RefreshModeKind {
12216 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12217 match self {
12218 RefreshModeKind::Auto => write!(f, "AUTO"),
12219 RefreshModeKind::Full => write!(f, "FULL"),
12220 RefreshModeKind::Incremental => write!(f, "INCREMENTAL"),
12221 }
12222 }
12223}
12224
12225#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12229#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12230#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12231pub enum InitializeKind {
12232 OnCreate,
12234 OnSchedule,
12236}
12237
12238impl fmt::Display for InitializeKind {
12239 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12240 match self {
12241 InitializeKind::OnCreate => write!(f, "ON_CREATE"),
12242 InitializeKind::OnSchedule => write!(f, "ON_SCHEDULE"),
12243 }
12244 }
12245}
12246
12247#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12254#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12255#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12256pub struct VacuumStatement {
12257 pub full: bool,
12259 pub sort_only: bool,
12261 pub delete_only: bool,
12263 pub reindex: bool,
12265 pub recluster: bool,
12267 pub table_name: Option<ObjectName>,
12269 pub threshold: Option<ValueWithSpan>,
12271 pub boost: bool,
12273}
12274
12275impl fmt::Display for VacuumStatement {
12276 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12277 write!(
12278 f,
12279 "VACUUM{}{}{}{}{}",
12280 if self.full { " FULL" } else { "" },
12281 if self.sort_only { " SORT ONLY" } else { "" },
12282 if self.delete_only { " DELETE ONLY" } else { "" },
12283 if self.reindex { " REINDEX" } else { "" },
12284 if self.recluster { " RECLUSTER" } else { "" },
12285 )?;
12286 if let Some(table_name) = &self.table_name {
12287 write!(f, " {table_name}")?;
12288 }
12289 if let Some(threshold) = &self.threshold {
12290 write!(f, " TO {threshold} PERCENT")?;
12291 }
12292 if self.boost {
12293 write!(f, " BOOST")?;
12294 }
12295 Ok(())
12296 }
12297}
12298
12299#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12301#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12302#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12303pub enum Reset {
12304 ALL,
12306
12307 SessionAuthorization,
12309
12310 ConfigurationParameter(ObjectName),
12312}
12313
12314#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12319#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12320#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12321pub struct ResetStatement {
12322 pub reset: Reset,
12324}
12325
12326#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12332#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12333#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12334pub struct OptimizerHint {
12335 pub prefix: String,
12342 pub text: String,
12344 pub style: OptimizerHintStyle,
12349}
12350
12351#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12353#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12354#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12355pub enum OptimizerHintStyle {
12356 SingleLine {
12359 prefix: String,
12361 },
12362 MultiLine,
12365}
12366
12367impl fmt::Display for OptimizerHint {
12368 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
12369 match &self.style {
12370 OptimizerHintStyle::SingleLine { prefix } => {
12371 f.write_str(prefix)?;
12372 f.write_str(&self.prefix)?;
12373 f.write_str("+")?;
12374 f.write_str(&self.text)?;
12375 f.write_str("\n")
12376 }
12377 OptimizerHintStyle::MultiLine => {
12378 f.write_str("/*")?;
12379 f.write_str(&self.prefix)?;
12380 f.write_str("+")?;
12381 f.write_str(&self.text)?;
12382 f.write_str("*/")
12383 }
12384 }
12385 }
12386}
12387
12388impl fmt::Display for ResetStatement {
12389 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12390 match &self.reset {
12391 Reset::ALL => write!(f, "RESET ALL"),
12392 Reset::SessionAuthorization => write!(f, "RESET SESSION AUTHORIZATION"),
12393 Reset::ConfigurationParameter(param) => write!(f, "RESET {}", param),
12394 }
12395 }
12396}
12397
12398impl From<Set> for Statement {
12399 fn from(s: Set) -> Self {
12400 Self::Set(s)
12401 }
12402}
12403
12404impl From<Query> for Statement {
12405 fn from(q: Query) -> Self {
12406 Box::new(q).into()
12407 }
12408}
12409
12410impl From<Box<Query>> for Statement {
12411 fn from(q: Box<Query>) -> Self {
12412 Self::Query(q)
12413 }
12414}
12415
12416impl From<Insert> for Statement {
12417 fn from(i: Insert) -> Self {
12418 Self::Insert(i)
12419 }
12420}
12421
12422impl From<Update> for Statement {
12423 fn from(u: Update) -> Self {
12424 Self::Update(u)
12425 }
12426}
12427
12428impl From<CreateView> for Statement {
12429 fn from(cv: CreateView) -> Self {
12430 Self::CreateView(cv)
12431 }
12432}
12433
12434impl From<CreateRole> for Statement {
12435 fn from(cr: CreateRole) -> Self {
12436 Self::CreateRole(cr)
12437 }
12438}
12439
12440impl From<AlterTable> for Statement {
12441 fn from(at: AlterTable) -> Self {
12442 Self::AlterTable(at)
12443 }
12444}
12445
12446impl From<DropFunction> for Statement {
12447 fn from(df: DropFunction) -> Self {
12448 Self::DropFunction(df)
12449 }
12450}
12451
12452impl From<CreateExtension> for Statement {
12453 fn from(ce: CreateExtension) -> Self {
12454 Self::CreateExtension(ce)
12455 }
12456}
12457
12458impl From<CreateCollation> for Statement {
12459 fn from(c: CreateCollation) -> Self {
12460 Self::CreateCollation(c)
12461 }
12462}
12463
12464impl From<DropExtension> for Statement {
12465 fn from(de: DropExtension) -> Self {
12466 Self::DropExtension(de)
12467 }
12468}
12469
12470impl From<CaseStatement> for Statement {
12471 fn from(c: CaseStatement) -> Self {
12472 Self::Case(c)
12473 }
12474}
12475
12476impl From<IfStatement> for Statement {
12477 fn from(i: IfStatement) -> Self {
12478 Self::If(i)
12479 }
12480}
12481
12482impl From<WhileStatement> for Statement {
12483 fn from(w: WhileStatement) -> Self {
12484 Self::While(w)
12485 }
12486}
12487
12488impl From<RaiseStatement> for Statement {
12489 fn from(r: RaiseStatement) -> Self {
12490 Self::Raise(r)
12491 }
12492}
12493
12494impl From<DoStatement> for Statement {
12495 fn from(statement: DoStatement) -> Self {
12496 Self::Do(statement)
12497 }
12498}
12499
12500impl From<ThrowStatement> for Statement {
12501 fn from(t: ThrowStatement) -> Self {
12502 Self::Throw(t)
12503 }
12504}
12505
12506impl From<Function> for Statement {
12507 fn from(f: Function) -> Self {
12508 Self::Call(f)
12509 }
12510}
12511
12512impl From<OpenStatement> for Statement {
12513 fn from(o: OpenStatement) -> Self {
12514 Self::Open(o)
12515 }
12516}
12517
12518impl From<Delete> for Statement {
12519 fn from(d: Delete) -> Self {
12520 Self::Delete(d)
12521 }
12522}
12523
12524impl From<CreateTable> for Statement {
12525 fn from(c: CreateTable) -> Self {
12526 Self::CreateTable(c)
12527 }
12528}
12529
12530impl From<CreateIndex> for Statement {
12531 fn from(c: CreateIndex) -> Self {
12532 Self::CreateIndex(c)
12533 }
12534}
12535
12536impl From<CreateServerStatement> for Statement {
12537 fn from(c: CreateServerStatement) -> Self {
12538 Self::CreateServer(c)
12539 }
12540}
12541
12542impl From<CreateConnector> for Statement {
12543 fn from(c: CreateConnector) -> Self {
12544 Self::CreateConnector(c)
12545 }
12546}
12547
12548impl From<CreateOperator> for Statement {
12549 fn from(c: CreateOperator) -> Self {
12550 Self::CreateOperator(c)
12551 }
12552}
12553
12554impl From<CreateOperatorFamily> for Statement {
12555 fn from(c: CreateOperatorFamily) -> Self {
12556 Self::CreateOperatorFamily(c)
12557 }
12558}
12559
12560impl From<CreateOperatorClass> for Statement {
12561 fn from(c: CreateOperatorClass) -> Self {
12562 Self::CreateOperatorClass(c)
12563 }
12564}
12565
12566impl From<CreateTextSearch> for Statement {
12567 fn from(c: CreateTextSearch) -> Self {
12568 Self::CreateTextSearch(c)
12569 }
12570}
12571
12572impl From<AlterSchema> for Statement {
12573 fn from(a: AlterSchema) -> Self {
12574 Self::AlterSchema(a)
12575 }
12576}
12577
12578impl From<AlterFunction> for Statement {
12579 fn from(a: AlterFunction) -> Self {
12580 Self::AlterFunction(a)
12581 }
12582}
12583
12584impl From<AlterType> for Statement {
12585 fn from(a: AlterType) -> Self {
12586 Self::AlterType(a)
12587 }
12588}
12589
12590impl From<AlterCollation> for Statement {
12591 fn from(a: AlterCollation) -> Self {
12592 Self::AlterCollation(a)
12593 }
12594}
12595
12596impl From<AlterOperator> for Statement {
12597 fn from(a: AlterOperator) -> Self {
12598 Self::AlterOperator(a)
12599 }
12600}
12601
12602impl From<AlterOperatorFamily> for Statement {
12603 fn from(a: AlterOperatorFamily) -> Self {
12604 Self::AlterOperatorFamily(a)
12605 }
12606}
12607
12608impl From<AlterOperatorClass> for Statement {
12609 fn from(a: AlterOperatorClass) -> Self {
12610 Self::AlterOperatorClass(a)
12611 }
12612}
12613
12614impl From<AlterTextSearch> for Statement {
12615 fn from(a: AlterTextSearch) -> Self {
12616 Self::AlterTextSearch(a)
12617 }
12618}
12619
12620impl From<Merge> for Statement {
12621 fn from(m: Merge) -> Self {
12622 Self::Merge(m)
12623 }
12624}
12625
12626impl From<AlterUser> for Statement {
12627 fn from(a: AlterUser) -> Self {
12628 Self::AlterUser(a)
12629 }
12630}
12631
12632impl From<DropDomain> for Statement {
12633 fn from(d: DropDomain) -> Self {
12634 Self::DropDomain(d)
12635 }
12636}
12637
12638impl From<ShowCharset> for Statement {
12639 fn from(s: ShowCharset) -> Self {
12640 Self::ShowCharset(s)
12641 }
12642}
12643
12644impl From<ShowObjects> for Statement {
12645 fn from(s: ShowObjects) -> Self {
12646 Self::ShowObjects(s)
12647 }
12648}
12649
12650impl From<Use> for Statement {
12651 fn from(u: Use) -> Self {
12652 Self::Use(u)
12653 }
12654}
12655
12656impl From<CreateFunction> for Statement {
12657 fn from(c: CreateFunction) -> Self {
12658 Self::CreateFunction(c)
12659 }
12660}
12661
12662impl From<CreateTrigger> for Statement {
12663 fn from(c: CreateTrigger) -> Self {
12664 Self::CreateTrigger(c)
12665 }
12666}
12667
12668impl From<DropTrigger> for Statement {
12669 fn from(d: DropTrigger) -> Self {
12670 Self::DropTrigger(d)
12671 }
12672}
12673
12674impl From<DropOperator> for Statement {
12675 fn from(d: DropOperator) -> Self {
12676 Self::DropOperator(d)
12677 }
12678}
12679
12680impl From<DropOperatorFamily> for Statement {
12681 fn from(d: DropOperatorFamily) -> Self {
12682 Self::DropOperatorFamily(d)
12683 }
12684}
12685
12686impl From<DropOperatorClass> for Statement {
12687 fn from(d: DropOperatorClass) -> Self {
12688 Self::DropOperatorClass(d)
12689 }
12690}
12691
12692impl From<DenyStatement> for Statement {
12693 fn from(d: DenyStatement) -> Self {
12694 Self::Deny(d)
12695 }
12696}
12697
12698impl From<CreateDomain> for Statement {
12699 fn from(c: CreateDomain) -> Self {
12700 Self::CreateDomain(c)
12701 }
12702}
12703
12704impl From<RenameTable> for Statement {
12705 fn from(r: RenameTable) -> Self {
12706 vec![r].into()
12707 }
12708}
12709
12710impl From<Vec<RenameTable>> for Statement {
12711 fn from(r: Vec<RenameTable>) -> Self {
12712 Self::RenameTable(r)
12713 }
12714}
12715
12716impl From<PrintStatement> for Statement {
12717 fn from(p: PrintStatement) -> Self {
12718 Self::Print(p)
12719 }
12720}
12721
12722impl From<ReturnStatement> for Statement {
12723 fn from(r: ReturnStatement) -> Self {
12724 Self::Return(r)
12725 }
12726}
12727
12728impl From<ExportData> for Statement {
12729 fn from(e: ExportData) -> Self {
12730 Self::ExportData(e)
12731 }
12732}
12733
12734impl From<CreateUser> for Statement {
12735 fn from(c: CreateUser) -> Self {
12736 Self::CreateUser(c)
12737 }
12738}
12739
12740impl From<CreateWarehouse> for Statement {
12741 fn from(c: CreateWarehouse) -> Self {
12742 Self::CreateWarehouse(c)
12743 }
12744}
12745
12746impl From<VacuumStatement> for Statement {
12747 fn from(v: VacuumStatement) -> Self {
12748 Self::Vacuum(v)
12749 }
12750}
12751
12752impl From<ResetStatement> for Statement {
12753 fn from(r: ResetStatement) -> Self {
12754 Self::Reset(r)
12755 }
12756}
12757
12758#[cfg(test)]
12759mod tests {
12760 use crate::tokenizer::Location;
12761
12762 use super::*;
12763
12764 #[test]
12765 fn test_window_frame_default() {
12766 let window_frame = WindowFrame::default();
12767 assert_eq!(WindowFrameBound::Preceding(None), window_frame.start_bound);
12768 }
12769
12770 #[test]
12771 fn test_grouping_sets_display() {
12772 let grouping_sets = Expr::GroupingSets(vec![
12774 vec![Expr::Identifier(Ident::new("a"))],
12775 vec![Expr::Identifier(Ident::new("b"))],
12776 ]);
12777 assert_eq!("GROUPING SETS ((a), (b))", format!("{grouping_sets}"));
12778
12779 let grouping_sets = Expr::GroupingSets(vec![vec![
12781 Expr::Identifier(Ident::new("a")),
12782 Expr::Identifier(Ident::new("b")),
12783 ]]);
12784 assert_eq!("GROUPING SETS ((a, b))", format!("{grouping_sets}"));
12785
12786 let grouping_sets = Expr::GroupingSets(vec![
12788 vec![
12789 Expr::Identifier(Ident::new("a")),
12790 Expr::Identifier(Ident::new("b")),
12791 ],
12792 vec![
12793 Expr::Identifier(Ident::new("c")),
12794 Expr::Identifier(Ident::new("d")),
12795 ],
12796 ]);
12797 assert_eq!("GROUPING SETS ((a, b), (c, d))", format!("{grouping_sets}"));
12798 }
12799
12800 #[test]
12801 fn test_rollup_display() {
12802 let rollup = Expr::Rollup(vec![vec![Expr::Identifier(Ident::new("a"))]]);
12803 assert_eq!("ROLLUP (a)", format!("{rollup}"));
12804
12805 let rollup = Expr::Rollup(vec![vec![
12806 Expr::Identifier(Ident::new("a")),
12807 Expr::Identifier(Ident::new("b")),
12808 ]]);
12809 assert_eq!("ROLLUP ((a, b))", format!("{rollup}"));
12810
12811 let rollup = Expr::Rollup(vec![
12812 vec![Expr::Identifier(Ident::new("a"))],
12813 vec![Expr::Identifier(Ident::new("b"))],
12814 ]);
12815 assert_eq!("ROLLUP (a, b)", format!("{rollup}"));
12816
12817 let rollup = Expr::Rollup(vec![
12818 vec![Expr::Identifier(Ident::new("a"))],
12819 vec![
12820 Expr::Identifier(Ident::new("b")),
12821 Expr::Identifier(Ident::new("c")),
12822 ],
12823 vec![Expr::Identifier(Ident::new("d"))],
12824 ]);
12825 assert_eq!("ROLLUP (a, (b, c), d)", format!("{rollup}"));
12826 }
12827
12828 #[test]
12829 fn test_cube_display() {
12830 let cube = Expr::Cube(vec![vec![Expr::Identifier(Ident::new("a"))]]);
12831 assert_eq!("CUBE (a)", format!("{cube}"));
12832
12833 let cube = Expr::Cube(vec![vec![
12834 Expr::Identifier(Ident::new("a")),
12835 Expr::Identifier(Ident::new("b")),
12836 ]]);
12837 assert_eq!("CUBE ((a, b))", format!("{cube}"));
12838
12839 let cube = Expr::Cube(vec![
12840 vec![Expr::Identifier(Ident::new("a"))],
12841 vec![Expr::Identifier(Ident::new("b"))],
12842 ]);
12843 assert_eq!("CUBE (a, b)", format!("{cube}"));
12844
12845 let cube = Expr::Cube(vec![
12846 vec![Expr::Identifier(Ident::new("a"))],
12847 vec![
12848 Expr::Identifier(Ident::new("b")),
12849 Expr::Identifier(Ident::new("c")),
12850 ],
12851 vec![Expr::Identifier(Ident::new("d"))],
12852 ]);
12853 assert_eq!("CUBE (a, (b, c), d)", format!("{cube}"));
12854 }
12855
12856 #[test]
12857 fn test_interval_display() {
12858 let interval = Expr::Interval(Interval {
12859 value: Box::new(Expr::Value(
12860 Value::SingleQuotedString(String::from("123:45.67")).with_empty_span(),
12861 )),
12862 leading_field: Some(DateTimeField::Minute),
12863 leading_precision: Some(10),
12864 last_field: Some(DateTimeField::Second),
12865 fractional_seconds_precision: Some(9),
12866 });
12867 assert_eq!(
12868 "INTERVAL '123:45.67' MINUTE (10) TO SECOND (9)",
12869 format!("{interval}"),
12870 );
12871
12872 let interval = Expr::Interval(Interval {
12873 value: Box::new(Expr::Value(
12874 Value::SingleQuotedString(String::from("5")).with_empty_span(),
12875 )),
12876 leading_field: Some(DateTimeField::Second),
12877 leading_precision: Some(1),
12878 last_field: None,
12879 fractional_seconds_precision: Some(3),
12880 });
12881 assert_eq!("INTERVAL '5' SECOND (1, 3)", format!("{interval}"));
12882 }
12883
12884 #[test]
12885 fn test_one_or_many_with_parens_deref() {
12886 use core::ops::Index;
12887
12888 let one = OneOrManyWithParens::One("a");
12889
12890 assert_eq!(one.deref(), &["a"]);
12891 assert_eq!(<OneOrManyWithParens<_> as Deref>::deref(&one), &["a"]);
12892
12893 assert_eq!(one[0], "a");
12894 assert_eq!(one.index(0), &"a");
12895 assert_eq!(
12896 <<OneOrManyWithParens<_> as Deref>::Target as Index<usize>>::index(&one, 0),
12897 &"a"
12898 );
12899
12900 assert_eq!(one.len(), 1);
12901 assert_eq!(<OneOrManyWithParens<_> as Deref>::Target::len(&one), 1);
12902
12903 let many1 = OneOrManyWithParens::Many(vec!["b"]);
12904
12905 assert_eq!(many1.deref(), &["b"]);
12906 assert_eq!(<OneOrManyWithParens<_> as Deref>::deref(&many1), &["b"]);
12907
12908 assert_eq!(many1[0], "b");
12909 assert_eq!(many1.index(0), &"b");
12910 assert_eq!(
12911 <<OneOrManyWithParens<_> as Deref>::Target as Index<usize>>::index(&many1, 0),
12912 &"b"
12913 );
12914
12915 assert_eq!(many1.len(), 1);
12916 assert_eq!(<OneOrManyWithParens<_> as Deref>::Target::len(&many1), 1);
12917
12918 let many2 = OneOrManyWithParens::Many(vec!["c", "d"]);
12919
12920 assert_eq!(many2.deref(), &["c", "d"]);
12921 assert_eq!(
12922 <OneOrManyWithParens<_> as Deref>::deref(&many2),
12923 &["c", "d"]
12924 );
12925
12926 assert_eq!(many2[0], "c");
12927 assert_eq!(many2.index(0), &"c");
12928 assert_eq!(
12929 <<OneOrManyWithParens<_> as Deref>::Target as Index<usize>>::index(&many2, 0),
12930 &"c"
12931 );
12932
12933 assert_eq!(many2[1], "d");
12934 assert_eq!(many2.index(1), &"d");
12935 assert_eq!(
12936 <<OneOrManyWithParens<_> as Deref>::Target as Index<usize>>::index(&many2, 1),
12937 &"d"
12938 );
12939
12940 assert_eq!(many2.len(), 2);
12941 assert_eq!(<OneOrManyWithParens<_> as Deref>::Target::len(&many2), 2);
12942 }
12943
12944 #[test]
12945 fn test_one_or_many_with_parens_as_ref() {
12946 let one = OneOrManyWithParens::One("a");
12947
12948 assert_eq!(one.as_ref(), &["a"]);
12949 assert_eq!(<OneOrManyWithParens<_> as AsRef<_>>::as_ref(&one), &["a"]);
12950
12951 let many1 = OneOrManyWithParens::Many(vec!["b"]);
12952
12953 assert_eq!(many1.as_ref(), &["b"]);
12954 assert_eq!(<OneOrManyWithParens<_> as AsRef<_>>::as_ref(&many1), &["b"]);
12955
12956 let many2 = OneOrManyWithParens::Many(vec!["c", "d"]);
12957
12958 assert_eq!(many2.as_ref(), &["c", "d"]);
12959 assert_eq!(
12960 <OneOrManyWithParens<_> as AsRef<_>>::as_ref(&many2),
12961 &["c", "d"]
12962 );
12963 }
12964
12965 #[test]
12966 fn test_one_or_many_with_parens_ref_into_iter() {
12967 let one = OneOrManyWithParens::One("a");
12968
12969 assert_eq!(Vec::from_iter(&one), vec![&"a"]);
12970
12971 let many1 = OneOrManyWithParens::Many(vec!["b"]);
12972
12973 assert_eq!(Vec::from_iter(&many1), vec![&"b"]);
12974
12975 let many2 = OneOrManyWithParens::Many(vec!["c", "d"]);
12976
12977 assert_eq!(Vec::from_iter(&many2), vec![&"c", &"d"]);
12978 }
12979
12980 #[test]
12981 fn test_one_or_many_with_parens_value_into_iter() {
12982 use core::iter::once;
12983
12984 fn test_steps<I>(ours: OneOrManyWithParens<usize>, inner: I, n: usize)
12986 where
12987 I: IntoIterator<Item = usize, IntoIter: DoubleEndedIterator + Clone> + Clone,
12988 {
12989 fn checks<I>(ours: OneOrManyWithParensIntoIter<usize>, inner: I)
12990 where
12991 I: Iterator<Item = usize> + Clone + DoubleEndedIterator,
12992 {
12993 assert_eq!(ours.size_hint(), inner.size_hint());
12994 assert_eq!(ours.clone().count(), inner.clone().count());
12995
12996 assert_eq!(
12997 ours.clone().fold(1, |a, v| a + v),
12998 inner.clone().fold(1, |a, v| a + v)
12999 );
13000
13001 assert_eq!(Vec::from_iter(ours.clone()), Vec::from_iter(inner.clone()));
13002 assert_eq!(
13003 Vec::from_iter(ours.clone().rev()),
13004 Vec::from_iter(inner.clone().rev())
13005 );
13006 }
13007
13008 let mut ours_next = ours.clone().into_iter();
13009 let mut inner_next = inner.clone().into_iter();
13010
13011 for _ in 0..n {
13012 checks(ours_next.clone(), inner_next.clone());
13013
13014 assert_eq!(ours_next.next(), inner_next.next());
13015 }
13016
13017 let mut ours_next_back = ours.clone().into_iter();
13018 let mut inner_next_back = inner.clone().into_iter();
13019
13020 for _ in 0..n {
13021 checks(ours_next_back.clone(), inner_next_back.clone());
13022
13023 assert_eq!(ours_next_back.next_back(), inner_next_back.next_back());
13024 }
13025
13026 let mut ours_mixed = ours.clone().into_iter();
13027 let mut inner_mixed = inner.clone().into_iter();
13028
13029 for i in 0..n {
13030 checks(ours_mixed.clone(), inner_mixed.clone());
13031
13032 if i % 2 == 0 {
13033 assert_eq!(ours_mixed.next_back(), inner_mixed.next_back());
13034 } else {
13035 assert_eq!(ours_mixed.next(), inner_mixed.next());
13036 }
13037 }
13038
13039 let mut ours_mixed2 = ours.into_iter();
13040 let mut inner_mixed2 = inner.into_iter();
13041
13042 for i in 0..n {
13043 checks(ours_mixed2.clone(), inner_mixed2.clone());
13044
13045 if i % 2 == 0 {
13046 assert_eq!(ours_mixed2.next(), inner_mixed2.next());
13047 } else {
13048 assert_eq!(ours_mixed2.next_back(), inner_mixed2.next_back());
13049 }
13050 }
13051 }
13052
13053 test_steps(OneOrManyWithParens::One(1), once(1), 3);
13054 test_steps(OneOrManyWithParens::Many(vec![2]), vec![2], 3);
13055 test_steps(OneOrManyWithParens::Many(vec![3, 4]), vec![3, 4], 4);
13056 }
13057
13058 #[test]
13061 fn test_ident_ord() {
13062 let mut a = Ident::with_span(Span::new(Location::new(1, 1), Location::new(1, 1)), "a");
13063 let mut b = Ident::with_span(Span::new(Location::new(2, 2), Location::new(2, 2)), "b");
13064
13065 assert!(a < b);
13066 std::mem::swap(&mut a.span, &mut b.span);
13067 assert!(a < b);
13068 }
13069}