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, OPERATOR_CHARS},
50};
51use crate::{
52 display_utils::{first_char, 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, TypeModifier,
59};
60pub use self::dcl::{
61 AlterDefaultPrivileges, AlterDefaultPrivilegesOperation, AlterRoleOperation, CreateRole,
62 DefaultPrivilegesObjectType, DefaultPrivilegesOption, Grant, GrantRole, ResetConfig, Revoke,
63 RevokeRole, RoleGrantOption, RoleGrantOptionValue, RoleKeyword, RoleOption, SecondaryRoles,
64 SetConfigValue, Use,
65};
66pub use self::ddl::{
67 AggregateModifyKind, Alignment, AlterCollation, AlterCollationOperation, AlterColumnOperation,
68 AlterConnectorOwner, AlterFunction, AlterFunctionAction, AlterFunctionKind,
69 AlterFunctionOperation, AlterGenericOption, AlterIndexOperation, AlterOperator,
70 AlterOperatorClass, AlterOperatorClassOperation, AlterOperatorFamily,
71 AlterOperatorFamilyOperation, AlterOperatorOperation, AlterPolicy, AlterPolicyOperation,
72 AlterSchema, AlterSchemaOperation, AlterTable, AlterTableAlgorithm, AlterTableLock,
73 AlterTableOperation, AlterTableType, AlterTextSearch, AlterTextSearchOperation,
74 AlterTextSearchOption, AlterTrigger, AlterTriggerOperation, AlterType, AlterTypeAddValue,
75 AlterTypeAddValuePosition, AlterTypeOperation, AlterTypeRename, AlterTypeRenameValue,
76 AlterView, AlterViewOperation, ClusteredBy, ColumnDef, ColumnOption, ColumnOptionDef,
77 ColumnOptions, ColumnPolicy, ColumnPolicyProperty, ConstraintCharacteristics, CreateAggregate,
78 CreateAggregateArgs, CreateAggregateOption, CreateCollation, CreateCollationDefinition,
79 CreateConnector, CreateDomain, CreateExtension, CreateForeignDataWrapper, CreateForeignTable,
80 CreateFunction, CreateIndex, CreateOperator, CreateOperatorClass, CreateOperatorFamily,
81 CreatePolicy, CreatePolicyCommand, CreatePolicyType, CreateRule, CreateRuleAction,
82 CreateRuleDoKind, CreateRuleEvent, CreateTable, CreateTextSearch, CreateTrigger,
83 CreateUserMapping, CreateView, Deduplicate, DeferrableInitial, DetachPartitionMode, DistStyle,
84 DropBehavior, DropExtension, DropFunction, DropOperator, DropOperatorClass, DropOperatorFamily,
85 DropOperatorSignature, DropPolicy, DropRule, DropTrigger, ForValues,
86 ForeignDataWrapperRoutineClause, FunctionReturnType, GeneratedAs, GeneratedExpressionMode,
87 IdentityParameters, IdentityProperty, IdentityPropertyFormatKind, IdentityPropertyKind,
88 IdentityPropertyOrder, IndexColumn, IndexOption, IndexType, KeyOrIndexDisplay, Msck,
89 NullsDistinctOption, OperatorArgTypes, OperatorClassItem, OperatorFamilyDropItem,
90 OperatorFamilyItem, OperatorOption, OperatorPurpose, Owner, Partition, PartitionBoundValue,
91 ProcedureParam, ReferentialAction, RenameTableNameKind, ReplicaIdentity, SqliteTableOption,
92 SqliteTableOptions, TagsColumnOption, TextSearchObjectType, TriggerObjectKind, Truncate,
93 UserDefinedTypeCompositeAttributeDef, UserDefinedTypeInternalLength,
94 UserDefinedTypeRangeOption, UserDefinedTypeRepresentation, UserDefinedTypeSqlDefinitionOption,
95 UserDefinedTypeStorage, UserMappingUser, ViewColumnDef, WithData,
96};
97pub use self::dml::{
98 Delete, Insert, InsertOverriding, Merge, MergeAction, MergeClause, MergeClauseKind,
99 MergeInsertExpr, MergeInsertKind, MergeUpdateExpr, MergeUpdateKind, MultiTableInsertIntoClause,
100 MultiTableInsertType, MultiTableInsertValue, MultiTableInsertValues,
101 MultiTableInsertWhenClause, OutputClause, Update,
102};
103pub use self::operator::{BinaryOperator, UnaryOperator};
104pub use self::query::{
105 AfterMatchSkip, ConnectByKind, Cte, CteAsMaterialized, Distinct, EmptyMatchesMode,
106 ExceptSelectItem, ExcludeSelectItem, ExprWithAlias, ExprWithAliasAndOrderBy, Fetch, ForClause,
107 ForJson, ForXml, FormatClause, GroupByExpr, GroupByWithModifier, IdentWithAlias,
108 IlikeSelectItem, InputFormatClause, Interpolate, InterpolateExpr, Join, JoinConstraint,
109 JoinOperator, JsonTableColumn, JsonTableColumnErrorHandling, JsonTableNamedColumn,
110 JsonTableNestedColumn, LateralView, LimitClause, LockClause, LockType, MatchRecognizePattern,
111 MatchRecognizeSymbol, Measure, NamedWindowDefinition, NamedWindowExpr, NonBlock, Offset,
112 OffsetRows, OpenJsonTableColumn, OrderBy, OrderByExpr, OrderByKind, OrderByOptions,
113 OrderBySort, PipeOperator, PivotValueSource, ProjectionSelect, Query, RenameSelectItem,
114 RepetitionQuantifier, ReplaceSelectElement, ReplaceSelectItem, RowsPerMatch, Select,
115 SelectFlavor, SelectInto, SelectItem, SelectItemQualifiedWildcardKind, SelectModifiers,
116 SetExpr, SetOperator, SetQuantifier, Setting, SymbolDefinition, Table, TableAlias,
117 TableAliasColumnDef, TableFactor, TableFunctionArgs, TableIndexDirective,
118 TableIndexHintForClause, TableIndexHintType, TableIndexHints, TableIndexType, TableInheritance,
119 TableSample, TableSampleBucket, TableSampleKind, TableSampleMethod, TableSampleModifier,
120 TableSampleQuantity, TableSampleSeed, TableSampleSeedModifier, TableSampleUnit, TableVersion,
121 TableWithJoins, Top, TopQuantity, UpdateTableFromKind, ValueTableMode, Values,
122 WildcardAdditionalOptions, With, WithFill, XmlNamespaceDefinition, XmlPassingArgument,
123 XmlPassingClause, XmlTableColumn, XmlTableColumnOption,
124};
125
126pub use self::trigger::{
127 TriggerEvent, TriggerExecBody, TriggerExecBodyType, TriggerObject, TriggerPeriod,
128 TriggerReferencing, TriggerReferencingType,
129};
130
131pub use self::value::{
132 escape_double_quote_string, escape_quoted_string, DateTimeField, DollarQuotedString,
133 NormalizationForm, QuoteDelimitedString, TrimWhereField, Value, ValueWithSpan,
134};
135
136use crate::ast::helpers::key_value_options::KeyValueOptions;
137use crate::ast::helpers::stmt_data_loading::StageParamsObject;
138
139#[cfg(feature = "visitor")]
140pub use visitor::*;
141
142pub use self::data_type::GeometricTypeKind;
143
144mod data_type;
145mod dcl;
146mod ddl;
147mod dml;
148pub mod helpers;
150pub mod table_constraints;
151pub use table_constraints::{
152 CheckConstraint, ConstraintUsingIndex, ExcludeConstraint, ExcludeConstraintElement,
153 ExcludeConstraintOperator, ForeignKeyConstraint, FullTextOrSpatialConstraint, IndexConstraint,
154 PrimaryKeyConstraint, TableConstraint, UniqueConstraint,
155};
156mod operator;
157mod query;
158mod spans;
159pub use spans::Spanned;
160
161pub mod comments;
162mod trigger;
163mod value;
164
165#[cfg(feature = "visitor")]
166mod visitor;
167
168pub struct DisplaySeparated<'a, T>
170where
171 T: fmt::Display,
172{
173 slice: &'a [T],
174 sep: &'static str,
175}
176
177impl<T> fmt::Display for DisplaySeparated<'_, T>
178where
179 T: fmt::Display,
180{
181 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
182 let mut delim = "";
183 for t in self.slice {
184 f.write_str(delim)?;
185 delim = self.sep;
186 t.fmt(f)?;
187 }
188 Ok(())
189 }
190}
191
192pub(crate) fn display_separated<'a, T>(slice: &'a [T], sep: &'static str) -> DisplaySeparated<'a, T>
193where
194 T: fmt::Display,
195{
196 DisplaySeparated { slice, sep }
197}
198
199pub(crate) fn display_comma_separated<T>(slice: &[T]) -> DisplaySeparated<'_, T>
200where
201 T: fmt::Display,
202{
203 DisplaySeparated { slice, sep: ", " }
204}
205
206fn format_statement_list(f: &mut fmt::Formatter, statements: &[Statement]) -> fmt::Result {
209 write!(f, "{}", display_separated(statements, "; "))?;
210 write!(f, ";")
213}
214
215fn format_begin_atomic(f: &mut fmt::Formatter, statements: &[Statement]) -> fmt::Result {
217 write!(f, " BEGIN ATOMIC")?;
218 if !statements.is_empty() {
219 write!(f, " ")?;
220 format_statement_list(f, statements)?;
221 }
222 write!(f, " END")
223}
224
225#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
227#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
228#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
229pub struct Parens<T> {
230 pub opening_token: AttachedToken,
232 pub content: T,
234 pub closing_token: AttachedToken,
236}
237
238impl<T> Parens<T> {
239 pub fn with_empty_span(content: T) -> Self {
242 Self {
243 opening_token: AttachedToken::empty(),
244 content,
245 closing_token: AttachedToken::empty(),
246 }
247 }
248}
249
250impl<T> Deref for Parens<T> {
251 type Target = T;
252
253 fn deref(&self) -> &Self::Target {
254 &self.content
255 }
256}
257
258impl<T> DerefMut for Parens<T> {
259 fn deref_mut(&mut self) -> &mut Self::Target {
260 &mut self.content
261 }
262}
263
264#[derive(Debug, Clone)]
266#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
267pub struct Ident {
268 pub value: String,
270 pub quote_style: Option<char>,
273 pub span: Span,
275}
276
277impl PartialEq for Ident {
278 fn eq(&self, other: &Self) -> bool {
279 let Ident {
280 value,
281 quote_style,
282 span: _,
284 } = self;
285
286 value == &other.value && quote_style == &other.quote_style
287 }
288}
289
290impl core::hash::Hash for Ident {
291 fn hash<H: hash::Hasher>(&self, state: &mut H) {
292 let Ident {
293 value,
294 quote_style,
295 span: _,
297 } = self;
298
299 value.hash(state);
300 quote_style.hash(state);
301 }
302}
303
304impl Eq for Ident {}
305
306impl PartialOrd for Ident {
307 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
308 Some(self.cmp(other))
309 }
310}
311
312impl Ord for Ident {
313 fn cmp(&self, other: &Self) -> Ordering {
314 let Ident {
315 value,
316 quote_style,
317 span: _,
319 } = self;
320
321 let Ident {
322 value: other_value,
323 quote_style: other_quote_style,
324 span: _,
326 } = other;
327
328 value
330 .cmp(other_value)
331 .then_with(|| quote_style.cmp(other_quote_style))
332 }
333}
334
335impl Ident {
336 pub fn new<S>(value: S) -> Self
338 where
339 S: Into<String>,
340 {
341 Ident {
342 value: value.into(),
343 quote_style: None,
344 span: Span::empty(),
345 }
346 }
347
348 pub fn with_quote<S>(quote: char, value: S) -> Self
351 where
352 S: Into<String>,
353 {
354 assert!(quote == '\'' || quote == '"' || quote == '`' || quote == '[');
355 Ident {
356 value: value.into(),
357 quote_style: Some(quote),
358 span: Span::empty(),
359 }
360 }
361
362 pub fn with_span<S>(span: Span, value: S) -> Self
364 where
365 S: Into<String>,
366 {
367 Ident {
368 value: value.into(),
369 quote_style: None,
370 span,
371 }
372 }
373
374 pub fn with_quote_and_span<S>(quote: char, span: Span, value: S) -> Self
376 where
377 S: Into<String>,
378 {
379 assert!(quote == '\'' || quote == '"' || quote == '`' || quote == '[');
380 Ident {
381 value: value.into(),
382 quote_style: Some(quote),
383 span,
384 }
385 }
386}
387
388impl From<&str> for Ident {
389 fn from(value: &str) -> Self {
390 Ident {
391 value: value.to_string(),
392 quote_style: None,
393 span: Span::empty(),
394 }
395 }
396}
397
398pub(crate) fn fmt_ident(
399 f: &mut fmt::Formatter,
400 value: &str,
401 quote_style: Option<char>,
402) -> fmt::Result {
403 match quote_style {
404 Some('[') => write!(f, "[{value}]"),
405 Some(q) => {
406 let escaped = value::escape_quoted_string(value, q);
407 write!(f, "{q}{escaped}{q}")
408 }
409 None => f.write_str(value),
410 }
411}
412
413impl fmt::Display for Ident {
414 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
415 fmt_ident(f, &self.value, self.quote_style)
416 }
417}
418
419#[cfg(feature = "visitor")]
420impl Visit for Ident {
421 fn visit<V: Visitor>(&self, visitor: &mut V) -> ControlFlow<V::Break> {
422 visitor.pre_visit_ident(self)?;
423 visitor.post_visit_ident(self)
424 }
425}
426
427#[cfg(feature = "visitor")]
428impl VisitMut for Ident {
429 fn visit<V: VisitorMut>(&mut self, visitor: &mut V) -> ControlFlow<V::Break> {
430 visitor.pre_visit_ident(self)?;
431 visitor.post_visit_ident(self)
432 }
433}
434
435#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
437#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
438#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
439pub struct ObjectName(pub Vec<ObjectNamePart>);
440
441impl From<Vec<Ident>> for ObjectName {
442 fn from(idents: Vec<Ident>) -> Self {
443 ObjectName(idents.into_iter().map(ObjectNamePart::Identifier).collect())
444 }
445}
446
447impl From<Ident> for ObjectName {
448 fn from(ident: Ident) -> Self {
449 ObjectName(vec![ObjectNamePart::Identifier(ident)])
450 }
451}
452
453impl fmt::Display for ObjectName {
454 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
455 write!(f, "{}", display_separated(&self.0, "."))
456 }
457}
458
459#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
461#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
462#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
463pub enum ObjectNamePart {
464 Identifier(Ident),
466 Function(ObjectNamePartFunction),
468}
469
470impl ObjectNamePart {
471 pub fn as_ident(&self) -> Option<&Ident> {
473 match self {
474 ObjectNamePart::Identifier(ident) => Some(ident),
475 ObjectNamePart::Function(_) => None,
476 }
477 }
478}
479
480impl fmt::Display for ObjectNamePart {
481 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
482 match self {
483 ObjectNamePart::Identifier(ident) => write!(f, "{ident}"),
484 ObjectNamePart::Function(func) => write!(f, "{func}"),
485 }
486 }
487}
488
489#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
494#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
495#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
496pub struct ObjectNamePartFunction {
497 pub name: Ident,
499 pub args: Vec<FunctionArg>,
501}
502
503impl fmt::Display for ObjectNamePartFunction {
504 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
505 write!(f, "{}(", self.name)?;
506 write!(f, "{})", display_comma_separated(&self.args))
507 }
508}
509
510#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
513#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
514#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
515pub struct Array {
516 pub elem: Vec<Expr>,
518
519 pub named: bool,
521}
522
523impl fmt::Display for Array {
524 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
525 write!(
526 f,
527 "{}[{}]",
528 if self.named { "ARRAY" } else { "" },
529 display_comma_separated(&self.elem)
530 )
531 }
532}
533
534#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
543#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
544#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
545pub struct Interval {
546 pub value: Box<Expr>,
548 pub leading_field: Option<DateTimeField>,
550 pub leading_precision: Option<u64>,
552 pub last_field: Option<DateTimeField>,
554 pub fractional_seconds_precision: Option<u64>,
558}
559
560impl fmt::Display for Interval {
561 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
562 let value = self.value.as_ref();
563 match (
564 &self.leading_field,
565 self.leading_precision,
566 self.fractional_seconds_precision,
567 ) {
568 (
569 Some(DateTimeField::Second),
570 Some(leading_precision),
571 Some(fractional_seconds_precision),
572 ) => {
573 assert!(self.last_field.is_none());
576 write!(
577 f,
578 "INTERVAL {value} SECOND ({leading_precision}, {fractional_seconds_precision})"
579 )
580 }
581 _ => {
582 write!(f, "INTERVAL {value}")?;
583 if let Some(leading_field) = &self.leading_field {
584 write!(f, " {leading_field}")?;
585 }
586 if let Some(leading_precision) = self.leading_precision {
587 write!(f, " ({leading_precision})")?;
588 }
589 if let Some(last_field) = &self.last_field {
590 write!(f, " TO {last_field}")?;
591 }
592 if let Some(fractional_seconds_precision) = self.fractional_seconds_precision {
593 write!(f, " ({fractional_seconds_precision})")?;
594 }
595 Ok(())
596 }
597 }
598 }
599}
600
601#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
605#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
606#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
607pub struct StructField {
608 pub field_name: Option<Ident>,
610 pub field_type: DataType,
612 pub options: Option<Vec<SqlOption>>,
615}
616
617impl fmt::Display for StructField {
618 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
619 if let Some(name) = &self.field_name {
620 write!(f, "{name} {}", self.field_type)?;
621 } else {
622 write!(f, "{}", self.field_type)?;
623 }
624 if let Some(options) = &self.options {
625 write!(f, " OPTIONS({})", display_separated(options, ", "))
626 } else {
627 Ok(())
628 }
629 }
630}
631
632#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
636#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
637#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
638pub struct UnionField {
639 pub field_name: Ident,
641 pub field_type: DataType,
643}
644
645impl fmt::Display for UnionField {
646 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
647 write!(f, "{} {}", self.field_name, self.field_type)
648 }
649}
650
651#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
655#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
656#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
657pub struct DictionaryField {
658 pub key: Ident,
660 pub value: Box<Expr>,
662}
663
664impl fmt::Display for DictionaryField {
665 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
666 write!(f, "{}: {}", self.key, self.value)
667 }
668}
669
670#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
672#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
673#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
674pub struct Map {
675 pub entries: Vec<MapEntry>,
677}
678
679impl Display for Map {
680 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
681 write!(f, "MAP {{{}}}", display_comma_separated(&self.entries))
682 }
683}
684
685#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
689#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
690#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
691pub struct MapEntry {
692 pub key: Box<Expr>,
694 pub value: Box<Expr>,
696}
697
698impl fmt::Display for MapEntry {
699 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
700 write!(f, "{}: {}", self.key, self.value)
701 }
702}
703
704#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
707#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
708#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
709pub enum CastFormat {
710 Value(ValueWithSpan),
712 ValueAtTimeZone(ValueWithSpan, ValueWithSpan),
714}
715
716#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
718#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
719#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
720pub enum JsonPathElem {
721 Dot {
725 key: String,
727 quoted: bool,
729 },
730 Bracket {
735 key: Expr,
737 },
738 ColonBracket {
743 key: Expr,
745 },
746}
747
748#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
753#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
754#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
755pub struct JsonPath {
756 pub path: Vec<JsonPathElem>,
758}
759
760impl fmt::Display for JsonPath {
761 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
762 for (i, elem) in self.path.iter().enumerate() {
763 match elem {
764 JsonPathElem::Dot { key, quoted } => {
765 if i == 0 {
766 write!(f, ":")?;
767 } else {
768 write!(f, ".")?;
769 }
770
771 if *quoted {
772 write!(f, "\"{}\"", escape_double_quote_string(key))?;
773 } else {
774 write!(f, "{key}")?;
775 }
776 }
777 JsonPathElem::Bracket { key } => {
778 write!(f, "[{key}]")?;
779 }
780 JsonPathElem::ColonBracket { key } => {
781 write!(f, ":[{key}]")?;
782 }
783 }
784 }
785 Ok(())
786 }
787}
788
789#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
791#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
792#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
793pub enum CastKind {
794 Cast,
796 TryCast,
801 SafeCast,
805 DoubleColon,
807}
808
809#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
813#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
814#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
815pub enum ConstraintReferenceMatchKind {
816 Full,
818 Partial,
820 Simple,
822}
823
824impl fmt::Display for ConstraintReferenceMatchKind {
825 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
826 match self {
827 Self::Full => write!(f, "MATCH FULL"),
828 Self::Partial => write!(f, "MATCH PARTIAL"),
829 Self::Simple => write!(f, "MATCH SIMPLE"),
830 }
831 }
832}
833
834#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
841#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
842#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
843pub enum ExtractSyntax {
844 From,
846 Comma,
848}
849
850#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
859#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
860#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
861pub enum CeilFloorKind {
862 DateTimeField(DateTimeField),
864 Scale(ValueWithSpan),
866}
867
868#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
871#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
872#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
873pub struct CaseWhen {
874 pub condition: Expr,
876 pub result: Expr,
878}
879
880impl fmt::Display for CaseWhen {
881 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
882 f.write_str("WHEN ")?;
883 self.condition.fmt(f)?;
884 f.write_str(" THEN")?;
885 SpaceOrNewline.fmt(f)?;
886 Indent(&self.result).fmt(f)?;
887 Ok(())
888 }
889}
890
891#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
893#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
894#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
895pub enum InTarget {
896 List(Vec<Expr>),
898 Subquery(Box<Query>),
900 Unnest(Box<Expr>),
903 Table {
906 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
907 name: ObjectName,
909 args: Option<Vec<FunctionArg>>,
911 },
912}
913
914impl fmt::Display for InTarget {
915 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
916 match self {
917 InTarget::List(list) => write!(f, "({})", display_comma_separated(list)),
918 InTarget::Subquery(subquery) => write!(f, "({subquery})"),
919 InTarget::Unnest(array_expr) => write!(f, "UNNEST({array_expr})"),
920 InTarget::Table { name, args } => {
921 write!(f, "{name}")?;
922 if let Some(args) = args {
923 write!(f, "({})", display_comma_separated(args))?;
924 }
925 Ok(())
926 }
927 }
928 }
929}
930
931#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
949#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
950#[cfg_attr(
951 feature = "visitor",
952 derive(Visit, VisitMut),
953 visit(with = "visit_expr")
954)]
955pub enum Expr {
956 Identifier(Ident),
958 CompoundIdentifier(Vec<Ident>),
960 CompoundFieldAccess {
979 root: Box<Expr>,
981 access_chain: Vec<AccessExpr>,
983 },
984 JsonAccess {
990 value: Box<Expr>,
992 path: JsonPath,
994 },
995 IsFalse(Box<Expr>),
997 IsNotFalse(Box<Expr>),
999 IsTrue(Box<Expr>),
1001 IsNotTrue(Box<Expr>),
1003 IsNull(Box<Expr>),
1005 IsNotNull(Box<Expr>),
1007 IsUnknown(Box<Expr>),
1009 IsNotUnknown(Box<Expr>),
1011 IsDistinctFrom(Box<Expr>, Box<Expr>),
1013 IsNotDistinctFrom(Box<Expr>, Box<Expr>),
1015 IsJson {
1017 expr: Box<Expr>,
1019 kind: Option<JsonPredicateType>,
1021 unique_keys: Option<JsonKeyUniqueness>,
1023 negated: bool,
1025 },
1026 IsNormalized {
1028 expr: Box<Expr>,
1030 form: Option<NormalizationForm>,
1032 negated: bool,
1034 },
1035 In {
1037 expr: Box<Expr>,
1039 target: InTarget,
1041 negated: bool,
1043 global: bool,
1045 },
1046 Between {
1048 expr: Box<Expr>,
1050 negated: bool,
1052 low: Box<Expr>,
1054 high: Box<Expr>,
1056 },
1057 BinaryOp {
1059 left: Box<Expr>,
1061 op: BinaryOperator,
1063 right: Box<Expr>,
1065 },
1066 Like {
1068 negated: bool,
1070 any: bool,
1073 expr: Box<Expr>,
1075 pattern: Box<Expr>,
1077 escape_char: Option<Box<Expr>>,
1079 },
1080 ILike {
1082 negated: bool,
1084 any: bool,
1087 expr: Box<Expr>,
1089 pattern: Box<Expr>,
1091 escape_char: Option<Box<Expr>>,
1093 },
1094 SimilarTo {
1096 negated: bool,
1098 expr: Box<Expr>,
1100 pattern: Box<Expr>,
1102 escape_char: Option<Box<Expr>>,
1104 },
1105 RLike {
1107 negated: bool,
1109 expr: Box<Expr>,
1111 pattern: Box<Expr>,
1113 regexp: bool,
1115 },
1116 AnyOp {
1119 left: Box<Expr>,
1121 compare_op: BinaryOperator,
1123 right: Box<Expr>,
1125 is_some: bool,
1127 },
1128 AllOp {
1131 left: Box<Expr>,
1133 compare_op: BinaryOperator,
1135 right: Box<Expr>,
1137 },
1138
1139 UnaryOp {
1141 op: UnaryOperator,
1143 expr: Box<Expr>,
1145 },
1146 Convert {
1148 is_try: bool,
1151 expr: Box<Expr>,
1153 data_type: Option<DataType>,
1155 charset: Option<ObjectName>,
1157 target_before_value: bool,
1159 styles: Vec<Expr>,
1163 },
1164 Cast {
1166 kind: CastKind,
1168 expr: Box<Expr>,
1170 data_type: DataType,
1172 format: Option<CastFormat>,
1176 },
1177 AtTimeZone {
1179 timestamp: Box<Expr>,
1181 time_zone: Box<Expr>,
1183 },
1184 Extract {
1192 field: DateTimeField,
1194 syntax: ExtractSyntax,
1196 expr: Box<Expr>,
1198 },
1199 Ceil {
1206 expr: Box<Expr>,
1208 field: CeilFloorKind,
1210 },
1211 Floor {
1218 expr: Box<Expr>,
1220 field: CeilFloorKind,
1222 },
1223 Position {
1227 expr: Box<Expr>,
1229 r#in: Box<Expr>,
1231 },
1232 Substring {
1240 expr: Box<Expr>,
1242 substring_from: Option<Box<Expr>>,
1244 substring_for: Option<Box<Expr>>,
1246
1247 special: bool,
1251
1252 shorthand: bool,
1255 },
1256 Trim {
1262 trim_where: Option<TrimWhereField>,
1264 trim_what: Option<Box<Expr>>,
1266 expr: Box<Expr>,
1268 trim_characters: Option<Vec<Expr>>,
1270 },
1271 Overlay {
1275 expr: Box<Expr>,
1277 overlay_what: Box<Expr>,
1279 overlay_from: Box<Expr>,
1281 overlay_for: Option<Box<Expr>>,
1283 },
1284 Collate {
1286 expr: Box<Expr>,
1288 collation: ObjectName,
1290 },
1291 Nested(Box<Expr>),
1293 Value(ValueWithSpan),
1295 Prefixed {
1299 prefix: Ident,
1301 value: Box<Expr>,
1304 },
1305 TypedString(TypedString),
1309 Function(Function),
1311 Case {
1317 case_token: AttachedToken,
1319 end_token: AttachedToken,
1321 operand: Option<Box<Expr>>,
1323 conditions: Vec<CaseWhen>,
1325 else_result: Option<Box<Expr>>,
1327 },
1328 Exists {
1331 subquery: Box<Query>,
1333 negated: bool,
1335 },
1336 Subquery(Box<Query>),
1339 GroupingSets(Vec<Vec<Expr>>),
1341 Cube(Vec<Vec<Expr>>),
1343 Rollup(Vec<Vec<Expr>>),
1345 Tuple(Vec<Expr>),
1347 Struct {
1356 values: Vec<Expr>,
1358 fields: Vec<StructField>,
1360 },
1361 Named {
1368 expr: Box<Expr>,
1370 name: Ident,
1372 },
1373 Dictionary(Vec<DictionaryField>),
1381 Map(Map),
1389 Array(Array),
1391 Interval(Interval),
1393 MatchAgainst {
1404 columns: Vec<ObjectName>,
1406 match_value: ValueWithSpan,
1408 opt_search_modifier: Option<SearchModifier>,
1410 },
1411 Wildcard(AttachedToken),
1413 QualifiedWildcard(ObjectName, AttachedToken),
1416 OuterJoin(Box<Expr>),
1431 Prior(Box<Expr>),
1433 Lambda(LambdaFunction),
1444 MemberOf(MemberOf),
1446}
1447
1448impl Expr {
1449 pub fn value(value: impl Into<ValueWithSpan>) -> Self {
1451 Expr::Value(value.into())
1452 }
1453}
1454
1455#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1457#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1458#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1459pub enum Subscript {
1460 Index {
1462 index: Expr,
1464 },
1465
1466 Slice {
1488 lower_bound: Option<Expr>,
1490 upper_bound: Option<Expr>,
1492 stride: Option<Expr>,
1494 },
1495}
1496
1497impl fmt::Display for Subscript {
1498 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1499 match self {
1500 Subscript::Index { index } => write!(f, "{index}"),
1501 Subscript::Slice {
1502 lower_bound,
1503 upper_bound,
1504 stride,
1505 } => {
1506 if let Some(lower) = lower_bound {
1507 write!(f, "{lower}")?;
1508 }
1509 write!(f, ":")?;
1510 if let Some(upper) = upper_bound {
1511 write!(f, "{upper}")?;
1512 }
1513 if let Some(stride) = stride {
1514 write!(f, ":")?;
1515 write!(f, "{stride}")?;
1516 }
1517 Ok(())
1518 }
1519 }
1520 }
1521}
1522
1523#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1526#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1527#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1528pub enum AccessExpr {
1529 Dot(Expr),
1531 Subscript(Subscript),
1533}
1534
1535const fn is_number_expr(expr: &Expr) -> bool {
1536 matches!(expr, Expr::Value(v) if matches!(v.value, Value::Number(_, _)))
1537}
1538
1539impl fmt::Display for AccessExpr {
1540 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1541 match self {
1542 AccessExpr::Dot(expr) if is_number_expr(expr) => write!(f, " . {expr}"),
1543 AccessExpr::Dot(expr) => write!(f, ".{expr}"),
1544 AccessExpr::Subscript(subscript) => write!(f, "[{subscript}]"),
1545 }
1546 }
1547}
1548
1549#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1551#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1552#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1553pub struct LambdaFunction {
1554 pub params: OneOrManyWithParens<LambdaFunctionParameter>,
1556 pub body: Box<Expr>,
1558 pub syntax: LambdaSyntax,
1560}
1561
1562impl fmt::Display for LambdaFunction {
1563 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1564 match self.syntax {
1565 LambdaSyntax::Arrow => write!(f, "{} -> {}", self.params, self.body),
1566 LambdaSyntax::LambdaKeyword => {
1567 write!(f, "lambda ")?;
1570 match &self.params {
1571 OneOrManyWithParens::One(p) => write!(f, "{p}")?,
1572 OneOrManyWithParens::Many(ps) => write!(f, "{}", display_comma_separated(ps))?,
1573 };
1574 write!(f, " : {}", self.body)
1575 }
1576 }
1577 }
1578}
1579
1580#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1582#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1583#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1584pub struct LambdaFunctionParameter {
1585 pub name: Ident,
1587 pub data_type: Option<DataType>,
1590}
1591
1592impl fmt::Display for LambdaFunctionParameter {
1593 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1594 match &self.data_type {
1595 Some(dt) => write!(f, "{} {}", self.name, dt),
1596 None => write!(f, "{}", self.name),
1597 }
1598 }
1599}
1600
1601#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Copy)]
1603#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1604#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1605pub enum LambdaSyntax {
1606 Arrow,
1613 LambdaKeyword,
1618}
1619
1620#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1643#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1644#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1645pub enum OneOrManyWithParens<T> {
1646 One(T),
1648 Many(Vec<T>),
1650}
1651
1652impl<T> Deref for OneOrManyWithParens<T> {
1653 type Target = [T];
1654
1655 fn deref(&self) -> &[T] {
1656 match self {
1657 OneOrManyWithParens::One(one) => core::slice::from_ref(one),
1658 OneOrManyWithParens::Many(many) => many,
1659 }
1660 }
1661}
1662
1663impl<T> AsRef<[T]> for OneOrManyWithParens<T> {
1664 fn as_ref(&self) -> &[T] {
1665 self
1666 }
1667}
1668
1669impl<'a, T> IntoIterator for &'a OneOrManyWithParens<T> {
1670 type Item = &'a T;
1671 type IntoIter = core::slice::Iter<'a, T>;
1672
1673 fn into_iter(self) -> Self::IntoIter {
1674 self.iter()
1675 }
1676}
1677
1678#[derive(Debug, Clone)]
1680pub struct OneOrManyWithParensIntoIter<T> {
1681 inner: OneOrManyWithParensIntoIterInner<T>,
1682}
1683
1684#[derive(Debug, Clone)]
1685enum OneOrManyWithParensIntoIterInner<T> {
1686 One(core::iter::Once<T>),
1687 Many(<Vec<T> as IntoIterator>::IntoIter),
1688}
1689
1690impl<T> core::iter::FusedIterator for OneOrManyWithParensIntoIter<T>
1691where
1692 core::iter::Once<T>: core::iter::FusedIterator,
1693 <Vec<T> as IntoIterator>::IntoIter: core::iter::FusedIterator,
1694{
1695}
1696
1697impl<T> core::iter::ExactSizeIterator for OneOrManyWithParensIntoIter<T>
1698where
1699 core::iter::Once<T>: core::iter::ExactSizeIterator,
1700 <Vec<T> as IntoIterator>::IntoIter: core::iter::ExactSizeIterator,
1701{
1702}
1703
1704impl<T> core::iter::Iterator for OneOrManyWithParensIntoIter<T> {
1705 type Item = T;
1706
1707 fn next(&mut self) -> Option<Self::Item> {
1708 match &mut self.inner {
1709 OneOrManyWithParensIntoIterInner::One(one) => one.next(),
1710 OneOrManyWithParensIntoIterInner::Many(many) => many.next(),
1711 }
1712 }
1713
1714 fn size_hint(&self) -> (usize, Option<usize>) {
1715 match &self.inner {
1716 OneOrManyWithParensIntoIterInner::One(one) => one.size_hint(),
1717 OneOrManyWithParensIntoIterInner::Many(many) => many.size_hint(),
1718 }
1719 }
1720
1721 fn count(self) -> usize
1722 where
1723 Self: Sized,
1724 {
1725 match self.inner {
1726 OneOrManyWithParensIntoIterInner::One(one) => one.count(),
1727 OneOrManyWithParensIntoIterInner::Many(many) => many.count(),
1728 }
1729 }
1730
1731 fn fold<B, F>(mut self, init: B, f: F) -> B
1732 where
1733 Self: Sized,
1734 F: FnMut(B, Self::Item) -> B,
1735 {
1736 match &mut self.inner {
1737 OneOrManyWithParensIntoIterInner::One(one) => one.fold(init, f),
1738 OneOrManyWithParensIntoIterInner::Many(many) => many.fold(init, f),
1739 }
1740 }
1741}
1742
1743impl<T> core::iter::DoubleEndedIterator for OneOrManyWithParensIntoIter<T> {
1744 fn next_back(&mut self) -> Option<Self::Item> {
1745 match &mut self.inner {
1746 OneOrManyWithParensIntoIterInner::One(one) => one.next_back(),
1747 OneOrManyWithParensIntoIterInner::Many(many) => many.next_back(),
1748 }
1749 }
1750}
1751
1752impl<T> IntoIterator for OneOrManyWithParens<T> {
1753 type Item = T;
1754
1755 type IntoIter = OneOrManyWithParensIntoIter<T>;
1756
1757 fn into_iter(self) -> Self::IntoIter {
1758 let inner = match self {
1759 OneOrManyWithParens::One(one) => {
1760 OneOrManyWithParensIntoIterInner::One(core::iter::once(one))
1761 }
1762 OneOrManyWithParens::Many(many) => {
1763 OneOrManyWithParensIntoIterInner::Many(many.into_iter())
1764 }
1765 };
1766
1767 OneOrManyWithParensIntoIter { inner }
1768 }
1769}
1770
1771impl<T> fmt::Display for OneOrManyWithParens<T>
1772where
1773 T: fmt::Display,
1774{
1775 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1776 match self {
1777 OneOrManyWithParens::One(value) => write!(f, "{value}"),
1778 OneOrManyWithParens::Many(values) => {
1779 write!(f, "({})", display_comma_separated(values))
1780 }
1781 }
1782 }
1783}
1784
1785impl fmt::Display for CastFormat {
1786 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1787 match self {
1788 CastFormat::Value(v) => write!(f, "{v}"),
1789 CastFormat::ValueAtTimeZone(v, tz) => write!(f, "{v} AT TIME ZONE {tz}"),
1790 }
1791 }
1792}
1793
1794impl fmt::Display for Expr {
1795 #[cfg_attr(feature = "recursive-protection", recursive::recursive)]
1796 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1797 match self {
1798 Expr::Identifier(s) => write!(f, "{s}"),
1799 Expr::Wildcard(_) => f.write_str("*"),
1800 Expr::QualifiedWildcard(prefix, _) => write!(f, "{prefix}.*"),
1801 Expr::CompoundIdentifier(s) => write!(f, "{}", display_separated(s, ".")),
1802 Expr::CompoundFieldAccess { root, access_chain } => {
1803 write!(f, "{root}")?;
1804 let mut prev_is_number = is_number_expr(root);
1805 for field in access_chain {
1806 match field {
1807 AccessExpr::Dot(expr) if prev_is_number => write!(f, " . {expr}")?,
1808 _ => write!(f, "{field}")?,
1809 }
1810 prev_is_number = matches!(field, AccessExpr::Dot(expr) if is_number_expr(expr));
1811 }
1812 Ok(())
1813 }
1814 Expr::IsTrue(ast) => write!(f, "{ast} IS TRUE"),
1815 Expr::IsNotTrue(ast) => write!(f, "{ast} IS NOT TRUE"),
1816 Expr::IsFalse(ast) => write!(f, "{ast} IS FALSE"),
1817 Expr::IsNotFalse(ast) => write!(f, "{ast} IS NOT FALSE"),
1818 Expr::IsNull(ast) => write!(f, "{ast} IS NULL"),
1819 Expr::IsNotNull(ast) => write!(f, "{ast} IS NOT NULL"),
1820 Expr::IsUnknown(ast) => write!(f, "{ast} IS UNKNOWN"),
1821 Expr::IsNotUnknown(ast) => write!(f, "{ast} IS NOT UNKNOWN"),
1822 Expr::IsJson {
1823 expr,
1824 kind,
1825 unique_keys,
1826 negated,
1827 } => {
1828 write!(f, "{expr} IS ")?;
1829 if *negated {
1830 write!(f, "NOT ")?;
1831 }
1832 write!(f, "JSON")?;
1833 if let Some(kind) = kind {
1834 write!(f, " {kind}")?;
1835 }
1836 if let Some(unique_keys) = unique_keys {
1837 write!(f, " {unique_keys}")?;
1838 }
1839 Ok(())
1840 }
1841 Expr::In {
1842 expr,
1843 target,
1844 negated,
1845 global,
1846 } => write!(
1847 f,
1848 "{} {}{}IN {}",
1849 expr,
1850 if *global { "GLOBAL " } else { "" },
1851 if *negated { "NOT " } else { "" },
1852 target
1853 ),
1854 Expr::Between {
1855 expr,
1856 negated,
1857 low,
1858 high,
1859 } => write!(
1860 f,
1861 "{} {}BETWEEN {} AND {}",
1862 expr,
1863 if *negated { "NOT " } else { "" },
1864 low,
1865 high
1866 ),
1867 Expr::BinaryOp { left, op, right } => write!(f, "{left} {op} {right}"),
1868 Expr::Like {
1869 negated,
1870 expr,
1871 pattern,
1872 escape_char,
1873 any,
1874 } => match escape_char {
1875 Some(ch) => write!(
1876 f,
1877 "{} {}LIKE {}{} ESCAPE {}",
1878 expr,
1879 if *negated { "NOT " } else { "" },
1880 if *any { "ANY " } else { "" },
1881 pattern,
1882 ch
1883 ),
1884 _ => write!(
1885 f,
1886 "{} {}LIKE {}{}",
1887 expr,
1888 if *negated { "NOT " } else { "" },
1889 if *any { "ANY " } else { "" },
1890 pattern
1891 ),
1892 },
1893 Expr::ILike {
1894 negated,
1895 expr,
1896 pattern,
1897 escape_char,
1898 any,
1899 } => match escape_char {
1900 Some(ch) => write!(
1901 f,
1902 "{} {}ILIKE {}{} ESCAPE {}",
1903 expr,
1904 if *negated { "NOT " } else { "" },
1905 if *any { "ANY" } else { "" },
1906 pattern,
1907 ch
1908 ),
1909 _ => write!(
1910 f,
1911 "{} {}ILIKE {}{}",
1912 expr,
1913 if *negated { "NOT " } else { "" },
1914 if *any { "ANY " } else { "" },
1915 pattern
1916 ),
1917 },
1918 Expr::RLike {
1919 negated,
1920 expr,
1921 pattern,
1922 regexp,
1923 } => write!(
1924 f,
1925 "{} {}{} {}",
1926 expr,
1927 if *negated { "NOT " } else { "" },
1928 if *regexp { "REGEXP" } else { "RLIKE" },
1929 pattern
1930 ),
1931 Expr::IsNormalized {
1932 expr,
1933 form,
1934 negated,
1935 } => {
1936 let not_ = if *negated { "NOT " } else { "" };
1937 if let Some(form) = form {
1938 write!(f, "{} IS {}{} NORMALIZED", expr, not_, form)
1939 } else {
1940 write!(f, "{expr} IS {not_}NORMALIZED")
1941 }
1942 }
1943 Expr::SimilarTo {
1944 negated,
1945 expr,
1946 pattern,
1947 escape_char,
1948 } => match escape_char {
1949 Some(ch) => write!(
1950 f,
1951 "{} {}SIMILAR TO {} ESCAPE {}",
1952 expr,
1953 if *negated { "NOT " } else { "" },
1954 pattern,
1955 ch
1956 ),
1957 _ => write!(
1958 f,
1959 "{} {}SIMILAR TO {}",
1960 expr,
1961 if *negated { "NOT " } else { "" },
1962 pattern
1963 ),
1964 },
1965 Expr::AnyOp {
1966 left,
1967 compare_op,
1968 right,
1969 is_some,
1970 } => {
1971 let add_parens = !matches!(right.as_ref(), Expr::Subquery(_));
1972 write!(
1973 f,
1974 "{left} {compare_op} {}{}{right}{}",
1975 if *is_some { "SOME" } else { "ANY" },
1976 if add_parens { "(" } else { "" },
1977 if add_parens { ")" } else { "" },
1978 )
1979 }
1980 Expr::AllOp {
1981 left,
1982 compare_op,
1983 right,
1984 } => {
1985 let add_parens = !matches!(right.as_ref(), Expr::Subquery(_));
1986 write!(
1987 f,
1988 "{left} {compare_op} ALL{}{right}{}",
1989 if add_parens { "(" } else { "" },
1990 if add_parens { ")" } else { "" },
1991 )
1992 }
1993 Expr::UnaryOp { op, expr } => match op {
1994 UnaryOperator::PGPostfixFactorial => {
1995 if matches!(
1996 expr.as_ref(),
1997 Expr::UnaryOp {
1998 op: UnaryOperator::PGPostfixFactorial,
1999 ..
2000 }
2001 ) {
2002 write!(f, "{expr} {op}")
2003 } else {
2004 write!(f, "{expr}{op}")
2005 }
2006 }
2007 UnaryOperator::Not
2008 | UnaryOperator::BitwiseNot
2009 | UnaryOperator::Hash
2010 | UnaryOperator::AtDashAt
2011 | UnaryOperator::DoubleAt
2012 | UnaryOperator::PGAbs
2013 | UnaryOperator::QuestionDash
2014 | UnaryOperator::QuestionPipe
2015 | UnaryOperator::PGSquareRoot
2016 | UnaryOperator::PGCubeRoot => write!(f, "{op} {expr}"),
2017 UnaryOperator::Minus | UnaryOperator::BangNot => {
2018 write!(f, "{op}")?;
2021 if starts_with_operator_char(expr) {
2022 f.write_str(" ")?;
2023 }
2024 write!(f, "{expr}")
2025 }
2026 UnaryOperator::Plus | UnaryOperator::PGPrefixFactorial => write!(f, "{op}{expr}"),
2027 },
2028 Expr::Convert {
2029 is_try,
2030 expr,
2031 target_before_value,
2032 data_type,
2033 charset,
2034 styles,
2035 } => {
2036 write!(f, "{}CONVERT(", if *is_try { "TRY_" } else { "" })?;
2037 if let Some(data_type) = data_type {
2038 if let Some(charset) = charset {
2039 write!(f, "{expr}, {data_type} CHARACTER SET {charset}")
2040 } else if *target_before_value {
2041 write!(f, "{data_type}, {expr}")
2042 } else {
2043 write!(f, "{expr}, {data_type}")
2044 }
2045 } else if let Some(charset) = charset {
2046 write!(f, "{expr} USING {charset}")
2047 } else {
2048 write!(f, "{expr}") }?;
2050 if !styles.is_empty() {
2051 write!(f, ", {}", display_comma_separated(styles))?;
2052 }
2053 write!(f, ")")
2054 }
2055 Expr::Cast {
2056 kind,
2057 expr,
2058 data_type,
2059 format,
2060 } => match kind {
2061 CastKind::Cast => {
2062 if matches!(data_type, DataType::Unspecified) {
2063 write!(f, "CAST({expr} AS")?;
2064 } else {
2065 write!(f, "CAST({expr} AS {data_type}")?;
2066 }
2067 if let Some(format) = format {
2068 write!(f, " FORMAT {format}")?;
2069 }
2070 write!(f, ")")
2071 }
2072 CastKind::TryCast => {
2073 if let Some(format) = format {
2074 write!(f, "TRY_CAST({expr} AS {data_type} FORMAT {format})")
2075 } else {
2076 write!(f, "TRY_CAST({expr} AS {data_type})")
2077 }
2078 }
2079 CastKind::SafeCast => {
2080 if let Some(format) = format {
2081 write!(f, "SAFE_CAST({expr} AS {data_type} FORMAT {format})")
2082 } else {
2083 write!(f, "SAFE_CAST({expr} AS {data_type})")
2084 }
2085 }
2086 CastKind::DoubleColon => {
2087 write!(f, "{expr}::{data_type}")
2088 }
2089 },
2090 Expr::Extract {
2091 field,
2092 syntax,
2093 expr,
2094 } => match syntax {
2095 ExtractSyntax::From => write!(f, "EXTRACT({field} FROM {expr})"),
2096 ExtractSyntax::Comma => write!(f, "EXTRACT({field}, {expr})"),
2097 },
2098 Expr::Ceil { expr, field } => match field {
2099 CeilFloorKind::DateTimeField(DateTimeField::NoDateTime) => {
2100 write!(f, "CEIL({expr})")
2101 }
2102 CeilFloorKind::DateTimeField(dt_field) => write!(f, "CEIL({expr} TO {dt_field})"),
2103 CeilFloorKind::Scale(s) => write!(f, "CEIL({expr}, {s})"),
2104 },
2105 Expr::Floor { expr, field } => match field {
2106 CeilFloorKind::DateTimeField(DateTimeField::NoDateTime) => {
2107 write!(f, "FLOOR({expr})")
2108 }
2109 CeilFloorKind::DateTimeField(dt_field) => write!(f, "FLOOR({expr} TO {dt_field})"),
2110 CeilFloorKind::Scale(s) => write!(f, "FLOOR({expr}, {s})"),
2111 },
2112 Expr::Position { expr, r#in } => write!(f, "POSITION({expr} IN {in})"),
2113 Expr::Collate { expr, collation } => write!(f, "{expr} COLLATE {collation}"),
2114 Expr::Nested(ast) => write!(f, "({ast})"),
2115 Expr::Value(v) => write!(f, "{v}"),
2116 Expr::Prefixed { prefix, value } => write!(f, "{prefix} {value}"),
2117 Expr::TypedString(ts) => ts.fmt(f),
2118 Expr::Function(fun) => fun.fmt(f),
2119 Expr::Case {
2120 case_token: _,
2121 end_token: _,
2122 operand,
2123 conditions,
2124 else_result,
2125 } => {
2126 f.write_str("CASE")?;
2127 if let Some(operand) = operand {
2128 f.write_str(" ")?;
2129 operand.fmt(f)?;
2130 }
2131 for when in conditions {
2132 SpaceOrNewline.fmt(f)?;
2133 Indent(when).fmt(f)?;
2134 }
2135 if let Some(else_result) = else_result {
2136 SpaceOrNewline.fmt(f)?;
2137 Indent("ELSE").fmt(f)?;
2138 SpaceOrNewline.fmt(f)?;
2139 Indent(Indent(else_result)).fmt(f)?;
2140 }
2141 SpaceOrNewline.fmt(f)?;
2142 f.write_str("END")
2143 }
2144 Expr::Exists { subquery, negated } => write!(
2145 f,
2146 "{}EXISTS ({})",
2147 if *negated { "NOT " } else { "" },
2148 subquery
2149 ),
2150 Expr::Subquery(s) => write!(f, "({s})"),
2151 Expr::GroupingSets(sets) => {
2152 write!(f, "GROUPING SETS (")?;
2153 let mut sep = "";
2154 for set in sets {
2155 write!(f, "{sep}")?;
2156 sep = ", ";
2157 write!(f, "({})", display_comma_separated(set))?;
2158 }
2159 write!(f, ")")
2160 }
2161 Expr::Cube(sets) => {
2162 write!(f, "CUBE (")?;
2163 let mut sep = "";
2164 for set in sets {
2165 write!(f, "{sep}")?;
2166 sep = ", ";
2167 if set.len() == 1 {
2168 write!(f, "{}", set[0])?;
2169 } else {
2170 write!(f, "({})", display_comma_separated(set))?;
2171 }
2172 }
2173 write!(f, ")")
2174 }
2175 Expr::Rollup(sets) => {
2176 write!(f, "ROLLUP (")?;
2177 let mut sep = "";
2178 for set in sets {
2179 write!(f, "{sep}")?;
2180 sep = ", ";
2181 if set.len() == 1 {
2182 write!(f, "{}", set[0])?;
2183 } else {
2184 write!(f, "({})", display_comma_separated(set))?;
2185 }
2186 }
2187 write!(f, ")")
2188 }
2189 Expr::Substring {
2190 expr,
2191 substring_from,
2192 substring_for,
2193 special,
2194 shorthand,
2195 } => {
2196 f.write_str("SUBSTR")?;
2197 if !*shorthand {
2198 f.write_str("ING")?;
2199 }
2200 write!(f, "({expr}")?;
2201 if let Some(from_part) = substring_from {
2202 if *special {
2203 write!(f, ", {from_part}")?;
2204 } else {
2205 write!(f, " FROM {from_part}")?;
2206 }
2207 }
2208 if let Some(for_part) = substring_for {
2209 if *special {
2210 write!(f, ", {for_part}")?;
2211 } else {
2212 write!(f, " FOR {for_part}")?;
2213 }
2214 }
2215
2216 write!(f, ")")
2217 }
2218 Expr::Overlay {
2219 expr,
2220 overlay_what,
2221 overlay_from,
2222 overlay_for,
2223 } => {
2224 write!(
2225 f,
2226 "OVERLAY({expr} PLACING {overlay_what} FROM {overlay_from}"
2227 )?;
2228 if let Some(for_part) = overlay_for {
2229 write!(f, " FOR {for_part}")?;
2230 }
2231
2232 write!(f, ")")
2233 }
2234 Expr::IsDistinctFrom(a, b) => write!(f, "{a} IS DISTINCT FROM {b}"),
2235 Expr::IsNotDistinctFrom(a, b) => write!(f, "{a} IS NOT DISTINCT FROM {b}"),
2236 Expr::Trim {
2237 expr,
2238 trim_where,
2239 trim_what,
2240 trim_characters,
2241 } => {
2242 write!(f, "TRIM(")?;
2243 if let Some(ident) = trim_where {
2244 write!(f, "{ident} ")?;
2245 }
2246 if let Some(trim_char) = trim_what {
2247 write!(f, "{trim_char} FROM {expr}")?;
2248 } else {
2249 write!(f, "{expr}")?;
2250 }
2251 if let Some(characters) = trim_characters {
2252 write!(f, ", {}", display_comma_separated(characters))?;
2253 }
2254
2255 write!(f, ")")
2256 }
2257 Expr::Tuple(exprs) => {
2258 write!(f, "({})", display_comma_separated(exprs))
2259 }
2260 Expr::Struct { values, fields } => {
2261 if !fields.is_empty() {
2262 write!(
2263 f,
2264 "STRUCT<{}>({})",
2265 display_comma_separated(fields),
2266 display_comma_separated(values)
2267 )
2268 } else {
2269 write!(f, "STRUCT({})", display_comma_separated(values))
2270 }
2271 }
2272 Expr::Named { expr, name } => {
2273 write!(f, "{expr} AS {name}")
2274 }
2275 Expr::Dictionary(fields) => {
2276 write!(f, "{{{}}}", display_comma_separated(fields))
2277 }
2278 Expr::Map(map) => {
2279 write!(f, "{map}")
2280 }
2281 Expr::Array(set) => {
2282 write!(f, "{set}")
2283 }
2284 Expr::JsonAccess { value, path } => {
2285 write!(f, "{value}{path}")
2286 }
2287 Expr::AtTimeZone {
2288 timestamp,
2289 time_zone,
2290 } => {
2291 write!(f, "{timestamp} AT TIME ZONE {time_zone}")
2292 }
2293 Expr::Interval(interval) => {
2294 write!(f, "{interval}")
2295 }
2296 Expr::MatchAgainst {
2297 columns,
2298 match_value: match_expr,
2299 opt_search_modifier,
2300 } => {
2301 write!(f, "MATCH ({}) AGAINST ", display_comma_separated(columns),)?;
2302
2303 if let Some(search_modifier) = opt_search_modifier {
2304 write!(f, "({match_expr} {search_modifier})")?;
2305 } else {
2306 write!(f, "({match_expr})")?;
2307 }
2308
2309 Ok(())
2310 }
2311 Expr::OuterJoin(expr) => {
2312 write!(f, "{expr} (+)")
2313 }
2314 Expr::Prior(expr) => write!(f, "PRIOR {expr}"),
2315 Expr::Lambda(lambda) => write!(f, "{lambda}"),
2316 Expr::MemberOf(member_of) => write!(f, "{member_of}"),
2317 }
2318 }
2319}
2320
2321#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2330#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2331#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2332pub enum WindowType {
2333 WindowSpec(WindowSpec),
2335 NamedWindow(Ident),
2337}
2338
2339impl Display for WindowType {
2340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2341 match self {
2342 WindowType::WindowSpec(spec) => {
2343 f.write_str("(")?;
2344 NewLine.fmt(f)?;
2345 Indent(spec).fmt(f)?;
2346 NewLine.fmt(f)?;
2347 f.write_str(")")
2348 }
2349 WindowType::NamedWindow(name) => name.fmt(f),
2350 }
2351 }
2352}
2353
2354#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2356#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2357#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2358pub struct WindowSpec {
2359 pub window_name: Option<Ident>,
2367 pub partition_by: Vec<Expr>,
2369 pub order_by: Vec<OrderByExpr>,
2371 pub window_frame: Option<WindowFrame>,
2373}
2374
2375impl fmt::Display for WindowSpec {
2376 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2377 let mut is_first = true;
2378 if let Some(window_name) = &self.window_name {
2379 if !is_first {
2380 SpaceOrNewline.fmt(f)?;
2381 }
2382 is_first = false;
2383 write!(f, "{window_name}")?;
2384 }
2385 if !self.partition_by.is_empty() {
2386 if !is_first {
2387 SpaceOrNewline.fmt(f)?;
2388 }
2389 is_first = false;
2390 write!(
2391 f,
2392 "PARTITION BY {}",
2393 display_comma_separated(&self.partition_by)
2394 )?;
2395 }
2396 if !self.order_by.is_empty() {
2397 if !is_first {
2398 SpaceOrNewline.fmt(f)?;
2399 }
2400 is_first = false;
2401 write!(f, "ORDER BY {}", display_comma_separated(&self.order_by))?;
2402 }
2403 if let Some(window_frame) = &self.window_frame {
2404 if !is_first {
2405 SpaceOrNewline.fmt(f)?;
2406 }
2407 if let Some(end_bound) = &window_frame.end_bound {
2408 write!(
2409 f,
2410 "{} BETWEEN {} AND {}",
2411 window_frame.units, window_frame.start_bound, end_bound
2412 )?;
2413 } else {
2414 write!(f, "{} {}", window_frame.units, window_frame.start_bound)?;
2415 }
2416 }
2417 Ok(())
2418 }
2419}
2420
2421#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2427#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2428#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2429pub struct WindowFrame {
2430 pub units: WindowFrameUnits,
2432 pub start_bound: WindowFrameBound,
2434 pub end_bound: Option<WindowFrameBound>,
2438 }
2440
2441impl Default for WindowFrame {
2442 fn default() -> Self {
2446 Self {
2447 units: WindowFrameUnits::Range,
2448 start_bound: WindowFrameBound::Preceding(None),
2449 end_bound: None,
2450 }
2451 }
2452}
2453
2454#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2455#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2456#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2457pub enum WindowFrameUnits {
2459 Rows,
2461 Range,
2463 Groups,
2465}
2466
2467impl fmt::Display for WindowFrameUnits {
2468 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2469 f.write_str(match self {
2470 WindowFrameUnits::Rows => "ROWS",
2471 WindowFrameUnits::Range => "RANGE",
2472 WindowFrameUnits::Groups => "GROUPS",
2473 })
2474 }
2475}
2476
2477#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2481#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2482#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2483pub enum NullTreatment {
2485 IgnoreNulls,
2487 RespectNulls,
2489}
2490
2491impl fmt::Display for NullTreatment {
2492 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2493 f.write_str(match self {
2494 NullTreatment::IgnoreNulls => "IGNORE NULLS",
2495 NullTreatment::RespectNulls => "RESPECT NULLS",
2496 })
2497 }
2498}
2499
2500#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2502#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2503#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2504pub enum WindowFrameBound {
2505 CurrentRow,
2507 Preceding(Option<Box<Expr>>),
2509 Following(Option<Box<Expr>>),
2511}
2512
2513impl fmt::Display for WindowFrameBound {
2514 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2515 match self {
2516 WindowFrameBound::CurrentRow => f.write_str("CURRENT ROW"),
2517 WindowFrameBound::Preceding(None) => f.write_str("UNBOUNDED PRECEDING"),
2518 WindowFrameBound::Following(None) => f.write_str("UNBOUNDED FOLLOWING"),
2519 WindowFrameBound::Preceding(Some(n)) => write!(f, "{n} PRECEDING"),
2520 WindowFrameBound::Following(Some(n)) => write!(f, "{n} FOLLOWING"),
2521 }
2522 }
2523}
2524
2525#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2526#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2527#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2528pub enum AddDropSync {
2530 ADD,
2532 DROP,
2534 SYNC,
2536}
2537
2538impl fmt::Display for AddDropSync {
2539 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2540 match self {
2541 AddDropSync::SYNC => f.write_str("SYNC PARTITIONS"),
2542 AddDropSync::DROP => f.write_str("DROP PARTITIONS"),
2543 AddDropSync::ADD => f.write_str("ADD PARTITIONS"),
2544 }
2545 }
2546}
2547
2548#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2549#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2550#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2551pub enum ShowCreateObject {
2553 Event,
2555 Function,
2557 Procedure,
2559 Table,
2561 Trigger,
2563 View,
2565}
2566
2567impl fmt::Display for ShowCreateObject {
2568 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2569 match self {
2570 ShowCreateObject::Event => f.write_str("EVENT"),
2571 ShowCreateObject::Function => f.write_str("FUNCTION"),
2572 ShowCreateObject::Procedure => f.write_str("PROCEDURE"),
2573 ShowCreateObject::Table => f.write_str("TABLE"),
2574 ShowCreateObject::Trigger => f.write_str("TRIGGER"),
2575 ShowCreateObject::View => f.write_str("VIEW"),
2576 }
2577 }
2578}
2579
2580#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2581#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2582#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2583pub enum CommentObject {
2585 Collation,
2587 Column,
2589 Database,
2591 Domain,
2593 Extension,
2595 ForeignTable,
2597 Function,
2599 Index,
2601 MaterializedView,
2603 Procedure,
2605 Role,
2607 Schema,
2609 Sequence,
2611 Table,
2613 Type,
2615 User,
2617 View,
2619}
2620
2621impl fmt::Display for CommentObject {
2622 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2623 match self {
2624 CommentObject::Collation => f.write_str("COLLATION"),
2625 CommentObject::Column => f.write_str("COLUMN"),
2626 CommentObject::Database => f.write_str("DATABASE"),
2627 CommentObject::Domain => f.write_str("DOMAIN"),
2628 CommentObject::Extension => f.write_str("EXTENSION"),
2629 CommentObject::ForeignTable => f.write_str("FOREIGN TABLE"),
2630 CommentObject::Function => f.write_str("FUNCTION"),
2631 CommentObject::Index => f.write_str("INDEX"),
2632 CommentObject::MaterializedView => f.write_str("MATERIALIZED VIEW"),
2633 CommentObject::Procedure => f.write_str("PROCEDURE"),
2634 CommentObject::Role => f.write_str("ROLE"),
2635 CommentObject::Schema => f.write_str("SCHEMA"),
2636 CommentObject::Sequence => f.write_str("SEQUENCE"),
2637 CommentObject::Table => f.write_str("TABLE"),
2638 CommentObject::Type => f.write_str("TYPE"),
2639 CommentObject::User => f.write_str("USER"),
2640 CommentObject::View => f.write_str("VIEW"),
2641 }
2642 }
2643}
2644
2645#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2646#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2647#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2648pub enum Password {
2650 Password(Expr),
2652 NullPassword,
2654}
2655
2656#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2673#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2674#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2675pub struct CaseStatement {
2676 pub case_token: AttachedToken,
2678 pub match_expr: Option<Expr>,
2680 pub when_blocks: Vec<ConditionalStatementBlock>,
2682 pub else_block: Option<ConditionalStatementBlock>,
2684 pub end_case_token: AttachedToken,
2686}
2687
2688impl fmt::Display for CaseStatement {
2689 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2690 let CaseStatement {
2691 case_token: _,
2692 match_expr,
2693 when_blocks,
2694 else_block,
2695 end_case_token: AttachedToken(end),
2696 } = self;
2697
2698 write!(f, "CASE")?;
2699
2700 if let Some(expr) = match_expr {
2701 write!(f, " {expr}")?;
2702 }
2703
2704 if !when_blocks.is_empty() {
2705 write!(f, " {}", display_separated(when_blocks, " "))?;
2706 }
2707
2708 if let Some(else_block) = else_block {
2709 write!(f, " {else_block}")?;
2710 }
2711
2712 write!(f, " END")?;
2713
2714 if let Token::Word(w) = &end.token {
2715 if w.keyword == Keyword::CASE {
2716 write!(f, " CASE")?;
2717 }
2718 }
2719
2720 Ok(())
2721 }
2722}
2723
2724#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2746#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2747#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2748pub struct IfStatement {
2749 pub if_block: ConditionalStatementBlock,
2751 pub elseif_blocks: Vec<ConditionalStatementBlock>,
2753 pub else_block: Option<ConditionalStatementBlock>,
2755 pub end_token: Option<AttachedToken>,
2757}
2758
2759impl fmt::Display for IfStatement {
2760 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2761 let IfStatement {
2762 if_block,
2763 elseif_blocks,
2764 else_block,
2765 end_token,
2766 } = self;
2767
2768 write!(f, "{if_block}")?;
2769
2770 for elseif_block in elseif_blocks {
2771 write!(f, " {elseif_block}")?;
2772 }
2773
2774 if let Some(else_block) = else_block {
2775 write!(f, " {else_block}")?;
2776 }
2777
2778 if let Some(AttachedToken(end_token)) = end_token {
2779 write!(f, " END {end_token}")?;
2780 }
2781
2782 Ok(())
2783 }
2784}
2785
2786#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2798#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2799#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2800pub struct WhileStatement {
2801 pub while_block: ConditionalStatementBlock,
2803}
2804
2805impl fmt::Display for WhileStatement {
2806 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2807 let WhileStatement { while_block } = self;
2808 write!(f, "{while_block}")?;
2809 Ok(())
2810 }
2811}
2812
2813#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2838#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2839#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2840pub struct ConditionalStatementBlock {
2841 pub start_token: AttachedToken,
2843 pub condition: Option<Expr>,
2845 pub then_token: Option<AttachedToken>,
2847 pub conditional_statements: ConditionalStatements,
2849}
2850
2851impl ConditionalStatementBlock {
2852 pub fn statements(&self) -> &Vec<Statement> {
2854 self.conditional_statements.statements()
2855 }
2856}
2857
2858impl fmt::Display for ConditionalStatementBlock {
2859 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2860 let ConditionalStatementBlock {
2861 start_token: AttachedToken(start_token),
2862 condition,
2863 then_token,
2864 conditional_statements,
2865 } = self;
2866
2867 write!(f, "{start_token}")?;
2868
2869 if let Some(condition) = condition {
2870 write!(f, " {condition}")?;
2871 }
2872
2873 if then_token.is_some() {
2874 write!(f, " THEN")?;
2875 }
2876
2877 if !conditional_statements.statements().is_empty() {
2878 write!(f, " {conditional_statements}")?;
2879 }
2880
2881 Ok(())
2882 }
2883}
2884
2885#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2887#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2888#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2889pub enum ConditionalStatements {
2891 Sequence {
2893 statements: Vec<Statement>,
2895 },
2896 BeginEnd(BeginEndStatements),
2898}
2899
2900impl ConditionalStatements {
2901 pub fn statements(&self) -> &Vec<Statement> {
2903 match self {
2904 ConditionalStatements::Sequence { statements } => statements,
2905 ConditionalStatements::BeginEnd(bes) => &bes.statements,
2906 }
2907 }
2908}
2909
2910impl fmt::Display for ConditionalStatements {
2911 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2912 match self {
2913 ConditionalStatements::Sequence { statements } => {
2914 if !statements.is_empty() {
2915 format_statement_list(f, statements)?;
2916 }
2917 Ok(())
2918 }
2919 ConditionalStatements::BeginEnd(bes) => write!(f, "{bes}"),
2920 }
2921 }
2922}
2923
2924#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2933#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2934#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2935pub struct BeginEndStatements {
2936 pub begin_token: AttachedToken,
2938 pub statements: Vec<Statement>,
2940 pub end_token: AttachedToken,
2942}
2943
2944impl fmt::Display for BeginEndStatements {
2945 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2946 let BeginEndStatements {
2947 begin_token: AttachedToken(begin_token),
2948 statements,
2949 end_token: AttachedToken(end_token),
2950 } = self;
2951
2952 if begin_token.token != Token::EOF {
2953 write!(f, "{begin_token} ")?;
2954 }
2955 if !statements.is_empty() {
2956 format_statement_list(f, statements)?;
2957 }
2958 if end_token.token != Token::EOF {
2959 write!(f, " {end_token}")?;
2960 }
2961 Ok(())
2962 }
2963}
2964
2965#[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 struct RaiseStatement {
2980 pub value: Option<RaiseStatementValue>,
2982}
2983
2984impl fmt::Display for RaiseStatement {
2985 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2986 let RaiseStatement { value } = self;
2987
2988 write!(f, "RAISE")?;
2989 if let Some(value) = value {
2990 write!(f, " {value}")?;
2991 }
2992
2993 Ok(())
2994 }
2995}
2996
2997#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2999#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3000#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3001pub enum RaiseStatementValue {
3002 UsingMessage(Expr),
3004 Expr(Expr),
3006}
3007
3008impl fmt::Display for RaiseStatementValue {
3009 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3010 match self {
3011 RaiseStatementValue::Expr(expr) => write!(f, "{expr}"),
3012 RaiseStatementValue::UsingMessage(expr) => write!(f, "USING MESSAGE = {expr}"),
3013 }
3014 }
3015}
3016
3017#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3025#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3026#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3027pub struct ThrowStatement {
3028 pub error_number: Option<Box<Expr>>,
3030 pub message: Option<Box<Expr>>,
3032 pub state: Option<Box<Expr>>,
3034}
3035
3036impl fmt::Display for ThrowStatement {
3037 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3038 let ThrowStatement {
3039 error_number,
3040 message,
3041 state,
3042 } = self;
3043
3044 write!(f, "THROW")?;
3045 if let (Some(error_number), Some(message), Some(state)) = (error_number, message, state) {
3046 write!(f, " {error_number}, {message}, {state}")?;
3047 }
3048 Ok(())
3049 }
3050}
3051
3052#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3060#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3061#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3062pub enum DeclareAssignment {
3063 Expr(Box<Expr>),
3065
3066 Default(Box<Expr>),
3068
3069 DuckAssignment(Box<Expr>),
3076
3077 For(Box<Expr>),
3084
3085 MsSqlAssignment(Box<Expr>),
3092}
3093
3094impl fmt::Display for DeclareAssignment {
3095 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3096 match self {
3097 DeclareAssignment::Expr(expr) => {
3098 write!(f, "{expr}")
3099 }
3100 DeclareAssignment::Default(expr) => {
3101 write!(f, "DEFAULT {expr}")
3102 }
3103 DeclareAssignment::DuckAssignment(expr) => {
3104 write!(f, ":= {expr}")
3105 }
3106 DeclareAssignment::MsSqlAssignment(expr) => {
3107 write!(f, "= {expr}")
3108 }
3109 DeclareAssignment::For(expr) => {
3110 write!(f, "FOR {expr}")
3111 }
3112 }
3113 }
3114}
3115
3116#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3118#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3119#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3120pub enum DeclareType {
3121 Cursor,
3127
3128 ResultSet,
3136
3137 Exception,
3145}
3146
3147impl fmt::Display for DeclareType {
3148 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3149 match self {
3150 DeclareType::Cursor => {
3151 write!(f, "CURSOR")
3152 }
3153 DeclareType::ResultSet => {
3154 write!(f, "RESULTSET")
3155 }
3156 DeclareType::Exception => {
3157 write!(f, "EXCEPTION")
3158 }
3159 }
3160 }
3161}
3162
3163#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash, Default)]
3165#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3166#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3167pub enum DeclareSeparator {
3168 #[default]
3172 Semicolon,
3173 Comma,
3177}
3178
3179#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3192#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3193#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3194pub struct Declare {
3195 pub names: Vec<Ident>,
3198 pub data_type: Option<DataType>,
3201 pub assignment: Option<DeclareAssignment>,
3203 pub declare_type: Option<DeclareType>,
3205 pub binary: Option<bool>,
3207 pub sensitive: Option<bool>,
3211 pub scroll: Option<bool>,
3215 pub hold: Option<bool>,
3219 pub for_query: Option<Box<Query>>,
3221}
3222
3223impl fmt::Display for Declare {
3224 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3225 let Declare {
3226 names,
3227 data_type,
3228 assignment,
3229 declare_type,
3230 binary,
3231 sensitive,
3232 scroll,
3233 hold,
3234 for_query,
3235 } = self;
3236 write!(f, "{}", display_comma_separated(names))?;
3237
3238 if let Some(true) = binary {
3239 write!(f, " BINARY")?;
3240 }
3241
3242 if let Some(sensitive) = sensitive {
3243 if *sensitive {
3244 write!(f, " INSENSITIVE")?;
3245 } else {
3246 write!(f, " ASENSITIVE")?;
3247 }
3248 }
3249
3250 if let Some(scroll) = scroll {
3251 if *scroll {
3252 write!(f, " SCROLL")?;
3253 } else {
3254 write!(f, " NO SCROLL")?;
3255 }
3256 }
3257
3258 if let Some(declare_type) = declare_type {
3259 write!(f, " {declare_type}")?;
3260 }
3261
3262 if let Some(hold) = hold {
3263 if *hold {
3264 write!(f, " WITH HOLD")?;
3265 } else {
3266 write!(f, " WITHOUT HOLD")?;
3267 }
3268 }
3269
3270 if let Some(query) = for_query {
3271 write!(f, " FOR {query}")?;
3272 }
3273
3274 if let Some(data_type) = data_type {
3275 write!(f, " {data_type}")?;
3276 }
3277
3278 if let Some(expr) = assignment {
3279 write!(f, " {expr}")?;
3280 }
3281 Ok(())
3282 }
3283}
3284
3285#[derive(Debug, Default, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3287#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3288#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3289pub enum CreateTableOptions {
3291 #[default]
3293 None,
3294 With(Vec<SqlOption>),
3296 Options(Vec<SqlOption>),
3298 Plain(Vec<SqlOption>),
3300 TableProperties(Vec<SqlOption>),
3302}
3303
3304impl fmt::Display for CreateTableOptions {
3305 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3306 match self {
3307 CreateTableOptions::With(with_options) => {
3308 write!(f, "WITH ({})", display_comma_separated(with_options))
3309 }
3310 CreateTableOptions::Options(options) => {
3311 write!(f, "OPTIONS({})", display_comma_separated(options))
3312 }
3313 CreateTableOptions::TableProperties(options) => {
3314 write!(f, "TBLPROPERTIES ({})", display_comma_separated(options))
3315 }
3316 CreateTableOptions::Plain(options) => {
3317 write!(f, "{}", display_separated(options, " "))
3318 }
3319 CreateTableOptions::None => Ok(()),
3320 }
3321 }
3322}
3323
3324#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3331#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3332#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3333pub enum FromTable {
3334 WithFromKeyword(Vec<TableWithJoins>),
3336 WithoutKeyword(Vec<TableWithJoins>),
3339}
3340impl Display for FromTable {
3341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3342 match self {
3343 FromTable::WithFromKeyword(tables) => {
3344 write!(f, "FROM {}", display_comma_separated(tables))
3345 }
3346 FromTable::WithoutKeyword(tables) => {
3347 write!(f, "{}", display_comma_separated(tables))
3348 }
3349 }
3350 }
3351}
3352
3353#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3354#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3355#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3356pub enum Set {
3358 SingleAssignment {
3362 scope: Option<ContextModifier>,
3364 hivevar: bool,
3366 variable: ObjectName,
3368 values: Vec<Expr>,
3370 },
3371 ParenthesizedAssignments {
3375 variables: Vec<ObjectName>,
3377 values: Vec<Expr>,
3379 },
3380 MultipleAssignments {
3384 assignments: Vec<SetAssignment>,
3386 },
3387 SetSessionAuthorization(SetSessionAuthorizationParam),
3396 SetSessionParam(SetSessionParamKind),
3400 SetRole {
3411 context_modifier: Option<ContextModifier>,
3413 role_name: Option<Ident>,
3415 },
3416 SetTimeZone {
3426 local: bool,
3428 value: Expr,
3430 },
3431 SetNames {
3435 charset_name: Ident,
3437 collation_name: Option<String>,
3439 },
3440 SetNamesDefault {},
3446 SetTransaction {
3450 modes: Vec<TransactionMode>,
3452 snapshot: Option<ValueWithSpan>,
3454 session: bool,
3456 },
3457}
3458
3459impl Display for Set {
3460 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3461 match self {
3462 Self::ParenthesizedAssignments { variables, values } => write!(
3463 f,
3464 "SET ({}) = ({})",
3465 display_comma_separated(variables),
3466 display_comma_separated(values)
3467 ),
3468 Self::MultipleAssignments { assignments } => {
3469 write!(f, "SET {}", display_comma_separated(assignments))
3470 }
3471 Self::SetRole {
3472 context_modifier,
3473 role_name,
3474 } => {
3475 let role_name = role_name.clone().unwrap_or_else(|| Ident::new("NONE"));
3476 write!(
3477 f,
3478 "SET {modifier}ROLE {role_name}",
3479 modifier = context_modifier.map(|m| format!("{m}")).unwrap_or_default()
3480 )
3481 }
3482 Self::SetSessionAuthorization(kind) => write!(f, "SET SESSION AUTHORIZATION {kind}"),
3483 Self::SetSessionParam(kind) => write!(f, "SET {kind}"),
3484 Self::SetTransaction {
3485 modes,
3486 snapshot,
3487 session,
3488 } => {
3489 if *session {
3490 write!(f, "SET SESSION CHARACTERISTICS AS TRANSACTION")?;
3491 } else {
3492 write!(f, "SET TRANSACTION")?;
3493 }
3494 if !modes.is_empty() {
3495 write!(f, " {}", display_comma_separated(modes))?;
3496 }
3497 if let Some(snapshot_id) = snapshot {
3498 write!(f, " SNAPSHOT {snapshot_id}")?;
3499 }
3500 Ok(())
3501 }
3502 Self::SetTimeZone { local, value } => {
3503 f.write_str("SET ")?;
3504 if *local {
3505 f.write_str("LOCAL ")?;
3506 }
3507 write!(f, "TIME ZONE {value}")
3508 }
3509 Self::SetNames {
3510 charset_name,
3511 collation_name,
3512 } => {
3513 write!(f, "SET NAMES {charset_name}")?;
3514
3515 if let Some(collation) = collation_name {
3516 f.write_str(" COLLATE ")?;
3517 f.write_str(collation)?;
3518 };
3519
3520 Ok(())
3521 }
3522 Self::SetNamesDefault {} => {
3523 f.write_str("SET NAMES DEFAULT")?;
3524
3525 Ok(())
3526 }
3527 Set::SingleAssignment {
3528 scope,
3529 hivevar,
3530 variable,
3531 values,
3532 } => {
3533 write!(
3534 f,
3535 "SET {}{}{} = {}",
3536 scope.map(|s| format!("{s}")).unwrap_or_default(),
3537 if *hivevar { "HIVEVAR:" } else { "" },
3538 variable,
3539 display_comma_separated(values)
3540 )
3541 }
3542 }
3543 }
3544}
3545
3546#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3552#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3553#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3554pub struct ExceptionWhen {
3555 pub idents: Vec<Ident>,
3557 pub statements: Vec<Statement>,
3559}
3560
3561impl Display for ExceptionWhen {
3562 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3563 write!(
3564 f,
3565 "WHEN {idents} THEN",
3566 idents = display_separated(&self.idents, " OR ")
3567 )?;
3568
3569 if !self.statements.is_empty() {
3570 write!(f, " ")?;
3571 format_statement_list(f, &self.statements)?;
3572 }
3573
3574 Ok(())
3575 }
3576}
3577
3578#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3585#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3586#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3587pub struct Analyze {
3588 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3589 pub table_name: Option<ObjectName>,
3591 pub partitions: Option<Vec<Expr>>,
3593 pub for_columns: bool,
3595 pub columns: Vec<Ident>,
3597 pub cache_metadata: bool,
3599 pub noscan: bool,
3601 pub compute_statistics: bool,
3603 pub has_table_keyword: bool,
3605}
3606
3607impl fmt::Display for Analyze {
3608 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3609 write!(f, "ANALYZE")?;
3610 if let Some(ref table_name) = self.table_name {
3611 if self.has_table_keyword {
3612 write!(f, " TABLE")?;
3613 }
3614 write!(f, " {table_name}")?;
3615 }
3616 if !self.for_columns && !self.columns.is_empty() {
3617 write!(f, " ({})", display_comma_separated(&self.columns))?;
3618 }
3619 if let Some(ref parts) = self.partitions {
3620 if !parts.is_empty() {
3621 write!(f, " PARTITION ({})", display_comma_separated(parts))?;
3622 }
3623 }
3624 if self.compute_statistics {
3625 write!(f, " COMPUTE STATISTICS")?;
3626 }
3627 if self.noscan {
3628 write!(f, " NOSCAN")?;
3629 }
3630 if self.cache_metadata {
3631 write!(f, " CACHE METADATA")?;
3632 }
3633 if self.for_columns {
3634 write!(f, " FOR COLUMNS")?;
3635 if !self.columns.is_empty() {
3636 write!(f, " {}", display_comma_separated(&self.columns))?;
3637 }
3638 }
3639 Ok(())
3640 }
3641}
3642
3643#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3645#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3646#[cfg_attr(
3647 feature = "visitor",
3648 derive(Visit, VisitMut),
3649 visit(with = "visit_statement")
3650)]
3651pub enum Statement {
3652 Analyze(Analyze),
3657 Set(Set),
3659 Truncate(Truncate),
3664 Msck(Msck),
3669 Query(Box<Query>),
3673 Insert(Insert),
3677 Install {
3681 extension_name: Ident,
3683 },
3684 Load {
3688 extension_name: Ident,
3690 },
3691 Directory {
3694 overwrite: bool,
3696 local: bool,
3698 path: String,
3700 file_format: Option<FileFormat>,
3702 source: Box<Query>,
3704 },
3705 Case(CaseStatement),
3707 If(IfStatement),
3709 While(WhileStatement),
3711 Raise(RaiseStatement),
3713 Call(Function),
3717 Copy {
3721 source: CopySource,
3723 to: bool,
3725 target: CopyTarget,
3727 options: Vec<CopyOption>,
3729 legacy_options: Vec<CopyLegacyOption>,
3731 payload: Option<CopyPayload>,
3735 },
3736 CopyIntoSnowflake {
3748 kind: CopyIntoSnowflakeKind,
3750 into: ObjectName,
3752 into_columns: Option<Vec<Ident>>,
3754 from_obj: Option<ObjectName>,
3756 from_obj_alias: Option<Ident>,
3758 stage_params: StageParamsObject,
3760 from_transformations: Option<Vec<StageLoadSelectItemKind>>,
3762 from_query: Option<Box<Query>>,
3764 files: Option<Vec<String>>,
3766 pattern: Option<String>,
3768 file_format: KeyValueOptions,
3770 copy_options: KeyValueOptions,
3772 validation_mode: Option<String>,
3774 partition: Option<Box<Expr>>,
3776 },
3777 Open(OpenStatement),
3782 Close {
3787 cursor: CloseCursor,
3789 },
3790 Update(Update),
3794 Delete(Delete),
3798 CreateView(CreateView),
3802 CreateTable(CreateTable),
3806 CreateVirtualTable {
3811 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3812 name: ObjectName,
3814 if_not_exists: bool,
3816 module_name: Ident,
3818 module_args: Vec<Ident>,
3820 },
3821 CreateIndex(CreateIndex),
3825 CreateRole(CreateRole),
3830 CreateSecret {
3835 or_replace: bool,
3837 temporary: Option<bool>,
3839 if_not_exists: bool,
3841 name: Option<Ident>,
3843 storage_specifier: Option<Ident>,
3845 secret_type: Ident,
3847 options: Vec<SecretOption>,
3849 },
3850 CreateServer(CreateServerStatement),
3852 CreateForeignTable(CreateForeignTable),
3857 CreateForeignDataWrapper(CreateForeignDataWrapper),
3862 CreateUserMapping(CreateUserMapping),
3867 CreatePolicy(CreatePolicy),
3872 CreateRule(CreateRule),
3877 CreateConnector(CreateConnector),
3882 CreateOperator(CreateOperator),
3887 CreateOperatorFamily(CreateOperatorFamily),
3892 CreateOperatorClass(CreateOperatorClass),
3897 CreateTextSearch(CreateTextSearch),
3901 CreateAggregate(CreateAggregate),
3906 AlterTable(AlterTable),
3910 AlterSchema(AlterSchema),
3915 AlterIndex {
3919 name: ObjectName,
3921 operation: AlterIndexOperation,
3923 },
3924 AlterView(AlterView),
3928 AlterFunction(AlterFunction),
3935 AlterType(AlterType),
3940 AlterCollation(AlterCollation),
3945 AlterOperator(AlterOperator),
3950 AlterOperatorFamily(AlterOperatorFamily),
3955 AlterOperatorClass(AlterOperatorClass),
3960 AlterTextSearch(AlterTextSearch),
3964 AlterRole {
3968 name: Ident,
3970 operation: AlterRoleOperation,
3972 },
3973 AlterPolicy(AlterPolicy),
3978 AlterTrigger(AlterTrigger),
3983 AlterConnector {
3992 name: Ident,
3994 properties: Option<Vec<SqlOption>>,
3996 url: Option<String>,
3998 owner: Option<ddl::AlterConnectorOwner>,
4000 },
4001 AlterSession {
4007 set: bool,
4009 session_params: KeyValueOptions,
4011 },
4012 AttachDatabase {
4017 schema_name: Ident,
4019 database_file_name: Expr,
4021 database: bool,
4023 },
4024 AttachDuckDBDatabase {
4030 if_not_exists: bool,
4032 database: bool,
4034 database_path: Ident,
4036 database_alias: Option<Ident>,
4038 attach_options: Vec<AttachDuckDBDatabaseOption>,
4040 },
4041 DetachDuckDBDatabase {
4047 if_exists: bool,
4049 database: bool,
4051 database_alias: Ident,
4053 },
4054 Drop {
4058 object_type: ObjectType,
4060 if_exists: bool,
4062 names: Vec<ObjectName>,
4064 cascade: bool,
4067 restrict: bool,
4070 purge: bool,
4073 temporary: bool,
4075 table: Option<ObjectName>,
4078 },
4079 DropFunction(DropFunction),
4083 DropDomain(DropDomain),
4091 DropProcedure {
4095 if_exists: bool,
4097 proc_desc: Vec<FunctionDesc>,
4099 drop_behavior: Option<DropBehavior>,
4101 },
4102 DropSecret {
4106 if_exists: bool,
4108 temporary: Option<bool>,
4110 name: Ident,
4112 storage_specifier: Option<Ident>,
4114 },
4115 DropPolicy(DropPolicy),
4120 DropRule(DropRule),
4125 DropConnector {
4130 if_exists: bool,
4132 name: Ident,
4134 },
4135 Declare {
4143 stmts: Vec<Declare>,
4145 separator: DeclareSeparator,
4147 },
4148 CreateExtension(CreateExtension),
4157 CreateCollation(CreateCollation),
4163 DropExtension(DropExtension),
4169 DropOperator(DropOperator),
4175 DropOperatorFamily(DropOperatorFamily),
4181 DropOperatorClass(DropOperatorClass),
4187 Fetch {
4195 name: Ident,
4197 direction: FetchDirection,
4199 position: FetchPosition,
4201 into: Option<ObjectName>,
4203 },
4204 Flush {
4211 object_type: FlushType,
4213 location: Option<FlushLocation>,
4215 channel: Option<String>,
4217 read_lock: bool,
4219 export: bool,
4221 tables: Vec<ObjectName>,
4223 },
4224 Discard {
4231 object_type: DiscardObject,
4233 },
4234 ShowFunctions {
4238 filter: Option<ShowStatementFilter>,
4240 },
4241 ShowVariable {
4247 variable: Vec<Ident>,
4249 },
4250 ShowStatus {
4256 filter: Option<ShowStatementFilter>,
4258 global: bool,
4260 session: bool,
4262 },
4263 ShowVariables {
4269 filter: Option<ShowStatementFilter>,
4271 global: bool,
4273 session: bool,
4275 },
4276 ShowCreate {
4282 obj_type: ShowCreateObject,
4284 obj_name: ObjectName,
4286 },
4287 ShowColumns {
4291 extended: bool,
4293 full: bool,
4295 show_options: ShowStatementOptions,
4297 },
4298 ShowCatalogs {
4302 terse: bool,
4304 history: bool,
4306 show_options: ShowStatementOptions,
4308 },
4309 ShowDatabases {
4313 terse: bool,
4315 history: bool,
4317 show_options: ShowStatementOptions,
4319 },
4320 ShowProcessList {
4326 full: bool,
4328 },
4329 ShowSchemas {
4333 terse: bool,
4335 history: bool,
4337 show_options: ShowStatementOptions,
4339 },
4340 ShowCharset(ShowCharset),
4347 ShowObjects(ShowObjects),
4353 ShowTables {
4357 terse: bool,
4359 history: bool,
4361 extended: bool,
4363 full: bool,
4365 external: bool,
4367 show_options: ShowStatementOptions,
4369 },
4370 ShowViews {
4374 terse: bool,
4376 materialized: bool,
4378 show_options: ShowStatementOptions,
4380 },
4381 ShowCollation {
4387 filter: Option<ShowStatementFilter>,
4389 },
4390 Use(Use),
4394 StartTransaction {
4404 modes: Vec<TransactionMode>,
4406 begin: bool,
4408 transaction: Option<BeginTransactionKind>,
4410 modifier: Option<TransactionModifier>,
4412 statements: Vec<Statement>,
4421 exception: Option<Vec<ExceptionWhen>>,
4435 has_end_keyword: bool,
4437 },
4438 Comment {
4444 object_type: CommentObject,
4446 object_name: ObjectName,
4448 comment: Option<String>,
4450 if_exists: bool,
4453 },
4454 Commit {
4464 chain: bool,
4466 end: bool,
4468 modifier: Option<TransactionModifier>,
4470 },
4471 Rollback {
4475 chain: bool,
4477 savepoint: Option<Ident>,
4479 },
4480 CreateSchema {
4484 schema_name: SchemaName,
4486 or_replace: bool,
4488 if_not_exists: bool,
4490 with: Option<Vec<SqlOption>>,
4498 options: Option<Vec<SqlOption>>,
4506 default_collate_spec: Option<Expr>,
4514 clone: Option<ObjectName>,
4522 },
4523 CreateDatabase {
4529 db_name: ObjectName,
4531 if_not_exists: bool,
4533 location: Option<String>,
4535 managed_location: Option<String>,
4537 or_replace: bool,
4539 transient: bool,
4541 clone: Option<ObjectName>,
4543 data_retention_time_in_days: Option<u64>,
4545 max_data_extension_time_in_days: Option<u64>,
4547 external_volume: Option<String>,
4549 catalog: Option<String>,
4551 replace_invalid_characters: Option<bool>,
4553 default_ddl_collation: Option<String>,
4555 storage_serialization_policy: Option<StorageSerializationPolicy>,
4557 comment: Option<String>,
4559 default_charset: Option<String>,
4561 default_collation: Option<String>,
4563 catalog_sync: Option<String>,
4565 catalog_sync_namespace_mode: Option<CatalogSyncNamespaceMode>,
4567 catalog_sync_namespace_flatten_delimiter: Option<String>,
4569 with_tags: Option<Vec<Tag>>,
4571 with_contacts: Option<Vec<ContactEntry>>,
4573 },
4574 CreateFunction(CreateFunction),
4584 CreateTrigger(CreateTrigger),
4586 DropTrigger(DropTrigger),
4588 CreateProcedure {
4592 or_alter: bool,
4594 name: ObjectName,
4596 params: Option<Vec<ProcedureParam>>,
4598 language: Option<Ident>,
4600 body: CreateProcedureBody,
4602 },
4603 CreateMacro {
4610 or_replace: bool,
4612 temporary: bool,
4614 name: ObjectName,
4616 args: Option<Vec<MacroArg>>,
4618 definition: MacroDefinition,
4620 },
4621 CreateStage {
4626 or_replace: bool,
4628 temporary: bool,
4630 if_not_exists: bool,
4632 name: ObjectName,
4634 stage_params: StageParamsObject,
4636 directory_table_params: KeyValueOptions,
4638 file_format: KeyValueOptions,
4640 copy_options: KeyValueOptions,
4642 comment: Option<String>,
4644 },
4645 CreateFileFormat {
4652 or_replace: bool,
4654 temporary: bool,
4656 volatile: bool,
4658 if_not_exists: bool,
4660 name: ObjectName,
4662 options: KeyValueOptions,
4664 comment: Option<String>,
4666 },
4667 CreateWarehouse(CreateWarehouse),
4675 Assert {
4679 condition: Expr,
4681 message: Option<Expr>,
4683 },
4684 Grant(Grant),
4688 GrantRole(GrantRole),
4692 Deny(DenyStatement),
4696 Revoke(Revoke),
4700 RevokeRole(RevokeRole),
4704 AlterDefaultPrivileges(AlterDefaultPrivileges),
4708 Deallocate {
4714 name: Ident,
4716 prepare: bool,
4718 },
4719 Execute {
4728 name: Option<ObjectName>,
4730 parameters: Vec<Expr>,
4732 has_parentheses: bool,
4734 immediate: bool,
4736 into: Vec<Ident>,
4738 using: Vec<ExprWithAlias>,
4740 output: bool,
4743 default: bool,
4746 },
4747 Prepare {
4753 name: Ident,
4755 data_types: Vec<DataType>,
4757 statement: Box<Statement>,
4759 },
4760 Kill {
4767 modifier: Option<KillType>,
4769 id: u64,
4772 },
4773 ExplainTable {
4778 describe_alias: DescribeAlias,
4780 hive_format: Option<HiveDescribeFormat>,
4782 has_table_keyword: bool,
4787 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4789 table_name: ObjectName,
4790 },
4791 Explain {
4795 describe_alias: DescribeAlias,
4797 analyze: bool,
4799 verbose: bool,
4801 query_plan: bool,
4806 estimate: bool,
4809 statement: Box<Statement>,
4811 format: Option<AnalyzeFormatKind>,
4813 options: Option<Vec<UtilityOption>>,
4815 },
4816 Savepoint {
4821 name: Ident,
4823 },
4824 ReleaseSavepoint {
4828 name: Ident,
4830 },
4831 Merge(Merge),
4840 Cache {
4848 table_flag: Option<ObjectName>,
4850 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4852 table_name: ObjectName,
4853 has_as: bool,
4855 options: Vec<SqlOption>,
4857 query: Option<Box<Query>>,
4859 },
4860 UNCache {
4864 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4866 table_name: ObjectName,
4867 if_exists: bool,
4869 },
4870 CreateSequence {
4875 temporary: bool,
4877 if_not_exists: bool,
4879 name: ObjectName,
4881 sequence_options: Vec<SequenceOptions>,
4883 },
4884 CreateDomain(CreateDomain),
4886 CreateType {
4890 name: ObjectName,
4892 representation: Option<UserDefinedTypeRepresentation>,
4894 },
4895 Pragma {
4899 name: ObjectName,
4901 value: Option<ValueWithSpan>,
4903 is_eq: bool,
4905 },
4906 Lock(Lock),
4912 LockTables {
4917 tables: Vec<LockTable>,
4919 },
4920 UnlockTables,
4925 Unload {
4937 query: Option<Box<Query>>,
4939 query_text: Option<String>,
4941 to: Ident,
4943 auth: Option<IamRoleKind>,
4945 with: Vec<SqlOption>,
4947 options: Vec<CopyLegacyOption>,
4949 },
4950 OptimizeTable {
4962 name: ObjectName,
4964 has_table_keyword: bool,
4966 on_cluster: Option<Ident>,
4969 partition: Option<Partition>,
4972 include_final: bool,
4975 deduplicate: Option<Deduplicate>,
4978 predicate: Option<Expr>,
4981 zorder: Option<Vec<Expr>>,
4984 },
4985 LISTEN {
4992 channel: Ident,
4994 },
4995 UNLISTEN {
5002 channel: Ident,
5004 },
5005 NOTIFY {
5012 channel: Ident,
5014 payload: Option<String>,
5016 },
5017 LoadData {
5026 local: bool,
5028 inpath: String,
5030 overwrite: bool,
5032 table_name: ObjectName,
5034 partitioned: Option<Vec<Expr>>,
5036 table_format: Option<HiveLoadDataFormat>,
5038 },
5039 RenameTable(Vec<RenameTable>),
5046 List(FileStagingCommand),
5049 Put {
5056 source: String,
5058 stage: ObjectName,
5060 options: KeyValueOptions,
5062 },
5063 Remove(FileStagingCommand),
5066 RaisError {
5073 message: Box<Expr>,
5075 severity: Box<Expr>,
5077 state: Box<Expr>,
5079 arguments: Vec<Expr>,
5081 options: Vec<RaisErrorOption>,
5083 },
5084 Throw(ThrowStatement),
5086 Print(PrintStatement),
5092 WaitFor(WaitForStatement),
5096 Return(ReturnStatement),
5102 ExportData(ExportData),
5111 CreateUser(CreateUser),
5116 AlterUser(AlterUser),
5121 Vacuum(VacuumStatement),
5128 Reset(ResetStatement),
5136 RefreshMaterializedView(RefreshMaterializedView),
5143}
5144
5145impl From<Analyze> for Statement {
5146 fn from(analyze: Analyze) -> Self {
5147 Statement::Analyze(analyze)
5148 }
5149}
5150
5151impl From<ddl::Truncate> for Statement {
5152 fn from(truncate: ddl::Truncate) -> Self {
5153 Statement::Truncate(truncate)
5154 }
5155}
5156
5157impl From<Lock> for Statement {
5158 fn from(lock: Lock) -> Self {
5159 Statement::Lock(lock)
5160 }
5161}
5162
5163impl From<ddl::Msck> for Statement {
5164 fn from(msck: ddl::Msck) -> Self {
5165 Statement::Msck(msck)
5166 }
5167}
5168
5169#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5175#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5176#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5177pub enum CurrentGrantsKind {
5178 CopyCurrentGrants,
5180 RevokeCurrentGrants,
5182}
5183
5184impl fmt::Display for CurrentGrantsKind {
5185 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5186 match self {
5187 CurrentGrantsKind::CopyCurrentGrants => write!(f, "COPY CURRENT GRANTS"),
5188 CurrentGrantsKind::RevokeCurrentGrants => write!(f, "REVOKE CURRENT GRANTS"),
5189 }
5190 }
5191}
5192
5193#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
5194#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
5195#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
5196pub enum RaisErrorOption {
5199 Log,
5201 NoWait,
5203 SetError,
5205}
5206
5207impl fmt::Display for RaisErrorOption {
5208 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5209 match self {
5210 RaisErrorOption::Log => write!(f, "LOG"),
5211 RaisErrorOption::NoWait => write!(f, "NOWAIT"),
5212 RaisErrorOption::SetError => write!(f, "SETERROR"),
5213 }
5214 }
5215}
5216
5217impl fmt::Display for Statement {
5218 #[expect(
5241 clippy::cognitive_complexity,
5242 reason = "splitting this match would need a struct for each `Statement` variant"
5243 )]
5244 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5245 match self {
5246 Statement::Flush {
5247 object_type,
5248 location,
5249 channel,
5250 read_lock,
5251 export,
5252 tables,
5253 } => {
5254 write!(f, "FLUSH")?;
5255 if let Some(location) = location {
5256 f.write_str(" ")?;
5257 location.fmt(f)?;
5258 }
5259 write!(f, " {object_type}")?;
5260
5261 if let Some(channel) = channel {
5262 write!(f, " FOR CHANNEL {channel}")?;
5263 }
5264
5265 write!(
5266 f,
5267 "{tables}{read}{export}",
5268 tables = if !tables.is_empty() {
5269 format!(" {}", display_comma_separated(tables))
5270 } else {
5271 String::new()
5272 },
5273 export = if *export { " FOR EXPORT" } else { "" },
5274 read = if *read_lock { " WITH READ LOCK" } else { "" }
5275 )
5276 }
5277 Statement::Kill { modifier, id } => {
5278 write!(f, "KILL ")?;
5279
5280 if let Some(m) = modifier {
5281 write!(f, "{m} ")?;
5282 }
5283
5284 write!(f, "{id}")
5285 }
5286 Statement::ExplainTable {
5287 describe_alias,
5288 hive_format,
5289 has_table_keyword,
5290 table_name,
5291 } => {
5292 write!(f, "{describe_alias} ")?;
5293
5294 if let Some(format) = hive_format {
5295 write!(f, "{format} ")?;
5296 }
5297 if *has_table_keyword {
5298 write!(f, "TABLE ")?;
5299 }
5300
5301 write!(f, "{table_name}")
5302 }
5303 Statement::Explain {
5304 describe_alias,
5305 verbose,
5306 analyze,
5307 query_plan,
5308 estimate,
5309 statement,
5310 format,
5311 options,
5312 } => {
5313 write!(f, "{describe_alias} ")?;
5314
5315 if *query_plan {
5316 write!(f, "QUERY PLAN ")?;
5317 }
5318 if *analyze {
5319 write!(f, "ANALYZE ")?;
5320 }
5321 if *estimate {
5322 write!(f, "ESTIMATE ")?;
5323 }
5324
5325 if *verbose {
5326 write!(f, "VERBOSE ")?;
5327 }
5328
5329 if let Some(format) = format {
5330 write!(f, "{format} ")?;
5331 }
5332
5333 if let Some(options) = options {
5334 write!(f, "({}) ", display_comma_separated(options))?;
5335 }
5336
5337 write!(f, "{statement}")
5338 }
5339 Statement::Query(s) => s.fmt(f),
5340 Statement::Declare { stmts, separator } => {
5341 let sep = match separator {
5342 DeclareSeparator::Comma => ", ",
5343 DeclareSeparator::Semicolon => "; ",
5344 };
5345 write!(f, "DECLARE {}", display_separated(stmts, sep))
5346 }
5347 Statement::Fetch {
5348 name,
5349 direction,
5350 position,
5351 into,
5352 } => {
5353 write!(f, "FETCH {direction} {position} {name}")?;
5354
5355 if let Some(into) = into {
5356 write!(f, " INTO {into}")?;
5357 }
5358
5359 Ok(())
5360 }
5361 Statement::Directory {
5362 overwrite,
5363 local,
5364 path,
5365 file_format,
5366 source,
5367 } => {
5368 write!(
5369 f,
5370 "INSERT{overwrite}{local} DIRECTORY '{path}'",
5371 overwrite = if *overwrite { " OVERWRITE" } else { "" },
5372 local = if *local { " LOCAL" } else { "" },
5373 path = path
5374 )?;
5375 if let Some(ref ff) = file_format {
5376 write!(f, " STORED AS {ff}")?
5377 }
5378 write!(f, " {source}")
5379 }
5380 Statement::Msck(msck) => msck.fmt(f),
5381 Statement::Truncate(truncate) => truncate.fmt(f),
5382 Statement::Case(stmt) => {
5383 write!(f, "{stmt}")
5384 }
5385 Statement::If(stmt) => {
5386 write!(f, "{stmt}")
5387 }
5388 Statement::While(stmt) => {
5389 write!(f, "{stmt}")
5390 }
5391 Statement::Raise(stmt) => {
5392 write!(f, "{stmt}")
5393 }
5394 Statement::AttachDatabase {
5395 schema_name,
5396 database_file_name,
5397 database,
5398 } => {
5399 let keyword = if *database { "DATABASE " } else { "" };
5400 write!(f, "ATTACH {keyword}{database_file_name} AS {schema_name}")
5401 }
5402 Statement::AttachDuckDBDatabase {
5403 if_not_exists,
5404 database,
5405 database_path,
5406 database_alias,
5407 attach_options,
5408 } => {
5409 write!(
5410 f,
5411 "ATTACH{database}{if_not_exists} {database_path}",
5412 database = if *database { " DATABASE" } else { "" },
5413 if_not_exists = if *if_not_exists { " IF NOT EXISTS" } else { "" },
5414 )?;
5415 if let Some(alias) = database_alias {
5416 write!(f, " AS {alias}")?;
5417 }
5418 if !attach_options.is_empty() {
5419 write!(f, " ({})", display_comma_separated(attach_options))?;
5420 }
5421 Ok(())
5422 }
5423 Statement::DetachDuckDBDatabase {
5424 if_exists,
5425 database,
5426 database_alias,
5427 } => {
5428 write!(
5429 f,
5430 "DETACH{database}{if_exists} {database_alias}",
5431 database = if *database { " DATABASE" } else { "" },
5432 if_exists = if *if_exists { " IF EXISTS" } else { "" },
5433 )?;
5434 Ok(())
5435 }
5436 Statement::Analyze(analyze) => analyze.fmt(f),
5437 Statement::Insert(insert) => insert.fmt(f),
5438 Statement::Install {
5439 extension_name: name,
5440 } => write!(f, "INSTALL {name}"),
5441
5442 Statement::Load {
5443 extension_name: name,
5444 } => write!(f, "LOAD {name}"),
5445
5446 Statement::Call(function) => write!(f, "CALL {function}"),
5447
5448 Statement::Copy {
5449 source,
5450 to,
5451 target,
5452 options,
5453 legacy_options,
5454 payload,
5455 } => {
5456 write!(f, "COPY")?;
5457 match source {
5458 CopySource::Query(query) => write!(f, " ({query})")?,
5459 CopySource::Table {
5460 table_name,
5461 columns,
5462 } => {
5463 write!(f, " {table_name}")?;
5464 if !columns.is_empty() {
5465 write!(f, " ({})", display_comma_separated(columns))?;
5466 }
5467 }
5468 }
5469 write!(f, " {} {}", if *to { "TO" } else { "FROM" }, target)?;
5470 if !options.is_empty() {
5471 write!(f, " ({})", display_comma_separated(options))?;
5472 }
5473 if !legacy_options.is_empty() {
5474 write!(f, " {}", display_separated(legacy_options, " "))?;
5475 }
5476 if let Some(payload) = payload {
5477 writeln!(f, ";")?;
5481 write!(f, "{}", payload.data)?;
5482 if payload.terminated {
5483 write!(f, "\\.")?;
5484 }
5485 }
5486 Ok(())
5487 }
5488 Statement::Update(update) => update.fmt(f),
5489 Statement::Delete(delete) => delete.fmt(f),
5490 Statement::Open(open) => open.fmt(f),
5491 Statement::Close { cursor } => {
5492 write!(f, "CLOSE {cursor}")?;
5493
5494 Ok(())
5495 }
5496 Statement::CreateDatabase {
5497 db_name,
5498 if_not_exists,
5499 location,
5500 managed_location,
5501 or_replace,
5502 transient,
5503 clone,
5504 data_retention_time_in_days,
5505 max_data_extension_time_in_days,
5506 external_volume,
5507 catalog,
5508 replace_invalid_characters,
5509 default_ddl_collation,
5510 storage_serialization_policy,
5511 comment,
5512 default_charset,
5513 default_collation,
5514 catalog_sync,
5515 catalog_sync_namespace_mode,
5516 catalog_sync_namespace_flatten_delimiter,
5517 with_tags,
5518 with_contacts,
5519 } => {
5520 write!(
5521 f,
5522 "CREATE {or_replace}{transient}DATABASE {if_not_exists}{name}",
5523 or_replace = if *or_replace { "OR REPLACE " } else { "" },
5524 transient = if *transient { "TRANSIENT " } else { "" },
5525 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
5526 name = db_name,
5527 )?;
5528
5529 if let Some(l) = location {
5530 write!(f, " LOCATION '{l}'")?;
5531 }
5532 if let Some(ml) = managed_location {
5533 write!(f, " MANAGEDLOCATION '{ml}'")?;
5534 }
5535 if let Some(clone) = clone {
5536 write!(f, " CLONE {clone}")?;
5537 }
5538
5539 if let Some(value) = data_retention_time_in_days {
5540 write!(f, " DATA_RETENTION_TIME_IN_DAYS = {value}")?;
5541 }
5542
5543 if let Some(value) = max_data_extension_time_in_days {
5544 write!(f, " MAX_DATA_EXTENSION_TIME_IN_DAYS = {value}")?;
5545 }
5546
5547 if let Some(vol) = external_volume {
5548 write!(f, " EXTERNAL_VOLUME = '{vol}'")?;
5549 }
5550
5551 if let Some(cat) = catalog {
5552 write!(f, " CATALOG = '{cat}'")?;
5553 }
5554
5555 if let Some(true) = replace_invalid_characters {
5556 write!(f, " REPLACE_INVALID_CHARACTERS = TRUE")?;
5557 } else if let Some(false) = replace_invalid_characters {
5558 write!(f, " REPLACE_INVALID_CHARACTERS = FALSE")?;
5559 }
5560
5561 if let Some(collation) = default_ddl_collation {
5562 write!(f, " DEFAULT_DDL_COLLATION = '{collation}'")?;
5563 }
5564
5565 if let Some(policy) = storage_serialization_policy {
5566 write!(f, " STORAGE_SERIALIZATION_POLICY = {policy}")?;
5567 }
5568
5569 if let Some(comment) = comment {
5570 write!(f, " COMMENT = '{comment}'")?;
5571 }
5572
5573 if let Some(charset) = default_charset {
5574 write!(f, " DEFAULT CHARACTER SET {charset}")?;
5575 }
5576
5577 if let Some(collation) = default_collation {
5578 write!(f, " DEFAULT COLLATE {collation}")?;
5579 }
5580
5581 if let Some(sync) = catalog_sync {
5582 write!(f, " CATALOG_SYNC = '{sync}'")?;
5583 }
5584
5585 if let Some(mode) = catalog_sync_namespace_mode {
5586 write!(f, " CATALOG_SYNC_NAMESPACE_MODE = {mode}")?;
5587 }
5588
5589 if let Some(delim) = catalog_sync_namespace_flatten_delimiter {
5590 write!(f, " CATALOG_SYNC_NAMESPACE_FLATTEN_DELIMITER = '{delim}'")?;
5591 }
5592
5593 if let Some(tags) = with_tags {
5594 write!(f, " WITH TAG ({})", display_comma_separated(tags))?;
5595 }
5596
5597 if let Some(contacts) = with_contacts {
5598 write!(f, " WITH CONTACT ({})", display_comma_separated(contacts))?;
5599 }
5600 Ok(())
5601 }
5602 Statement::CreateFunction(create_function) => create_function.fmt(f),
5603 Statement::CreateDomain(create_domain) => create_domain.fmt(f),
5604 Statement::CreateTrigger(create_trigger) => create_trigger.fmt(f),
5605 Statement::DropTrigger(drop_trigger) => drop_trigger.fmt(f),
5606 Statement::CreateProcedure {
5607 name,
5608 or_alter,
5609 params,
5610 language,
5611 body,
5612 } => {
5613 write!(
5614 f,
5615 "CREATE {or_alter}PROCEDURE {name}",
5616 or_alter = if *or_alter { "OR ALTER " } else { "" },
5617 name = name
5618 )?;
5619
5620 if let Some(p) = params {
5621 write!(f, " ({})", display_comma_separated(p))?;
5622 }
5623
5624 if let Some(language) = language {
5625 write!(f, " LANGUAGE {language}")?;
5626 }
5627
5628 match body {
5629 CreateProcedureBody::As(body) => write!(f, " AS {body}"),
5630 CreateProcedureBody::BeginAtomic(BeginEndStatements { statements, .. }) => {
5631 format_begin_atomic(f, statements)
5632 }
5633 }
5634 }
5635 Statement::CreateMacro {
5636 or_replace,
5637 temporary,
5638 name,
5639 args,
5640 definition,
5641 } => {
5642 write!(
5643 f,
5644 "CREATE {or_replace}{temp}MACRO {name}",
5645 temp = if *temporary { "TEMPORARY " } else { "" },
5646 or_replace = if *or_replace { "OR REPLACE " } else { "" },
5647 )?;
5648 write!(
5649 f,
5650 "({})",
5651 display_comma_separated(args.as_deref().unwrap_or(&[]))
5652 )?;
5653 match definition {
5654 MacroDefinition::Expr(expr) => write!(f, " AS {expr}")?,
5655 MacroDefinition::Table(query) => write!(f, " AS TABLE {query}")?,
5656 }
5657 Ok(())
5658 }
5659 Statement::CreateView(create_view) => create_view.fmt(f),
5660 Statement::CreateTable(create_table) => create_table.fmt(f),
5661 Statement::LoadData {
5662 local,
5663 inpath,
5664 overwrite,
5665 table_name,
5666 partitioned,
5667 table_format,
5668 } => {
5669 write!(
5670 f,
5671 "LOAD DATA {local}INPATH '{inpath}' {overwrite}INTO TABLE {table_name}",
5672 local = if *local { "LOCAL " } else { "" },
5673 inpath = inpath,
5674 overwrite = if *overwrite { "OVERWRITE " } else { "" },
5675 table_name = table_name,
5676 )?;
5677 if let Some(ref parts) = &partitioned {
5678 if !parts.is_empty() {
5679 write!(f, " PARTITION ({})", display_comma_separated(parts))?;
5680 }
5681 }
5682 if let Some(HiveLoadDataFormat {
5683 serde,
5684 input_format,
5685 }) = &table_format
5686 {
5687 write!(f, " INPUTFORMAT {input_format} SERDE {serde}")?;
5688 }
5689 Ok(())
5690 }
5691 Statement::CreateVirtualTable {
5692 name,
5693 if_not_exists,
5694 module_name,
5695 module_args,
5696 } => {
5697 write!(
5698 f,
5699 "CREATE VIRTUAL TABLE {if_not_exists}{name} USING {module_name}",
5700 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
5701 name = name,
5702 module_name = module_name
5703 )?;
5704 if !module_args.is_empty() {
5705 write!(f, " ({})", display_comma_separated(module_args))?;
5706 }
5707 Ok(())
5708 }
5709 Statement::CreateIndex(create_index) => create_index.fmt(f),
5710 Statement::CreateExtension(create_extension) => write!(f, "{create_extension}"),
5711 Statement::CreateCollation(create_collation) => write!(f, "{create_collation}"),
5712 Statement::DropExtension(drop_extension) => write!(f, "{drop_extension}"),
5713 Statement::DropOperator(drop_operator) => write!(f, "{drop_operator}"),
5714 Statement::DropOperatorFamily(drop_operator_family) => {
5715 write!(f, "{drop_operator_family}")
5716 }
5717 Statement::DropOperatorClass(drop_operator_class) => {
5718 write!(f, "{drop_operator_class}")
5719 }
5720 Statement::CreateRole(create_role) => write!(f, "{create_role}"),
5721 Statement::CreateSecret {
5722 or_replace,
5723 temporary,
5724 if_not_exists,
5725 name,
5726 storage_specifier,
5727 secret_type,
5728 options,
5729 } => {
5730 write!(
5731 f,
5732 "CREATE {or_replace}",
5733 or_replace = if *or_replace { "OR REPLACE " } else { "" },
5734 )?;
5735 if let Some(t) = temporary {
5736 write!(f, "{}", if *t { "TEMPORARY " } else { "PERSISTENT " })?;
5737 }
5738 write!(
5739 f,
5740 "SECRET {if_not_exists}",
5741 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
5742 )?;
5743 if let Some(n) = name {
5744 write!(f, "{n} ")?;
5745 };
5746 if let Some(s) = storage_specifier {
5747 write!(f, "IN {s} ")?;
5748 }
5749 write!(f, "( TYPE {secret_type}",)?;
5750 if !options.is_empty() {
5751 write!(f, ", {o}", o = display_comma_separated(options))?;
5752 }
5753 write!(f, " )")?;
5754 Ok(())
5755 }
5756 Statement::CreateServer(stmt) => {
5757 write!(f, "{stmt}")
5758 }
5759 Statement::CreateForeignTable(stmt) => write!(f, "{stmt}"),
5760 Statement::CreateForeignDataWrapper(stmt) => write!(f, "{stmt}"),
5761 Statement::CreateUserMapping(stmt) => write!(f, "{stmt}"),
5762 Statement::CreatePolicy(policy) => write!(f, "{policy}"),
5763 Statement::CreateRule(rule) => write!(f, "{rule}"),
5764 Statement::CreateConnector(create_connector) => create_connector.fmt(f),
5765 Statement::CreateOperator(create_operator) => create_operator.fmt(f),
5766 Statement::CreateOperatorFamily(create_operator_family) => {
5767 create_operator_family.fmt(f)
5768 }
5769 Statement::CreateOperatorClass(create_operator_class) => create_operator_class.fmt(f),
5770 Statement::CreateAggregate(create_aggregate) => create_aggregate.fmt(f),
5771 Statement::CreateTextSearch(create_text_search) => create_text_search.fmt(f),
5772 Statement::AlterTable(alter_table) => write!(f, "{alter_table}"),
5773 Statement::AlterIndex { name, operation } => {
5774 write!(f, "ALTER INDEX {name} {operation}")
5775 }
5776 Statement::AlterView(alter_view) => write!(f, "{alter_view}"),
5777 Statement::AlterFunction(alter_function) => write!(f, "{alter_function}"),
5778 Statement::AlterType(AlterType { name, operation }) => {
5779 write!(f, "ALTER TYPE {name} {operation}")
5780 }
5781 Statement::AlterCollation(alter_collation) => write!(f, "{alter_collation}"),
5782 Statement::AlterOperator(alter_operator) => write!(f, "{alter_operator}"),
5783 Statement::AlterOperatorFamily(alter_operator_family) => {
5784 write!(f, "{alter_operator_family}")
5785 }
5786 Statement::AlterOperatorClass(alter_operator_class) => {
5787 write!(f, "{alter_operator_class}")
5788 }
5789 Statement::AlterTextSearch(alter_text_search) => write!(f, "{alter_text_search}"),
5790 Statement::AlterRole { name, operation } => {
5791 write!(f, "ALTER ROLE {name} {operation}")
5792 }
5793 Statement::AlterPolicy(alter_policy) => write!(f, "{alter_policy}"),
5794 Statement::AlterTrigger(alter_trigger) => write!(f, "{alter_trigger}"),
5795 Statement::AlterConnector {
5796 name,
5797 properties,
5798 url,
5799 owner,
5800 } => {
5801 write!(f, "ALTER CONNECTOR {name}")?;
5802 if let Some(properties) = properties {
5803 write!(
5804 f,
5805 " SET DCPROPERTIES({})",
5806 display_comma_separated(properties)
5807 )?;
5808 }
5809 if let Some(url) = url {
5810 write!(f, " SET URL '{url}'")?;
5811 }
5812 if let Some(owner) = owner {
5813 write!(f, " SET OWNER {owner}")?;
5814 }
5815 Ok(())
5816 }
5817 Statement::AlterSession {
5818 set,
5819 session_params,
5820 } => {
5821 write!(
5822 f,
5823 "ALTER SESSION {set}",
5824 set = if *set { "SET" } else { "UNSET" }
5825 )?;
5826 if !session_params.options.is_empty() {
5827 if *set {
5828 write!(f, " {session_params}")?;
5829 } else {
5830 let options = session_params
5831 .options
5832 .iter()
5833 .map(|p| p.option_name.clone())
5834 .collect::<Vec<_>>();
5835 write!(f, " {}", display_separated(&options, ", "))?;
5836 }
5837 }
5838 Ok(())
5839 }
5840 Statement::Drop {
5841 object_type,
5842 if_exists,
5843 names,
5844 cascade,
5845 restrict,
5846 purge,
5847 temporary,
5848 table,
5849 } => {
5850 write!(
5851 f,
5852 "DROP {}{}{} {}{}{}{}",
5853 if *temporary { "TEMPORARY " } else { "" },
5854 object_type,
5855 if *if_exists { " IF EXISTS" } else { "" },
5856 display_comma_separated(names),
5857 if *cascade { " CASCADE" } else { "" },
5858 if *restrict { " RESTRICT" } else { "" },
5859 if *purge { " PURGE" } else { "" },
5860 )?;
5861 if let Some(table_name) = table.as_ref() {
5862 write!(f, " ON {table_name}")?;
5863 };
5864 Ok(())
5865 }
5866 Statement::DropFunction(drop_function) => write!(f, "{drop_function}"),
5867 Statement::DropDomain(DropDomain {
5868 if_exists,
5869 name,
5870 drop_behavior,
5871 }) => {
5872 write!(
5873 f,
5874 "DROP DOMAIN{} {name}",
5875 if *if_exists { " IF EXISTS" } else { "" },
5876 )?;
5877 if let Some(op) = drop_behavior {
5878 write!(f, " {op}")?;
5879 }
5880 Ok(())
5881 }
5882 Statement::DropProcedure {
5883 if_exists,
5884 proc_desc,
5885 drop_behavior,
5886 } => {
5887 write!(
5888 f,
5889 "DROP PROCEDURE{} {}",
5890 if *if_exists { " IF EXISTS" } else { "" },
5891 display_comma_separated(proc_desc),
5892 )?;
5893 if let Some(op) = drop_behavior {
5894 write!(f, " {op}")?;
5895 }
5896 Ok(())
5897 }
5898 Statement::DropSecret {
5899 if_exists,
5900 temporary,
5901 name,
5902 storage_specifier,
5903 } => {
5904 write!(f, "DROP ")?;
5905 if let Some(t) = temporary {
5906 write!(f, "{}", if *t { "TEMPORARY " } else { "PERSISTENT " })?;
5907 }
5908 write!(
5909 f,
5910 "SECRET {if_exists}{name}",
5911 if_exists = if *if_exists { "IF EXISTS " } else { "" },
5912 )?;
5913 if let Some(s) = storage_specifier {
5914 write!(f, " FROM {s}")?;
5915 }
5916 Ok(())
5917 }
5918 Statement::DropPolicy(policy) => write!(f, "{policy}"),
5919 Statement::DropRule(rule) => write!(f, "{rule}"),
5920 Statement::DropConnector { if_exists, name } => {
5921 write!(
5922 f,
5923 "DROP CONNECTOR {if_exists}{name}",
5924 if_exists = if *if_exists { "IF EXISTS " } else { "" }
5925 )?;
5926 Ok(())
5927 }
5928 Statement::Discard { object_type } => {
5929 write!(f, "DISCARD {object_type}")?;
5930 Ok(())
5931 }
5932 Self::Set(set) => write!(f, "{set}"),
5933 Statement::ShowVariable { variable } => {
5934 write!(f, "SHOW")?;
5935 if !variable.is_empty() {
5936 write!(f, " {}", display_separated(variable, " "))?;
5937 }
5938 Ok(())
5939 }
5940 Statement::ShowStatus {
5941 filter,
5942 global,
5943 session,
5944 } => {
5945 write!(f, "SHOW")?;
5946 if *global {
5947 write!(f, " GLOBAL")?;
5948 }
5949 if *session {
5950 write!(f, " SESSION")?;
5951 }
5952 write!(f, " STATUS")?;
5953 if let Some(filter) = filter {
5954 write!(f, " {}", filter)?;
5955 }
5956 Ok(())
5957 }
5958 Statement::ShowVariables {
5959 filter,
5960 global,
5961 session,
5962 } => {
5963 write!(f, "SHOW")?;
5964 if *global {
5965 write!(f, " GLOBAL")?;
5966 }
5967 if *session {
5968 write!(f, " SESSION")?;
5969 }
5970 write!(f, " VARIABLES")?;
5971 if let Some(filter) = filter {
5972 write!(f, " {}", filter)?;
5973 }
5974 Ok(())
5975 }
5976 Statement::ShowCreate { obj_type, obj_name } => {
5977 write!(f, "SHOW CREATE {obj_type} {obj_name}",)?;
5978 Ok(())
5979 }
5980 Statement::ShowColumns {
5981 extended,
5982 full,
5983 show_options,
5984 } => {
5985 write!(
5986 f,
5987 "SHOW {extended}{full}COLUMNS{show_options}",
5988 extended = if *extended { "EXTENDED " } else { "" },
5989 full = if *full { "FULL " } else { "" },
5990 )?;
5991 Ok(())
5992 }
5993 Statement::ShowDatabases {
5994 terse,
5995 history,
5996 show_options,
5997 } => {
5998 write!(
5999 f,
6000 "SHOW {terse}DATABASES{history}{show_options}",
6001 terse = if *terse { "TERSE " } else { "" },
6002 history = if *history { " HISTORY" } else { "" },
6003 )?;
6004 Ok(())
6005 }
6006 Statement::ShowCatalogs {
6007 terse,
6008 history,
6009 show_options,
6010 } => {
6011 write!(
6012 f,
6013 "SHOW {terse}CATALOGS{history}{show_options}",
6014 terse = if *terse { "TERSE " } else { "" },
6015 history = if *history { " HISTORY" } else { "" },
6016 )?;
6017 Ok(())
6018 }
6019 Statement::ShowProcessList { full } => {
6020 write!(
6021 f,
6022 "SHOW {full}PROCESSLIST",
6023 full = if *full { "FULL " } else { "" },
6024 )?;
6025 Ok(())
6026 }
6027 Statement::ShowSchemas {
6028 terse,
6029 history,
6030 show_options,
6031 } => {
6032 write!(
6033 f,
6034 "SHOW {terse}SCHEMAS{history}{show_options}",
6035 terse = if *terse { "TERSE " } else { "" },
6036 history = if *history { " HISTORY" } else { "" },
6037 )?;
6038 Ok(())
6039 }
6040 Statement::ShowObjects(ShowObjects {
6041 terse,
6042 show_options,
6043 }) => {
6044 write!(
6045 f,
6046 "SHOW {terse}OBJECTS{show_options}",
6047 terse = if *terse { "TERSE " } else { "" },
6048 )?;
6049 Ok(())
6050 }
6051 Statement::ShowTables {
6052 terse,
6053 history,
6054 extended,
6055 full,
6056 external,
6057 show_options,
6058 } => {
6059 write!(
6060 f,
6061 "SHOW {terse}{extended}{full}{external}TABLES{history}{show_options}",
6062 terse = if *terse { "TERSE " } else { "" },
6063 extended = if *extended { "EXTENDED " } else { "" },
6064 full = if *full { "FULL " } else { "" },
6065 external = if *external { "EXTERNAL " } else { "" },
6066 history = if *history { " HISTORY" } else { "" },
6067 )?;
6068 Ok(())
6069 }
6070 Statement::ShowViews {
6071 terse,
6072 materialized,
6073 show_options,
6074 } => {
6075 write!(
6076 f,
6077 "SHOW {terse}{materialized}VIEWS{show_options}",
6078 terse = if *terse { "TERSE " } else { "" },
6079 materialized = if *materialized { "MATERIALIZED " } else { "" }
6080 )?;
6081 Ok(())
6082 }
6083 Statement::ShowFunctions { filter } => {
6084 write!(f, "SHOW FUNCTIONS")?;
6085 if let Some(filter) = filter {
6086 write!(f, " {filter}")?;
6087 }
6088 Ok(())
6089 }
6090 Statement::Use(use_expr) => use_expr.fmt(f),
6091 Statement::ShowCollation { filter } => {
6092 write!(f, "SHOW COLLATION")?;
6093 if let Some(filter) = filter {
6094 write!(f, " {filter}")?;
6095 }
6096 Ok(())
6097 }
6098 Statement::ShowCharset(show_stm) => show_stm.fmt(f),
6099 Statement::StartTransaction {
6100 modes,
6101 begin: syntax_begin,
6102 transaction,
6103 modifier,
6104 statements,
6105 exception,
6106 has_end_keyword,
6107 } => {
6108 if *syntax_begin {
6109 if let Some(modifier) = *modifier {
6110 write!(f, "BEGIN {modifier}")?;
6111 } else {
6112 write!(f, "BEGIN")?;
6113 }
6114 } else {
6115 write!(f, "START")?;
6116 }
6117 if let Some(transaction) = transaction {
6118 write!(f, " {transaction}")?;
6119 }
6120 if !modes.is_empty() {
6121 write!(f, " {}", display_comma_separated(modes))?;
6122 }
6123 if !statements.is_empty() {
6124 write!(f, " ")?;
6125 format_statement_list(f, statements)?;
6126 }
6127 if let Some(exception_when) = exception {
6128 write!(f, " EXCEPTION")?;
6129 for when in exception_when {
6130 write!(f, " {when}")?;
6131 }
6132 }
6133 if *has_end_keyword {
6134 write!(f, " END")?;
6135 }
6136 Ok(())
6137 }
6138 Statement::Commit {
6139 chain,
6140 end: end_syntax,
6141 modifier,
6142 } => {
6143 if *end_syntax {
6144 write!(f, "END")?;
6145 if let Some(modifier) = *modifier {
6146 write!(f, " {modifier}")?;
6147 }
6148 if *chain {
6149 write!(f, " AND CHAIN")?;
6150 }
6151 } else {
6152 write!(f, "COMMIT{}", if *chain { " AND CHAIN" } else { "" })?;
6153 }
6154 Ok(())
6155 }
6156 Statement::Rollback { chain, savepoint } => {
6157 write!(f, "ROLLBACK")?;
6158
6159 if *chain {
6160 write!(f, " AND CHAIN")?;
6161 }
6162
6163 if let Some(savepoint) = savepoint {
6164 write!(f, " TO SAVEPOINT {savepoint}")?;
6165 }
6166
6167 Ok(())
6168 }
6169 Statement::CreateSchema {
6170 schema_name,
6171 or_replace,
6172 if_not_exists,
6173 with,
6174 options,
6175 default_collate_spec,
6176 clone,
6177 } => {
6178 write!(
6179 f,
6180 "CREATE {or_replace}SCHEMA {if_not_exists}{name}",
6181 or_replace = if *or_replace { "OR REPLACE " } else { "" },
6182 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
6183 name = schema_name
6184 )?;
6185
6186 if let Some(collate) = default_collate_spec {
6187 write!(f, " DEFAULT COLLATE {collate}")?;
6188 }
6189
6190 if let Some(with) = with {
6191 write!(f, " WITH ({})", display_comma_separated(with))?;
6192 }
6193
6194 if let Some(options) = options {
6195 write!(f, " OPTIONS({})", display_comma_separated(options))?;
6196 }
6197
6198 if let Some(clone) = clone {
6199 write!(f, " CLONE {clone}")?;
6200 }
6201 Ok(())
6202 }
6203 Statement::Assert { condition, message } => {
6204 write!(f, "ASSERT {condition}")?;
6205 if let Some(m) = message {
6206 write!(f, " AS {m}")?;
6207 }
6208 Ok(())
6209 }
6210 Statement::Grant(grant) => write!(f, "{grant}"),
6211 Statement::Deny(s) => write!(f, "{s}"),
6212 Statement::Revoke(revoke) => write!(f, "{revoke}"),
6213 Statement::GrantRole(grant) => write!(f, "{grant}"),
6214 Statement::RevokeRole(revoke) => write!(f, "{revoke}"),
6215 Statement::AlterDefaultPrivileges(stmt) => write!(f, "{stmt}"),
6216 Statement::Deallocate { name, prepare } => write!(
6217 f,
6218 "DEALLOCATE {prepare}{name}",
6219 prepare = if *prepare { "PREPARE " } else { "" },
6220 name = name,
6221 ),
6222 Statement::Execute {
6223 name,
6224 parameters,
6225 has_parentheses,
6226 immediate,
6227 into,
6228 using,
6229 output,
6230 default,
6231 } => {
6232 let (open, close) = if *has_parentheses {
6233 (if name.is_some() { "(" } else { " (" }, ")")
6235 } else {
6236 (if parameters.is_empty() { "" } else { " " }, "")
6237 };
6238 write!(f, "EXECUTE")?;
6239 if *immediate {
6240 write!(f, " IMMEDIATE")?;
6241 }
6242 if let Some(name) = name {
6243 write!(f, " {name}")?;
6244 }
6245 write!(f, "{open}{}{close}", display_comma_separated(parameters),)?;
6246 if !into.is_empty() {
6247 write!(f, " INTO {}", display_comma_separated(into))?;
6248 }
6249 if !using.is_empty() {
6250 write!(f, " USING {}", display_comma_separated(using))?;
6251 };
6252 if *output {
6253 write!(f, " OUTPUT")?;
6254 }
6255 if *default {
6256 write!(f, " DEFAULT")?;
6257 }
6258 Ok(())
6259 }
6260 Statement::Prepare {
6261 name,
6262 data_types,
6263 statement,
6264 } => {
6265 write!(f, "PREPARE {name} ")?;
6266 if !data_types.is_empty() {
6267 write!(f, "({}) ", display_comma_separated(data_types))?;
6268 }
6269 write!(f, "AS {statement}")
6270 }
6271 Statement::Comment {
6272 object_type,
6273 object_name,
6274 comment,
6275 if_exists,
6276 } => {
6277 write!(f, "COMMENT ")?;
6278 if *if_exists {
6279 write!(f, "IF EXISTS ")?
6280 };
6281 write!(f, "ON {object_type} {object_name} IS ")?;
6282 if let Some(c) = comment {
6283 write!(f, "'{c}'")
6284 } else {
6285 write!(f, "NULL")
6286 }
6287 }
6288 Statement::Savepoint { name } => {
6289 write!(f, "SAVEPOINT ")?;
6290 write!(f, "{name}")
6291 }
6292 Statement::ReleaseSavepoint { name } => {
6293 write!(f, "RELEASE SAVEPOINT {name}")
6294 }
6295 Statement::Merge(merge) => merge.fmt(f),
6296 Statement::Cache {
6297 table_name,
6298 table_flag,
6299 has_as,
6300 options,
6301 query,
6302 } => {
6303 if let Some(table_flag) = table_flag {
6304 write!(f, "CACHE {table_flag} TABLE {table_name}")?;
6305 } else {
6306 write!(f, "CACHE TABLE {table_name}")?;
6307 }
6308
6309 if !options.is_empty() {
6310 write!(f, " OPTIONS({})", display_comma_separated(options))?;
6311 }
6312
6313 match (*has_as, query) {
6314 (true, Some(query)) => write!(f, " AS {query}"),
6315 (true, None) => f.write_str(" AS"),
6316 (false, Some(query)) => write!(f, " {query}"),
6317 (false, None) => Ok(()),
6318 }
6319 }
6320 Statement::UNCache {
6321 table_name,
6322 if_exists,
6323 } => {
6324 if *if_exists {
6325 write!(f, "UNCACHE TABLE IF EXISTS {table_name}")
6326 } else {
6327 write!(f, "UNCACHE TABLE {table_name}")
6328 }
6329 }
6330 Statement::CreateSequence {
6331 temporary,
6332 if_not_exists,
6333 name,
6334 sequence_options,
6335 } => {
6336 write!(
6337 f,
6338 "CREATE {temporary}SEQUENCE {if_not_exists}{name}",
6339 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
6340 temporary = if *temporary { "TEMPORARY " } else { "" },
6341 name = name,
6342 )?;
6343 for sequence_option in sequence_options {
6344 write!(f, "{sequence_option}")?;
6345 }
6346 Ok(())
6347 }
6348 Statement::CreateStage {
6349 or_replace,
6350 temporary,
6351 if_not_exists,
6352 name,
6353 stage_params,
6354 directory_table_params,
6355 file_format,
6356 copy_options,
6357 comment,
6358 ..
6359 } => {
6360 write!(
6361 f,
6362 "CREATE {or_replace}{temp}STAGE {if_not_exists}{name}{stage_params}",
6363 temp = if *temporary { "TEMPORARY " } else { "" },
6364 or_replace = if *or_replace { "OR REPLACE " } else { "" },
6365 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
6366 )?;
6367 if !directory_table_params.options.is_empty() {
6368 write!(f, " DIRECTORY=({directory_table_params})")?;
6369 }
6370 if !file_format.options.is_empty() {
6371 write!(f, " FILE_FORMAT=({file_format})")?;
6372 }
6373 if !copy_options.options.is_empty() {
6374 write!(f, " COPY_OPTIONS=({copy_options})")?;
6375 }
6376 if let Some(comment) = comment {
6377 write!(f, " COMMENT='{}'", comment)?;
6378 }
6379 Ok(())
6380 }
6381 Statement::CreateFileFormat {
6382 or_replace,
6383 temporary,
6384 volatile,
6385 if_not_exists,
6386 name,
6387 options,
6388 comment,
6389 } => {
6390 write!(
6391 f,
6392 "CREATE {or_replace}{temp}{volatile}FILE FORMAT {if_not_exists}{name}",
6393 or_replace = if *or_replace { "OR REPLACE " } else { "" },
6394 temp = if *temporary { "TEMPORARY " } else { "" },
6395 volatile = if *volatile { "VOLATILE " } else { "" },
6396 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
6397 )?;
6398 if !options.options.is_empty() {
6399 write!(f, " {options}")?;
6400 }
6401 if let Some(comment) = comment {
6402 write!(f, " COMMENT='{}'", comment)?;
6403 }
6404 Ok(())
6405 }
6406 Statement::CreateWarehouse(s) => write!(f, "{s}"),
6407 Statement::CopyIntoSnowflake {
6408 kind,
6409 into,
6410 into_columns,
6411 from_obj,
6412 from_obj_alias,
6413 stage_params,
6414 from_transformations,
6415 from_query,
6416 files,
6417 pattern,
6418 file_format,
6419 copy_options,
6420 validation_mode,
6421 partition,
6422 } => {
6423 write!(f, "COPY INTO {into}")?;
6424 if let Some(into_columns) = into_columns {
6425 write!(f, " ({})", display_comma_separated(into_columns))?;
6426 }
6427 if let Some(from_transformations) = from_transformations {
6428 if let Some(from_stage) = from_obj {
6430 write!(
6431 f,
6432 " FROM (SELECT {} FROM {}{}",
6433 display_separated(from_transformations, ", "),
6434 from_stage,
6435 stage_params
6436 )?;
6437 }
6438 if let Some(from_obj_alias) = from_obj_alias {
6439 write!(f, " AS {from_obj_alias}")?;
6440 }
6441 write!(f, ")")?;
6442 } else if let Some(from_obj) = from_obj {
6443 write!(f, " FROM {from_obj}{stage_params}")?;
6445 if let Some(from_obj_alias) = from_obj_alias {
6446 write!(f, " AS {from_obj_alias}")?;
6447 }
6448 } else if let Some(from_query) = from_query {
6449 write!(f, " FROM ({from_query})")?;
6451 }
6452
6453 if let Some(files) = files {
6454 write!(f, " FILES = ('{}')", display_separated(files, "', '"))?;
6455 }
6456 if let Some(pattern) = pattern {
6457 write!(f, " PATTERN = '{pattern}'")?;
6458 }
6459 if let Some(partition) = partition {
6460 write!(f, " PARTITION BY {partition}")?;
6461 }
6462 if !file_format.options.is_empty() {
6463 write!(f, " FILE_FORMAT=({file_format})")?;
6464 }
6465 if !copy_options.options.is_empty() {
6466 match kind {
6467 CopyIntoSnowflakeKind::Table => {
6468 write!(f, " COPY_OPTIONS=({copy_options})")?
6469 }
6470 CopyIntoSnowflakeKind::Location => write!(f, " {copy_options}")?,
6471 }
6472 }
6473 if let Some(validation_mode) = validation_mode {
6474 write!(f, " VALIDATION_MODE = {validation_mode}")?;
6475 }
6476 Ok(())
6477 }
6478 Statement::CreateType {
6479 name,
6480 representation,
6481 } => {
6482 write!(f, "CREATE TYPE {name}")?;
6483 if let Some(repr) = representation {
6484 write!(f, " {repr}")?;
6485 }
6486 Ok(())
6487 }
6488 Statement::Pragma { name, value, is_eq } => {
6489 write!(f, "PRAGMA {name}")?;
6490 if let Some(value) = value {
6491 if *is_eq {
6492 write!(f, " = {value}")?;
6493 } else {
6494 write!(f, "({value})")?;
6495 }
6496 }
6497 Ok(())
6498 }
6499 Statement::Lock(lock) => lock.fmt(f),
6500 Statement::LockTables { tables } => {
6501 write!(f, "LOCK TABLES {}", display_comma_separated(tables))
6502 }
6503 Statement::UnlockTables => {
6504 write!(f, "UNLOCK TABLES")
6505 }
6506 Statement::Unload {
6507 query,
6508 query_text,
6509 to,
6510 auth,
6511 with,
6512 options,
6513 } => {
6514 write!(f, "UNLOAD(")?;
6515 if let Some(query) = query {
6516 write!(f, "{query}")?;
6517 }
6518 if let Some(query_text) = query_text {
6519 write!(f, "'{query_text}'")?;
6520 }
6521 write!(f, ") TO {to}")?;
6522 if let Some(auth) = auth {
6523 write!(f, " IAM_ROLE {auth}")?;
6524 }
6525 if !with.is_empty() {
6526 write!(f, " WITH ({})", display_comma_separated(with))?;
6527 }
6528 if !options.is_empty() {
6529 write!(f, " {}", display_separated(options, " "))?;
6530 }
6531 Ok(())
6532 }
6533 Statement::OptimizeTable {
6534 name,
6535 has_table_keyword,
6536 on_cluster,
6537 partition,
6538 include_final,
6539 deduplicate,
6540 predicate,
6541 zorder,
6542 } => {
6543 write!(f, "OPTIMIZE")?;
6544 if *has_table_keyword {
6545 write!(f, " TABLE")?;
6546 }
6547 write!(f, " {name}")?;
6548 if let Some(on_cluster) = on_cluster {
6549 write!(f, " ON CLUSTER {on_cluster}")?;
6550 }
6551 if let Some(partition) = partition {
6552 write!(f, " {partition}")?;
6553 }
6554 if *include_final {
6555 write!(f, " FINAL")?;
6556 }
6557 if let Some(deduplicate) = deduplicate {
6558 write!(f, " {deduplicate}")?;
6559 }
6560 if let Some(predicate) = predicate {
6561 write!(f, " WHERE {predicate}")?;
6562 }
6563 if let Some(zorder) = zorder {
6564 write!(f, " ZORDER BY ({})", display_comma_separated(zorder))?;
6565 }
6566 Ok(())
6567 }
6568 Statement::LISTEN { channel } => {
6569 write!(f, "LISTEN {channel}")?;
6570 Ok(())
6571 }
6572 Statement::UNLISTEN { channel } => {
6573 write!(f, "UNLISTEN {channel}")?;
6574 Ok(())
6575 }
6576 Statement::NOTIFY { channel, payload } => {
6577 write!(f, "NOTIFY {channel}")?;
6578 if let Some(payload) = payload {
6579 write!(f, ", '{payload}'")?;
6580 }
6581 Ok(())
6582 }
6583 Statement::RenameTable(rename_tables) => {
6584 write!(f, "RENAME TABLE {}", display_comma_separated(rename_tables))
6585 }
6586 Statement::RaisError {
6587 message,
6588 severity,
6589 state,
6590 arguments,
6591 options,
6592 } => {
6593 write!(f, "RAISERROR({message}, {severity}, {state}")?;
6594 if !arguments.is_empty() {
6595 write!(f, ", {}", display_comma_separated(arguments))?;
6596 }
6597 write!(f, ")")?;
6598 if !options.is_empty() {
6599 write!(f, " WITH {}", display_comma_separated(options))?;
6600 }
6601 Ok(())
6602 }
6603 Statement::Throw(s) => write!(f, "{s}"),
6604 Statement::Print(s) => write!(f, "{s}"),
6605 Statement::WaitFor(s) => write!(f, "{s}"),
6606 Statement::Return(r) => write!(f, "{r}"),
6607 Statement::List(command) => write!(f, "LIST {command}"),
6608 Statement::Put {
6609 source,
6610 stage,
6611 options,
6612 } => {
6613 write!(f, "PUT '{source}' {stage}")?;
6614 if !options.options.is_empty() {
6615 write!(f, " {options}")?;
6616 }
6617 Ok(())
6618 }
6619 Statement::Remove(command) => write!(f, "REMOVE {command}"),
6620 Statement::ExportData(e) => write!(f, "{e}"),
6621 Statement::CreateUser(s) => write!(f, "{s}"),
6622 Statement::AlterSchema(s) => write!(f, "{s}"),
6623 Statement::Vacuum(s) => write!(f, "{s}"),
6624 Statement::AlterUser(s) => write!(f, "{s}"),
6625 Statement::Reset(s) => write!(f, "{s}"),
6626 Statement::RefreshMaterializedView(s) => write!(f, "{s}"),
6627 }
6628 }
6629}
6630
6631#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6643#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6644#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6645pub enum SequenceOptions {
6646 DataType(DataType),
6648 IncrementBy(Expr, bool),
6650 MinValue(Option<Expr>),
6652 MaxValue(Option<Expr>),
6654 StartWith(Expr, bool),
6656 Cache(Expr),
6658 Cycle(bool),
6660 OwnedBy(Option<ObjectName>),
6662}
6663
6664impl fmt::Display for SequenceOptions {
6665 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6666 match self {
6667 SequenceOptions::DataType(data_type) => {
6668 write!(f, " AS {data_type}")
6669 }
6670 SequenceOptions::IncrementBy(increment, by) => {
6671 write!(
6672 f,
6673 " INCREMENT{by} {increment}",
6674 by = if *by { " BY" } else { "" },
6675 increment = increment
6676 )
6677 }
6678 SequenceOptions::MinValue(Some(expr)) => {
6679 write!(f, " MINVALUE {expr}")
6680 }
6681 SequenceOptions::MinValue(None) => {
6682 write!(f, " NO MINVALUE")
6683 }
6684 SequenceOptions::MaxValue(Some(expr)) => {
6685 write!(f, " MAXVALUE {expr}")
6686 }
6687 SequenceOptions::MaxValue(None) => {
6688 write!(f, " NO MAXVALUE")
6689 }
6690 SequenceOptions::StartWith(start, with) => {
6691 write!(
6692 f,
6693 " START{with} {start}",
6694 with = if *with { " WITH" } else { "" },
6695 start = start
6696 )
6697 }
6698 SequenceOptions::Cache(cache) => {
6699 write!(f, " CACHE {}", *cache)
6700 }
6701 SequenceOptions::Cycle(no) => {
6702 write!(f, " {}CYCLE", if *no { "NO " } else { "" })
6703 }
6704 SequenceOptions::OwnedBy(Some(object_name)) => {
6705 write!(f, " OWNED BY {object_name}")
6706 }
6707 SequenceOptions::OwnedBy(None) => {
6708 write!(f, " OWNED BY NONE")
6709 }
6710 }
6711 }
6712}
6713
6714#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6716#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6717#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6718pub struct SetAssignment {
6719 pub scope: Option<ContextModifier>,
6721 pub name: ObjectName,
6723 pub value: Expr,
6725}
6726
6727impl fmt::Display for SetAssignment {
6728 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6729 write!(
6730 f,
6731 "{}{} = {}",
6732 self.scope.map(|s| format!("{s}")).unwrap_or_default(),
6733 self.name,
6734 self.value
6735 )
6736 }
6737}
6738
6739#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6743#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6744#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6745pub struct TruncateTableTarget {
6746 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6748 pub name: ObjectName,
6749 pub only: bool,
6755 pub has_asterisk: bool,
6761}
6762
6763impl fmt::Display for TruncateTableTarget {
6764 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6765 if self.only {
6766 write!(f, "ONLY ")?;
6767 };
6768 write!(f, "{}", self.name)?;
6769 if self.has_asterisk {
6770 write!(f, " *")?;
6771 };
6772 Ok(())
6773 }
6774}
6775
6776#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6780#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6781#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6782pub struct Lock {
6783 pub tables: Vec<LockTableTarget>,
6785 pub lock_mode: Option<LockTableMode>,
6787 pub nowait: bool,
6789}
6790
6791impl fmt::Display for Lock {
6792 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6793 write!(f, "LOCK TABLE {}", display_comma_separated(&self.tables))?;
6794 if let Some(lock_mode) = &self.lock_mode {
6795 write!(f, " IN {lock_mode} MODE")?;
6796 }
6797 if self.nowait {
6798 write!(f, " NOWAIT")?;
6799 }
6800 Ok(())
6801 }
6802}
6803
6804#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6808#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6809#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6810pub struct LockTableTarget {
6811 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6813 pub name: ObjectName,
6814 pub only: bool,
6816 pub has_asterisk: bool,
6818}
6819
6820impl fmt::Display for LockTableTarget {
6821 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6822 if self.only {
6823 write!(f, "ONLY ")?;
6824 }
6825 write!(f, "{}", self.name)?;
6826 if self.has_asterisk {
6827 write!(f, " *")?;
6828 }
6829 Ok(())
6830 }
6831}
6832
6833#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6837#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6838#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6839pub enum LockTableMode {
6840 AccessShare,
6842 RowShare,
6844 RowExclusive,
6846 ShareUpdateExclusive,
6848 Share,
6850 ShareRowExclusive,
6852 Exclusive,
6854 AccessExclusive,
6856}
6857
6858impl fmt::Display for LockTableMode {
6859 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6860 let text = match self {
6861 Self::AccessShare => "ACCESS SHARE",
6862 Self::RowShare => "ROW SHARE",
6863 Self::RowExclusive => "ROW EXCLUSIVE",
6864 Self::ShareUpdateExclusive => "SHARE UPDATE EXCLUSIVE",
6865 Self::Share => "SHARE",
6866 Self::ShareRowExclusive => "SHARE ROW EXCLUSIVE",
6867 Self::Exclusive => "EXCLUSIVE",
6868 Self::AccessExclusive => "ACCESS EXCLUSIVE",
6869 };
6870 write!(f, "{text}")
6871 }
6872}
6873
6874#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6877#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6878#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6879pub enum TruncateIdentityOption {
6880 Restart,
6882 Continue,
6884}
6885
6886#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6889#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6890#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6891pub enum CascadeOption {
6892 Cascade,
6894 Restrict,
6896}
6897
6898impl Display for CascadeOption {
6899 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6900 match self {
6901 CascadeOption::Cascade => write!(f, "CASCADE"),
6902 CascadeOption::Restrict => write!(f, "RESTRICT"),
6903 }
6904 }
6905}
6906
6907#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6909#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6910#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6911pub enum BeginTransactionKind {
6912 Transaction,
6914 Work,
6916 Tran,
6919}
6920
6921impl Display for BeginTransactionKind {
6922 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6923 match self {
6924 BeginTransactionKind::Transaction => write!(f, "TRANSACTION"),
6925 BeginTransactionKind::Work => write!(f, "WORK"),
6926 BeginTransactionKind::Tran => write!(f, "TRAN"),
6927 }
6928 }
6929}
6930
6931#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6934#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6935#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6936pub enum MinMaxValue {
6937 Empty,
6939 None,
6941 Some(Expr),
6943}
6944
6945#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6946#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6947#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6948#[non_exhaustive]
6949pub enum OnInsert {
6951 DuplicateKeyUpdate(Vec<Assignment>),
6953 OnConflict(OnConflict),
6955}
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 struct InsertAliases {
6962 pub row_alias: ObjectName,
6964 pub col_aliases: Option<Vec<Ident>>,
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 TableAliasWithoutColumns {
6973 pub explicit: bool,
6975 pub alias: Ident,
6977}
6978
6979#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6980#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6981#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6982pub struct OnConflict {
6984 pub conflict_target: Option<ConflictTarget>,
6986 pub action: OnConflictAction,
6988}
6989#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6990#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6991#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6992pub enum ConflictTarget {
6994 Columns {
7001 columns: Vec<Ident>,
7003 predicate: Option<Expr>,
7005 },
7006 OnConstraint(ObjectName),
7008}
7009#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7010#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7011#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7012pub enum OnConflictAction {
7014 DoNothing,
7016 DoUpdate(DoUpdate),
7018}
7019
7020#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7021#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7022#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7023pub struct DoUpdate {
7025 pub assignments: Vec<Assignment>,
7027 pub selection: Option<Expr>,
7029}
7030
7031impl fmt::Display for OnInsert {
7032 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7033 match self {
7034 Self::DuplicateKeyUpdate(expr) => write!(
7035 f,
7036 " ON DUPLICATE KEY UPDATE {}",
7037 display_comma_separated(expr)
7038 ),
7039 Self::OnConflict(o) => write!(f, "{o}"),
7040 }
7041 }
7042}
7043impl fmt::Display for OnConflict {
7044 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7045 write!(f, " ON CONFLICT")?;
7046 if let Some(target) = &self.conflict_target {
7047 write!(f, "{target}")?;
7048 }
7049 write!(f, " {}", self.action)
7050 }
7051}
7052impl fmt::Display for ConflictTarget {
7053 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7054 match self {
7055 ConflictTarget::Columns { columns, predicate } => {
7056 write!(f, "({})", display_comma_separated(columns))?;
7057 if let Some(predicate) = predicate {
7058 write!(f, " WHERE {predicate}")?;
7059 }
7060 Ok(())
7061 }
7062 ConflictTarget::OnConstraint(name) => write!(f, " ON CONSTRAINT {name}"),
7063 }
7064 }
7065}
7066impl fmt::Display for OnConflictAction {
7067 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7068 match self {
7069 Self::DoNothing => write!(f, "DO NOTHING"),
7070 Self::DoUpdate(do_update) => {
7071 write!(f, "DO UPDATE")?;
7072 if !do_update.assignments.is_empty() {
7073 write!(
7074 f,
7075 " SET {}",
7076 display_comma_separated(&do_update.assignments)
7077 )?;
7078 }
7079 if let Some(selection) = &do_update.selection {
7080 write!(f, " WHERE {selection}")?;
7081 }
7082 Ok(())
7083 }
7084 }
7085 }
7086}
7087
7088#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7090#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7091#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7092pub enum Privileges {
7093 All {
7095 with_privileges_keyword: bool,
7097 },
7098 Actions(Vec<Action>),
7100}
7101
7102impl fmt::Display for Privileges {
7103 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7104 match self {
7105 Privileges::All {
7106 with_privileges_keyword,
7107 } => {
7108 write!(
7109 f,
7110 "ALL{}",
7111 if *with_privileges_keyword {
7112 " PRIVILEGES"
7113 } else {
7114 ""
7115 }
7116 )
7117 }
7118 Privileges::Actions(actions) => {
7119 write!(f, "{}", display_comma_separated(actions))
7120 }
7121 }
7122 }
7123}
7124
7125#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7127#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7128#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7129pub enum FetchDirection {
7130 Count {
7132 limit: ValueWithSpan,
7134 },
7135 Next,
7137 Prior,
7139 First,
7141 Last,
7143 Absolute {
7145 limit: ValueWithSpan,
7147 },
7148 Relative {
7150 limit: ValueWithSpan,
7152 },
7153 All,
7155 Forward {
7159 limit: Option<ValueWithSpan>,
7161 },
7162 ForwardAll,
7164 Backward {
7168 limit: Option<ValueWithSpan>,
7170 },
7171 BackwardAll,
7173}
7174
7175impl fmt::Display for FetchDirection {
7176 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7177 match self {
7178 FetchDirection::Count { limit } => f.write_str(&limit.to_string())?,
7179 FetchDirection::Next => f.write_str("NEXT")?,
7180 FetchDirection::Prior => f.write_str("PRIOR")?,
7181 FetchDirection::First => f.write_str("FIRST")?,
7182 FetchDirection::Last => f.write_str("LAST")?,
7183 FetchDirection::Absolute { limit } => {
7184 f.write_str("ABSOLUTE ")?;
7185 f.write_str(&limit.to_string())?;
7186 }
7187 FetchDirection::Relative { limit } => {
7188 f.write_str("RELATIVE ")?;
7189 f.write_str(&limit.to_string())?;
7190 }
7191 FetchDirection::All => f.write_str("ALL")?,
7192 FetchDirection::Forward { limit } => {
7193 f.write_str("FORWARD")?;
7194
7195 if let Some(l) = limit {
7196 f.write_str(" ")?;
7197 f.write_str(&l.to_string())?;
7198 }
7199 }
7200 FetchDirection::ForwardAll => f.write_str("FORWARD ALL")?,
7201 FetchDirection::Backward { limit } => {
7202 f.write_str("BACKWARD")?;
7203
7204 if let Some(l) = limit {
7205 f.write_str(" ")?;
7206 f.write_str(&l.to_string())?;
7207 }
7208 }
7209 FetchDirection::BackwardAll => f.write_str("BACKWARD ALL")?,
7210 };
7211
7212 Ok(())
7213 }
7214}
7215
7216#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7220#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7221#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7222pub enum FetchPosition {
7223 From,
7225 In,
7227}
7228
7229impl fmt::Display for FetchPosition {
7230 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7231 match self {
7232 FetchPosition::From => f.write_str("FROM")?,
7233 FetchPosition::In => f.write_str("IN")?,
7234 };
7235
7236 Ok(())
7237 }
7238}
7239
7240#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7242#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7243#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7244pub enum Action {
7245 AddSearchOptimization,
7247 Apply {
7249 apply_type: ActionApplyType,
7251 },
7252 ApplyBudget,
7254 AttachListing,
7256 AttachPolicy,
7258 Audit,
7260 BindServiceEndpoint,
7262 Connect,
7264 Create {
7266 obj_type: Option<ActionCreateObjectType>,
7268 },
7269 DatabaseRole {
7271 role: ObjectName,
7273 },
7274 Delete,
7276 Drop,
7278 EvolveSchema,
7280 Exec {
7282 obj_type: Option<ActionExecuteObjectType>,
7284 },
7285 Execute {
7287 obj_type: Option<ActionExecuteObjectType>,
7289 },
7290 Failover,
7292 ImportedPrivileges,
7294 ImportShare,
7296 Insert {
7298 columns: Option<Vec<Ident>>,
7300 },
7301 Manage {
7303 manage_type: ActionManageType,
7305 },
7306 ManageReleases,
7308 ManageVersions,
7310 Modify {
7312 modify_type: Option<ActionModifyType>,
7314 },
7315 Monitor {
7317 monitor_type: Option<ActionMonitorType>,
7319 },
7320 Operate,
7322 OverrideShareRestrictions,
7324 Ownership,
7326 PurchaseDataExchangeListing,
7328
7329 Read,
7331 ReadSession,
7333 References {
7335 columns: Option<Vec<Ident>>,
7337 },
7338 Replicate,
7340 ResolveAll,
7342 Role {
7344 role: ObjectName,
7346 },
7347 Select {
7349 columns: Option<Vec<Ident>>,
7351 },
7352 Temporary,
7354 Trigger,
7356 Truncate,
7358 Update {
7360 columns: Option<Vec<Ident>>,
7362 },
7363 Usage,
7365}
7366
7367impl fmt::Display for Action {
7368 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7369 match self {
7370 Action::AddSearchOptimization => f.write_str("ADD SEARCH OPTIMIZATION")?,
7371 Action::Apply { apply_type } => write!(f, "APPLY {apply_type}")?,
7372 Action::ApplyBudget => f.write_str("APPLYBUDGET")?,
7373 Action::AttachListing => f.write_str("ATTACH LISTING")?,
7374 Action::AttachPolicy => f.write_str("ATTACH POLICY")?,
7375 Action::Audit => f.write_str("AUDIT")?,
7376 Action::BindServiceEndpoint => f.write_str("BIND SERVICE ENDPOINT")?,
7377 Action::Connect => f.write_str("CONNECT")?,
7378 Action::Create { obj_type } => {
7379 f.write_str("CREATE")?;
7380 if let Some(obj_type) = obj_type {
7381 write!(f, " {obj_type}")?
7382 }
7383 }
7384 Action::DatabaseRole { role } => write!(f, "DATABASE ROLE {role}")?,
7385 Action::Delete => f.write_str("DELETE")?,
7386 Action::Drop => f.write_str("DROP")?,
7387 Action::EvolveSchema => f.write_str("EVOLVE SCHEMA")?,
7388 Action::Exec { obj_type } => {
7389 f.write_str("EXEC")?;
7390 if let Some(obj_type) = obj_type {
7391 write!(f, " {obj_type}")?
7392 }
7393 }
7394 Action::Execute { obj_type } => {
7395 f.write_str("EXECUTE")?;
7396 if let Some(obj_type) = obj_type {
7397 write!(f, " {obj_type}")?
7398 }
7399 }
7400 Action::Failover => f.write_str("FAILOVER")?,
7401 Action::ImportedPrivileges => f.write_str("IMPORTED PRIVILEGES")?,
7402 Action::ImportShare => f.write_str("IMPORT SHARE")?,
7403 Action::Insert { .. } => f.write_str("INSERT")?,
7404 Action::Manage { manage_type } => write!(f, "MANAGE {manage_type}")?,
7405 Action::ManageReleases => f.write_str("MANAGE RELEASES")?,
7406 Action::ManageVersions => f.write_str("MANAGE VERSIONS")?,
7407 Action::Modify { modify_type } => {
7408 write!(f, "MODIFY")?;
7409 if let Some(modify_type) = modify_type {
7410 write!(f, " {modify_type}")?;
7411 }
7412 }
7413 Action::Monitor { monitor_type } => {
7414 write!(f, "MONITOR")?;
7415 if let Some(monitor_type) = monitor_type {
7416 write!(f, " {monitor_type}")?
7417 }
7418 }
7419 Action::Operate => f.write_str("OPERATE")?,
7420 Action::OverrideShareRestrictions => f.write_str("OVERRIDE SHARE RESTRICTIONS")?,
7421 Action::Ownership => f.write_str("OWNERSHIP")?,
7422 Action::PurchaseDataExchangeListing => f.write_str("PURCHASE DATA EXCHANGE LISTING")?,
7423 Action::Read => f.write_str("READ")?,
7424 Action::ReadSession => f.write_str("READ SESSION")?,
7425 Action::References { .. } => f.write_str("REFERENCES")?,
7426 Action::Replicate => f.write_str("REPLICATE")?,
7427 Action::ResolveAll => f.write_str("RESOLVE ALL")?,
7428 Action::Role { role } => write!(f, "ROLE {role}")?,
7429 Action::Select { .. } => f.write_str("SELECT")?,
7430 Action::Temporary => f.write_str("TEMPORARY")?,
7431 Action::Trigger => f.write_str("TRIGGER")?,
7432 Action::Truncate => f.write_str("TRUNCATE")?,
7433 Action::Update { .. } => f.write_str("UPDATE")?,
7434 Action::Usage => f.write_str("USAGE")?,
7435 };
7436 match self {
7437 Action::Insert { columns }
7438 | Action::References { columns }
7439 | Action::Select { columns }
7440 | Action::Update { columns } => {
7441 if let Some(columns) = columns {
7442 write!(f, " ({})", display_comma_separated(columns))?;
7443 }
7444 }
7445 _ => (),
7446 };
7447 Ok(())
7448 }
7449}
7450
7451#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7452#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7453#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7454pub enum ActionCreateObjectType {
7457 Account,
7459 Application,
7461 ApplicationPackage,
7463 ComputePool,
7465 DataExchangeListing,
7467 Database,
7469 ExternalVolume,
7471 FailoverGroup,
7473 Integration,
7475 NetworkPolicy,
7477 OrganiationListing,
7479 ReplicationGroup,
7481 Role,
7483 Schema,
7485 Share,
7487 User,
7489 Warehouse,
7491}
7492
7493impl fmt::Display for ActionCreateObjectType {
7494 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7495 match self {
7496 ActionCreateObjectType::Account => write!(f, "ACCOUNT"),
7497 ActionCreateObjectType::Application => write!(f, "APPLICATION"),
7498 ActionCreateObjectType::ApplicationPackage => write!(f, "APPLICATION PACKAGE"),
7499 ActionCreateObjectType::ComputePool => write!(f, "COMPUTE POOL"),
7500 ActionCreateObjectType::DataExchangeListing => write!(f, "DATA EXCHANGE LISTING"),
7501 ActionCreateObjectType::Database => write!(f, "DATABASE"),
7502 ActionCreateObjectType::ExternalVolume => write!(f, "EXTERNAL VOLUME"),
7503 ActionCreateObjectType::FailoverGroup => write!(f, "FAILOVER GROUP"),
7504 ActionCreateObjectType::Integration => write!(f, "INTEGRATION"),
7505 ActionCreateObjectType::NetworkPolicy => write!(f, "NETWORK POLICY"),
7506 ActionCreateObjectType::OrganiationListing => write!(f, "ORGANIZATION LISTING"),
7507 ActionCreateObjectType::ReplicationGroup => write!(f, "REPLICATION GROUP"),
7508 ActionCreateObjectType::Role => write!(f, "ROLE"),
7509 ActionCreateObjectType::Schema => write!(f, "SCHEMA"),
7510 ActionCreateObjectType::Share => write!(f, "SHARE"),
7511 ActionCreateObjectType::User => write!(f, "USER"),
7512 ActionCreateObjectType::Warehouse => write!(f, "WAREHOUSE"),
7513 }
7514 }
7515}
7516
7517#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7518#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7519#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7520pub enum ActionApplyType {
7523 AggregationPolicy,
7525 AuthenticationPolicy,
7527 JoinPolicy,
7529 MaskingPolicy,
7531 PackagesPolicy,
7533 PasswordPolicy,
7535 ProjectionPolicy,
7537 RowAccessPolicy,
7539 SessionPolicy,
7541 Tag,
7543}
7544
7545impl fmt::Display for ActionApplyType {
7546 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7547 match self {
7548 ActionApplyType::AggregationPolicy => write!(f, "AGGREGATION POLICY"),
7549 ActionApplyType::AuthenticationPolicy => write!(f, "AUTHENTICATION POLICY"),
7550 ActionApplyType::JoinPolicy => write!(f, "JOIN POLICY"),
7551 ActionApplyType::MaskingPolicy => write!(f, "MASKING POLICY"),
7552 ActionApplyType::PackagesPolicy => write!(f, "PACKAGES POLICY"),
7553 ActionApplyType::PasswordPolicy => write!(f, "PASSWORD POLICY"),
7554 ActionApplyType::ProjectionPolicy => write!(f, "PROJECTION POLICY"),
7555 ActionApplyType::RowAccessPolicy => write!(f, "ROW ACCESS POLICY"),
7556 ActionApplyType::SessionPolicy => write!(f, "SESSION POLICY"),
7557 ActionApplyType::Tag => write!(f, "TAG"),
7558 }
7559 }
7560}
7561
7562#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7563#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7564#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7565pub enum ActionExecuteObjectType {
7568 Alert,
7570 DataMetricFunction,
7572 ManagedAlert,
7574 ManagedTask,
7576 Task,
7578}
7579
7580impl fmt::Display for ActionExecuteObjectType {
7581 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7582 match self {
7583 ActionExecuteObjectType::Alert => write!(f, "ALERT"),
7584 ActionExecuteObjectType::DataMetricFunction => write!(f, "DATA METRIC FUNCTION"),
7585 ActionExecuteObjectType::ManagedAlert => write!(f, "MANAGED ALERT"),
7586 ActionExecuteObjectType::ManagedTask => write!(f, "MANAGED TASK"),
7587 ActionExecuteObjectType::Task => write!(f, "TASK"),
7588 }
7589 }
7590}
7591
7592#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7593#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7594#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7595pub enum ActionManageType {
7598 AccountSupportCases,
7600 EventSharing,
7602 Grants,
7604 ListingAutoFulfillment,
7606 OrganizationSupportCases,
7608 UserSupportCases,
7610 Warehouses,
7612}
7613
7614impl fmt::Display for ActionManageType {
7615 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7616 match self {
7617 ActionManageType::AccountSupportCases => write!(f, "ACCOUNT SUPPORT CASES"),
7618 ActionManageType::EventSharing => write!(f, "EVENT SHARING"),
7619 ActionManageType::Grants => write!(f, "GRANTS"),
7620 ActionManageType::ListingAutoFulfillment => write!(f, "LISTING AUTO FULFILLMENT"),
7621 ActionManageType::OrganizationSupportCases => write!(f, "ORGANIZATION SUPPORT CASES"),
7622 ActionManageType::UserSupportCases => write!(f, "USER SUPPORT CASES"),
7623 ActionManageType::Warehouses => write!(f, "WAREHOUSES"),
7624 }
7625 }
7626}
7627
7628#[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 enum ActionModifyType {
7634 LogLevel,
7636 TraceLevel,
7638 SessionLogLevel,
7640 SessionTraceLevel,
7642}
7643
7644impl fmt::Display for ActionModifyType {
7645 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7646 match self {
7647 ActionModifyType::LogLevel => write!(f, "LOG LEVEL"),
7648 ActionModifyType::TraceLevel => write!(f, "TRACE LEVEL"),
7649 ActionModifyType::SessionLogLevel => write!(f, "SESSION LOG LEVEL"),
7650 ActionModifyType::SessionTraceLevel => write!(f, "SESSION TRACE LEVEL"),
7651 }
7652 }
7653}
7654
7655#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7656#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7657#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7658pub enum ActionMonitorType {
7661 Execution,
7663 Security,
7665 Usage,
7667}
7668
7669impl fmt::Display for ActionMonitorType {
7670 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7671 match self {
7672 ActionMonitorType::Execution => write!(f, "EXECUTION"),
7673 ActionMonitorType::Security => write!(f, "SECURITY"),
7674 ActionMonitorType::Usage => write!(f, "USAGE"),
7675 }
7676 }
7677}
7678
7679#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7681#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7682#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7683pub struct Grantee {
7684 pub grantee_type: GranteesType,
7686 pub name: Option<GranteeName>,
7688}
7689
7690impl fmt::Display for Grantee {
7691 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7692 let keyword = match self.grantee_type {
7693 GranteesType::Role => "ROLE",
7694 GranteesType::Share => "SHARE",
7695 GranteesType::User => "USER",
7696 GranteesType::Group => "GROUP",
7697 GranteesType::Public => "PUBLIC",
7698 GranteesType::DatabaseRole => "DATABASE ROLE",
7699 GranteesType::Application => "APPLICATION",
7700 GranteesType::ApplicationRole => "APPLICATION ROLE",
7701 GranteesType::None => "",
7702 };
7703 f.write_str(keyword)?;
7704 if let Some(name) = &self.name {
7705 if !keyword.is_empty() {
7706 f.write_str(" ")?;
7707 }
7708 name.fmt(f)?;
7709 }
7710 Ok(())
7711 }
7712}
7713
7714#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7715#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7716#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7717pub enum GranteesType {
7719 Role,
7721 Share,
7723 User,
7725 Group,
7727 Public,
7729 DatabaseRole,
7731 Application,
7733 ApplicationRole,
7735 None,
7737}
7738
7739#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7741#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7742#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7743pub enum GranteeName {
7744 ObjectName(ObjectName),
7746 UserHost {
7748 user: Ident,
7750 host: Ident,
7752 },
7753}
7754
7755impl fmt::Display for GranteeName {
7756 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7757 match self {
7758 GranteeName::ObjectName(name) => name.fmt(f),
7759 GranteeName::UserHost { user, host } => {
7760 write!(f, "{user}@{host}")
7761 }
7762 }
7763 }
7764}
7765
7766#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7768#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7769#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7770pub enum GrantObjects {
7771 AllSequencesInSchema {
7773 schemas: Vec<ObjectName>,
7775 },
7776 AllTablesInSchema {
7778 schemas: Vec<ObjectName>,
7780 },
7781 AllViewsInSchema {
7783 schemas: Vec<ObjectName>,
7785 },
7786 AllMaterializedViewsInSchema {
7788 schemas: Vec<ObjectName>,
7790 },
7791 AllExternalTablesInSchema {
7793 schemas: Vec<ObjectName>,
7795 },
7796 AllFunctionsInSchema {
7798 schemas: Vec<ObjectName>,
7800 },
7801 AllProceduresInSchema {
7803 schemas: Vec<ObjectName>,
7805 },
7806 AllRoutinesInSchema {
7808 schemas: Vec<ObjectName>,
7810 },
7811 FutureSchemasInDatabase {
7813 databases: Vec<ObjectName>,
7815 },
7816 FutureTablesInSchema {
7818 schemas: Vec<ObjectName>,
7820 },
7821 FutureViewsInSchema {
7823 schemas: Vec<ObjectName>,
7825 },
7826 FutureExternalTablesInSchema {
7828 schemas: Vec<ObjectName>,
7830 },
7831 FutureMaterializedViewsInSchema {
7833 schemas: Vec<ObjectName>,
7835 },
7836 FutureSequencesInSchema {
7838 schemas: Vec<ObjectName>,
7840 },
7841 Databases(Vec<ObjectName>),
7843 Schemas(Vec<ObjectName>),
7845 Sequences(Vec<ObjectName>),
7847 Tables(Vec<ObjectName>),
7849 Views(Vec<ObjectName>),
7851 Warehouses(Vec<ObjectName>),
7853 Integrations(Vec<ObjectName>),
7855 ResourceMonitors(Vec<ObjectName>),
7857 Users(Vec<ObjectName>),
7859 ComputePools(Vec<ObjectName>),
7861 Connections(Vec<ObjectName>),
7863 FailoverGroup(Vec<ObjectName>),
7865 ReplicationGroup(Vec<ObjectName>),
7867 ExternalVolumes(Vec<ObjectName>),
7869 Procedures(Vec<FunctionDesc>),
7874 Functions(Vec<FunctionDesc>),
7879 Routines(Vec<FunctionDesc>),
7886}
7887
7888impl fmt::Display for GrantObjects {
7889 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7890 match self {
7891 GrantObjects::Sequences(sequences) => {
7892 write!(f, "SEQUENCE {}", display_comma_separated(sequences))
7893 }
7894 GrantObjects::Databases(databases) => {
7895 write!(f, "DATABASE {}", display_comma_separated(databases))
7896 }
7897 GrantObjects::Schemas(schemas) => {
7898 write!(f, "SCHEMA {}", display_comma_separated(schemas))
7899 }
7900 GrantObjects::Tables(tables) => {
7901 write!(f, "{}", display_comma_separated(tables))
7902 }
7903 GrantObjects::Views(views) => {
7904 write!(f, "VIEW {}", display_comma_separated(views))
7905 }
7906 GrantObjects::Warehouses(warehouses) => {
7907 write!(f, "WAREHOUSE {}", display_comma_separated(warehouses))
7908 }
7909 GrantObjects::Integrations(integrations) => {
7910 write!(f, "INTEGRATION {}", display_comma_separated(integrations))
7911 }
7912 GrantObjects::AllSequencesInSchema { schemas } => {
7913 write!(
7914 f,
7915 "ALL SEQUENCES IN SCHEMA {}",
7916 display_comma_separated(schemas)
7917 )
7918 }
7919 GrantObjects::AllTablesInSchema { schemas } => {
7920 write!(
7921 f,
7922 "ALL TABLES IN SCHEMA {}",
7923 display_comma_separated(schemas)
7924 )
7925 }
7926 GrantObjects::AllExternalTablesInSchema { schemas } => {
7927 write!(
7928 f,
7929 "ALL EXTERNAL TABLES IN SCHEMA {}",
7930 display_comma_separated(schemas)
7931 )
7932 }
7933 GrantObjects::AllViewsInSchema { schemas } => {
7934 write!(
7935 f,
7936 "ALL VIEWS IN SCHEMA {}",
7937 display_comma_separated(schemas)
7938 )
7939 }
7940 GrantObjects::AllMaterializedViewsInSchema { schemas } => {
7941 write!(
7942 f,
7943 "ALL MATERIALIZED VIEWS IN SCHEMA {}",
7944 display_comma_separated(schemas)
7945 )
7946 }
7947 GrantObjects::AllFunctionsInSchema { schemas } => {
7948 write!(
7949 f,
7950 "ALL FUNCTIONS IN SCHEMA {}",
7951 display_comma_separated(schemas)
7952 )
7953 }
7954 GrantObjects::AllProceduresInSchema { schemas } => {
7955 write!(
7956 f,
7957 "ALL PROCEDURES IN SCHEMA {}",
7958 display_comma_separated(schemas)
7959 )
7960 }
7961 GrantObjects::AllRoutinesInSchema { schemas } => {
7962 write!(
7963 f,
7964 "ALL ROUTINES IN SCHEMA {}",
7965 display_comma_separated(schemas)
7966 )
7967 }
7968 GrantObjects::FutureSchemasInDatabase { databases } => {
7969 write!(
7970 f,
7971 "FUTURE SCHEMAS IN DATABASE {}",
7972 display_comma_separated(databases)
7973 )
7974 }
7975 GrantObjects::FutureTablesInSchema { schemas } => {
7976 write!(
7977 f,
7978 "FUTURE TABLES IN SCHEMA {}",
7979 display_comma_separated(schemas)
7980 )
7981 }
7982 GrantObjects::FutureExternalTablesInSchema { schemas } => {
7983 write!(
7984 f,
7985 "FUTURE EXTERNAL TABLES IN SCHEMA {}",
7986 display_comma_separated(schemas)
7987 )
7988 }
7989 GrantObjects::FutureViewsInSchema { schemas } => {
7990 write!(
7991 f,
7992 "FUTURE VIEWS IN SCHEMA {}",
7993 display_comma_separated(schemas)
7994 )
7995 }
7996 GrantObjects::FutureMaterializedViewsInSchema { schemas } => {
7997 write!(
7998 f,
7999 "FUTURE MATERIALIZED VIEWS IN SCHEMA {}",
8000 display_comma_separated(schemas)
8001 )
8002 }
8003 GrantObjects::FutureSequencesInSchema { schemas } => {
8004 write!(
8005 f,
8006 "FUTURE SEQUENCES IN SCHEMA {}",
8007 display_comma_separated(schemas)
8008 )
8009 }
8010 GrantObjects::ResourceMonitors(objects) => {
8011 write!(f, "RESOURCE MONITOR {}", display_comma_separated(objects))
8012 }
8013 GrantObjects::Users(objects) => {
8014 write!(f, "USER {}", display_comma_separated(objects))
8015 }
8016 GrantObjects::ComputePools(objects) => {
8017 write!(f, "COMPUTE POOL {}", display_comma_separated(objects))
8018 }
8019 GrantObjects::Connections(objects) => {
8020 write!(f, "CONNECTION {}", display_comma_separated(objects))
8021 }
8022 GrantObjects::FailoverGroup(objects) => {
8023 write!(f, "FAILOVER GROUP {}", display_comma_separated(objects))
8024 }
8025 GrantObjects::ReplicationGroup(objects) => {
8026 write!(f, "REPLICATION GROUP {}", display_comma_separated(objects))
8027 }
8028 GrantObjects::ExternalVolumes(objects) => {
8029 write!(f, "EXTERNAL VOLUME {}", display_comma_separated(objects))
8030 }
8031 GrantObjects::Procedures(procedures) => {
8032 write!(f, "PROCEDURE {}", display_comma_separated(procedures))
8033 }
8034 GrantObjects::Functions(functions) => {
8035 write!(f, "FUNCTION {}", display_comma_separated(functions))
8036 }
8037 GrantObjects::Routines(routines) => {
8038 write!(f, "ROUTINE {}", display_comma_separated(routines))
8039 }
8040 }
8041 }
8042}
8043
8044#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8048#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8049#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8050pub struct DenyStatement {
8051 pub privileges: Privileges,
8053 pub objects: GrantObjects,
8055 pub grantees: Vec<Grantee>,
8057 pub granted_by: Option<Ident>,
8059 pub cascade: Option<CascadeOption>,
8061}
8062
8063impl fmt::Display for DenyStatement {
8064 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8065 write!(f, "DENY {}", self.privileges)?;
8066 write!(f, " ON {}", self.objects)?;
8067 if !self.grantees.is_empty() {
8068 write!(f, " TO {}", display_comma_separated(&self.grantees))?;
8069 }
8070 if let Some(cascade) = &self.cascade {
8071 write!(f, " {cascade}")?;
8072 }
8073 if let Some(granted_by) = &self.granted_by {
8074 write!(f, " AS {granted_by}")?;
8075 }
8076 Ok(())
8077 }
8078}
8079
8080#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8082#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8083#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8084pub struct Assignment {
8085 pub target: AssignmentTarget,
8087 pub value: Expr,
8089}
8090
8091impl fmt::Display for Assignment {
8092 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8093 write!(f, "{} = {}", self.target, self.value)
8094 }
8095}
8096
8097#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8101#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8102#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8103pub enum AssignmentTarget {
8104 ColumnName(ObjectName),
8106 Tuple(Vec<ObjectName>),
8108}
8109
8110impl fmt::Display for AssignmentTarget {
8111 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8112 match self {
8113 AssignmentTarget::ColumnName(column) => write!(f, "{column}"),
8114 AssignmentTarget::Tuple(columns) => write!(f, "({})", display_comma_separated(columns)),
8115 }
8116 }
8117}
8118
8119#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8120#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8121#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8122pub enum FunctionArgExpr {
8124 Expr(Expr),
8126 QualifiedWildcard(ObjectName),
8128 Wildcard,
8130 WildcardWithOptions(WildcardAdditionalOptions),
8134}
8135
8136impl From<Expr> for FunctionArgExpr {
8137 fn from(wildcard_expr: Expr) -> Self {
8138 match wildcard_expr {
8139 Expr::QualifiedWildcard(prefix, _) => Self::QualifiedWildcard(prefix),
8140 Expr::Wildcard(_) => Self::Wildcard,
8141 expr => Self::Expr(expr),
8142 }
8143 }
8144}
8145
8146impl fmt::Display for FunctionArgExpr {
8147 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8148 match self {
8149 FunctionArgExpr::Expr(expr) => write!(f, "{expr}"),
8150 FunctionArgExpr::QualifiedWildcard(prefix) => write!(f, "{prefix}.*"),
8151 FunctionArgExpr::Wildcard => f.write_str("*"),
8152 FunctionArgExpr::WildcardWithOptions(opts) => write!(f, "*{opts}"),
8153 }
8154 }
8155}
8156
8157#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8158#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8159#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8160pub enum FunctionArgOperator {
8162 Equals,
8164 RightArrow,
8166 Assignment,
8168 Colon,
8170 Value,
8172 Space,
8177}
8178
8179impl fmt::Display for FunctionArgOperator {
8180 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8181 match self {
8182 FunctionArgOperator::Equals => f.write_str("="),
8183 FunctionArgOperator::RightArrow => f.write_str("=>"),
8184 FunctionArgOperator::Assignment => f.write_str(":="),
8185 FunctionArgOperator::Colon => f.write_str(":"),
8186 FunctionArgOperator::Value => f.write_str("VALUE"),
8187 FunctionArgOperator::Space => Ok(()),
8188 }
8189 }
8190}
8191
8192#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8193#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8194#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8195pub enum FunctionArg {
8197 Named {
8201 name: Ident,
8203 arg: FunctionArgExpr,
8205 operator: FunctionArgOperator,
8207 },
8208 ExprNamed {
8212 name: Expr,
8214 arg: FunctionArgExpr,
8216 operator: FunctionArgOperator,
8218 },
8219 Unnamed(FunctionArgExpr),
8221}
8222
8223impl fmt::Display for FunctionArg {
8224 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8225 match self {
8226 FunctionArg::Named {
8227 name,
8228 arg,
8229 operator,
8230 } => fmt_named_function_arg(f, name, operator, arg),
8231 FunctionArg::ExprNamed {
8232 name,
8233 arg,
8234 operator,
8235 } => fmt_named_function_arg(f, name, operator, arg),
8236 FunctionArg::Unnamed(unnamed_arg) => write!(f, "{unnamed_arg}"),
8237 }
8238 }
8239}
8240
8241fn starts_with_operator_char(expr: &Expr) -> bool {
8245 first_char(expr).is_some_and(|c| OPERATOR_CHARS.contains(c))
8246}
8247
8248fn fmt_named_function_arg(
8251 f: &mut fmt::Formatter,
8252 name: &impl fmt::Display,
8253 operator: &FunctionArgOperator,
8254 arg: &FunctionArgExpr,
8255) -> fmt::Result {
8256 match operator {
8257 FunctionArgOperator::Space => write!(f, "{name} {arg}"),
8258 _ => write!(f, "{name} {operator} {arg}"),
8259 }
8260}
8261
8262#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8263#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8264#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8265pub enum CloseCursor {
8267 All,
8269 Specific {
8271 name: Ident,
8273 },
8274}
8275
8276impl fmt::Display for CloseCursor {
8277 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8278 match self {
8279 CloseCursor::All => write!(f, "ALL"),
8280 CloseCursor::Specific { name } => write!(f, "{name}"),
8281 }
8282 }
8283}
8284
8285#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8287#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8288#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8289pub struct DropDomain {
8290 pub if_exists: bool,
8292 pub name: ObjectName,
8294 pub drop_behavior: Option<DropBehavior>,
8296}
8297
8298#[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 TypedString {
8305 pub data_type: DataType,
8307 pub value: ValueWithSpan,
8310 pub uses_odbc_syntax: bool,
8321}
8322
8323impl fmt::Display for TypedString {
8324 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8325 let data_type = &self.data_type;
8326 let value = &self.value;
8327 match self.uses_odbc_syntax {
8328 false => {
8329 write!(f, "{data_type}")?;
8330 write!(f, " {value}")
8331 }
8332 true => {
8333 let prefix = match data_type {
8334 DataType::Date => "d",
8335 DataType::Time(..) => "t",
8336 DataType::Timestamp(..) => "ts",
8337 _ => "?",
8338 };
8339 write!(f, "{{{prefix} {value}}}")
8340 }
8341 }
8342 }
8343}
8344
8345#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8347#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8348#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8349pub struct Function {
8350 pub name: ObjectName,
8352 pub uses_odbc_syntax: bool,
8361 pub parameters: FunctionArguments,
8371 pub args: FunctionArguments,
8374 pub within_group: Vec<OrderByExpr>,
8382 pub filter: Option<Box<Expr>>,
8384 pub null_treatment: Option<NullTreatment>,
8393 pub over: Option<WindowType>,
8395}
8396
8397impl fmt::Display for Function {
8398 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8399 if self.uses_odbc_syntax {
8400 write!(f, "{{fn ")?;
8401 }
8402
8403 write!(f, "{}{}{}", self.name, self.parameters, self.args)?;
8404
8405 if !self.within_group.is_empty() {
8406 write!(
8407 f,
8408 " WITHIN GROUP (ORDER BY {})",
8409 display_comma_separated(&self.within_group)
8410 )?;
8411 }
8412
8413 if let Some(filter_cond) = &self.filter {
8414 write!(f, " FILTER (WHERE {filter_cond})")?;
8415 }
8416
8417 if let Some(null_treatment) = &self.null_treatment {
8418 write!(f, " {null_treatment}")?;
8419 }
8420
8421 if let Some(o) = &self.over {
8422 f.write_str(" OVER ")?;
8423 o.fmt(f)?;
8424 }
8425
8426 if self.uses_odbc_syntax {
8427 write!(f, "}}")?;
8428 }
8429
8430 Ok(())
8431 }
8432}
8433
8434#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8436#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8437#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8438pub enum FunctionArguments {
8439 None,
8442 Subquery(Box<Query>),
8445 List(FunctionArgumentList),
8448}
8449
8450impl fmt::Display for FunctionArguments {
8451 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8452 match self {
8453 FunctionArguments::None => Ok(()),
8454 FunctionArguments::Subquery(query) => write!(f, "({query})"),
8455 FunctionArguments::List(args) => write!(f, "({args})"),
8456 }
8457 }
8458}
8459
8460#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8462#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8463#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8464pub struct FunctionArgumentList {
8465 pub duplicate_treatment: Option<DuplicateTreatment>,
8467 pub args: Vec<FunctionArg>,
8469 pub clauses: Vec<FunctionArgumentClause>,
8471}
8472
8473impl fmt::Display for FunctionArgumentList {
8474 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8475 if let Some(duplicate_treatment) = self.duplicate_treatment {
8476 write!(f, "{duplicate_treatment} ")?;
8477 }
8478 write!(f, "{}", display_comma_separated(&self.args))?;
8479 if !self.clauses.is_empty() {
8480 if !self.args.is_empty() {
8481 write!(f, " ")?;
8482 }
8483 write!(f, "{}", display_separated(&self.clauses, " "))?;
8484 }
8485 Ok(())
8486 }
8487}
8488
8489#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8490#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8491#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8492pub enum FunctionArgumentClause {
8494 IgnoreOrRespectNulls(NullTreatment),
8503 Where(Expr),
8510 OrderBy(Vec<OrderByExpr>),
8514 Limit(Expr),
8516 OnOverflow(ListAggOnOverflow),
8520 Having(HavingBound),
8529 Separator(ValueWithSpan),
8533 JsonNullClause(JsonNullClause),
8539 JsonReturningClause(JsonReturningClause),
8543}
8544
8545impl fmt::Display for FunctionArgumentClause {
8546 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8547 match self {
8548 FunctionArgumentClause::IgnoreOrRespectNulls(null_treatment) => {
8549 write!(f, "{null_treatment}")
8550 }
8551 FunctionArgumentClause::Where(expr) => write!(f, "WHERE {expr}"),
8552 FunctionArgumentClause::OrderBy(order_by) => {
8553 write!(f, "ORDER BY {}", display_comma_separated(order_by))
8554 }
8555 FunctionArgumentClause::Limit(limit) => write!(f, "LIMIT {limit}"),
8556 FunctionArgumentClause::OnOverflow(on_overflow) => write!(f, "{on_overflow}"),
8557 FunctionArgumentClause::Having(bound) => write!(f, "{bound}"),
8558 FunctionArgumentClause::Separator(sep) => write!(f, "SEPARATOR {sep}"),
8559 FunctionArgumentClause::JsonNullClause(null_clause) => write!(f, "{null_clause}"),
8560 FunctionArgumentClause::JsonReturningClause(returning_clause) => {
8561 write!(f, "{returning_clause}")
8562 }
8563 }
8564 }
8565}
8566
8567#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8569#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8570#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8571pub struct Method {
8572 pub expr: Box<Expr>,
8574 pub method_chain: Vec<Function>,
8577}
8578
8579impl fmt::Display for Method {
8580 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8581 write!(
8582 f,
8583 "{}.{}",
8584 self.expr,
8585 display_separated(&self.method_chain, ".")
8586 )
8587 }
8588}
8589
8590#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8591#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8592#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8593pub enum DuplicateTreatment {
8595 Distinct,
8597 All,
8599}
8600
8601impl fmt::Display for DuplicateTreatment {
8602 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8603 match self {
8604 DuplicateTreatment::Distinct => write!(f, "DISTINCT"),
8605 DuplicateTreatment::All => write!(f, "ALL"),
8606 }
8607 }
8608}
8609
8610#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8611#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8612#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8613pub enum AnalyzeFormatKind {
8615 Keyword(AnalyzeFormat),
8617 Assignment(AnalyzeFormat),
8619}
8620
8621impl fmt::Display for AnalyzeFormatKind {
8622 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
8623 match self {
8624 AnalyzeFormatKind::Keyword(format) => write!(f, "FORMAT {format}"),
8625 AnalyzeFormatKind::Assignment(format) => write!(f, "FORMAT={format}"),
8626 }
8627 }
8628}
8629
8630#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8631#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8632#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8633pub enum AnalyzeFormat {
8635 TEXT,
8637 GRAPHVIZ,
8639 JSON,
8641 TRADITIONAL,
8643 TREE,
8645}
8646
8647#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
8649#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8650#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8651pub enum JsonPredicateType {
8652 Value,
8654 Scalar,
8656 Array,
8658 Object,
8660}
8661
8662impl fmt::Display for JsonPredicateType {
8663 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8664 match self {
8665 JsonPredicateType::Value => write!(f, "VALUE"),
8666 JsonPredicateType::Scalar => write!(f, "SCALAR"),
8667 JsonPredicateType::Array => write!(f, "ARRAY"),
8668 JsonPredicateType::Object => write!(f, "OBJECT"),
8669 }
8670 }
8671}
8672
8673#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
8675#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8676#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8677pub enum JsonKeyUniqueness {
8678 WithUniqueKeys,
8680 WithoutUniqueKeys,
8682}
8683
8684impl fmt::Display for JsonKeyUniqueness {
8685 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8686 match self {
8687 JsonKeyUniqueness::WithUniqueKeys => write!(f, "WITH UNIQUE KEYS"),
8688 JsonKeyUniqueness::WithoutUniqueKeys => write!(f, "WITHOUT UNIQUE KEYS"),
8689 }
8690 }
8691}
8692
8693impl fmt::Display for AnalyzeFormat {
8694 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
8695 f.write_str(match self {
8696 AnalyzeFormat::TEXT => "TEXT",
8697 AnalyzeFormat::GRAPHVIZ => "GRAPHVIZ",
8698 AnalyzeFormat::JSON => "JSON",
8699 AnalyzeFormat::TRADITIONAL => "TRADITIONAL",
8700 AnalyzeFormat::TREE => "TREE",
8701 })
8702 }
8703}
8704
8705#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8707#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8708#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8709pub enum FileFormat {
8710 TEXTFILE,
8712 SEQUENCEFILE,
8714 ORC,
8716 PARQUET,
8718 AVRO,
8720 RCFILE,
8722 JSONFILE,
8724}
8725
8726impl fmt::Display for FileFormat {
8727 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8728 use self::FileFormat::*;
8729 f.write_str(match self {
8730 TEXTFILE => "TEXTFILE",
8731 SEQUENCEFILE => "SEQUENCEFILE",
8732 ORC => "ORC",
8733 PARQUET => "PARQUET",
8734 AVRO => "AVRO",
8735 RCFILE => "RCFILE",
8736 JSONFILE => "JSONFILE",
8737 })
8738 }
8739}
8740
8741#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8743#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8744#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8745pub enum ListAggOnOverflow {
8746 Error,
8748
8749 Truncate {
8751 filler: Option<Box<Expr>>,
8753 with_count: bool,
8755 },
8756}
8757
8758impl fmt::Display for ListAggOnOverflow {
8759 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8760 write!(f, "ON OVERFLOW")?;
8761 match self {
8762 ListAggOnOverflow::Error => write!(f, " ERROR"),
8763 ListAggOnOverflow::Truncate { filler, with_count } => {
8764 write!(f, " TRUNCATE")?;
8765 if let Some(filler) = filler {
8766 write!(f, " {filler}")?;
8767 }
8768 if *with_count {
8769 write!(f, " WITH")?;
8770 } else {
8771 write!(f, " WITHOUT")?;
8772 }
8773 write!(f, " COUNT")
8774 }
8775 }
8776 }
8777}
8778
8779#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8781#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8782#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8783pub struct HavingBound(pub HavingBoundKind, pub Expr);
8784
8785impl fmt::Display for HavingBound {
8786 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8787 write!(f, "HAVING {} {}", self.0, self.1)
8788 }
8789}
8790
8791#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8792#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8793#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8794pub enum HavingBoundKind {
8796 Min,
8798 Max,
8800}
8801
8802impl fmt::Display for HavingBoundKind {
8803 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8804 match self {
8805 HavingBoundKind::Min => write!(f, "MIN"),
8806 HavingBoundKind::Max => write!(f, "MAX"),
8807 }
8808 }
8809}
8810
8811#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8812#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8813#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8814pub enum ObjectType {
8816 Collation,
8818 Table,
8820 ForeignTable,
8822 View,
8824 MaterializedView,
8826 Index,
8828 Schema,
8830 Database,
8832 Role,
8834 Group,
8836 Sequence,
8838 Stage,
8840 Type,
8842 User,
8844 Stream,
8846 Warehouse,
8848}
8849
8850impl fmt::Display for ObjectType {
8851 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8852 f.write_str(match self {
8853 ObjectType::Collation => "COLLATION",
8854 ObjectType::Table => "TABLE",
8855 ObjectType::ForeignTable => "FOREIGN TABLE",
8856 ObjectType::View => "VIEW",
8857 ObjectType::MaterializedView => "MATERIALIZED VIEW",
8858 ObjectType::Index => "INDEX",
8859 ObjectType::Schema => "SCHEMA",
8860 ObjectType::Database => "DATABASE",
8861 ObjectType::Role => "ROLE",
8862 ObjectType::Group => "GROUP",
8863 ObjectType::Sequence => "SEQUENCE",
8864 ObjectType::Stage => "STAGE",
8865 ObjectType::Type => "TYPE",
8866 ObjectType::User => "USER",
8867 ObjectType::Stream => "STREAM",
8868 ObjectType::Warehouse => "WAREHOUSE",
8869 })
8870 }
8871}
8872
8873#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8874#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8875#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8876pub enum KillType {
8878 Connection,
8880 Query,
8882 Mutation,
8884}
8885
8886impl fmt::Display for KillType {
8887 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8888 f.write_str(match self {
8889 KillType::Connection => "CONNECTION",
8891 KillType::Query => "QUERY",
8892 KillType::Mutation => "MUTATION",
8894 })
8895 }
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 enum HiveDistributionStyle {
8903 PARTITIONED {
8905 columns: Vec<ColumnDef>,
8907 },
8908 SKEWED {
8910 columns: Vec<ColumnDef>,
8912 on: Vec<ColumnDef>,
8914 stored_as_directories: bool,
8916 },
8917 NONE,
8919}
8920
8921#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8922#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8923#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8924pub enum HiveRowFormat {
8926 SERDE {
8928 class: String,
8930 },
8931 DELIMITED {
8933 delimiters: Vec<HiveRowDelimiter>,
8935 },
8936}
8937
8938#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8939#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8940#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8941pub struct HiveLoadDataFormat {
8943 pub serde: Expr,
8945 pub input_format: Expr,
8947}
8948
8949#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8950#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8951#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8952pub struct HiveRowDelimiter {
8954 pub delimiter: HiveDelimiter,
8956 pub char: Ident,
8958}
8959
8960impl fmt::Display for HiveRowDelimiter {
8961 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8962 write!(f, "{} ", self.delimiter)?;
8963 write!(f, "{}", self.char)
8964 }
8965}
8966
8967#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8968#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8969#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8970pub enum HiveDelimiter {
8972 FieldsTerminatedBy,
8974 FieldsEscapedBy,
8976 CollectionItemsTerminatedBy,
8978 MapKeysTerminatedBy,
8980 LinesTerminatedBy,
8982 NullDefinedAs,
8984}
8985
8986impl fmt::Display for HiveDelimiter {
8987 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8988 use HiveDelimiter::*;
8989 f.write_str(match self {
8990 FieldsTerminatedBy => "FIELDS TERMINATED BY",
8991 FieldsEscapedBy => "ESCAPED BY",
8992 CollectionItemsTerminatedBy => "COLLECTION ITEMS TERMINATED BY",
8993 MapKeysTerminatedBy => "MAP KEYS TERMINATED BY",
8994 LinesTerminatedBy => "LINES TERMINATED BY",
8995 NullDefinedAs => "NULL DEFINED AS",
8996 })
8997 }
8998}
8999
9000#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9001#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9002#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9003pub enum HiveDescribeFormat {
9005 Extended,
9007 Formatted,
9009}
9010
9011impl fmt::Display for HiveDescribeFormat {
9012 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9013 use HiveDescribeFormat::*;
9014 f.write_str(match self {
9015 Extended => "EXTENDED",
9016 Formatted => "FORMATTED",
9017 })
9018 }
9019}
9020
9021#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9022#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9023#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9024pub enum DescribeAlias {
9026 Describe,
9028 Explain,
9030 Desc,
9032}
9033
9034impl fmt::Display for DescribeAlias {
9035 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9036 use DescribeAlias::*;
9037 f.write_str(match self {
9038 Describe => "DESCRIBE",
9039 Explain => "EXPLAIN",
9040 Desc => "DESC",
9041 })
9042 }
9043}
9044
9045#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9046#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9047#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9048pub enum HiveIOFormat {
9050 IOF {
9052 input_format: Expr,
9054 output_format: Expr,
9056 },
9057 FileFormat {
9059 format: FileFormat,
9061 },
9062 Using {
9068 format: Ident,
9070 },
9071}
9072
9073#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Default)]
9074#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9075#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9076pub struct HiveFormat {
9078 pub row_format: Option<HiveRowFormat>,
9080 pub serde_properties: Option<Vec<SqlOption>>,
9082 pub storage: Option<HiveIOFormat>,
9084 pub location: Option<String>,
9086}
9087
9088#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9089#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9090#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9091pub struct ClusteredIndex {
9093 pub name: Ident,
9095 pub asc: Option<bool>,
9097}
9098
9099impl fmt::Display for ClusteredIndex {
9100 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9101 write!(f, "{}", self.name)?;
9102 match self.asc {
9103 Some(true) => write!(f, " ASC"),
9104 Some(false) => write!(f, " DESC"),
9105 _ => Ok(()),
9106 }
9107 }
9108}
9109
9110#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9111#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9112#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9113pub enum TableOptionsClustered {
9115 ColumnstoreIndex,
9117 ColumnstoreIndexOrder(Vec<Ident>),
9119 Index(Vec<ClusteredIndex>),
9121}
9122
9123impl fmt::Display for TableOptionsClustered {
9124 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9125 match self {
9126 TableOptionsClustered::ColumnstoreIndex => {
9127 write!(f, "CLUSTERED COLUMNSTORE INDEX")
9128 }
9129 TableOptionsClustered::ColumnstoreIndexOrder(values) => {
9130 write!(
9131 f,
9132 "CLUSTERED COLUMNSTORE INDEX ORDER ({})",
9133 display_comma_separated(values)
9134 )
9135 }
9136 TableOptionsClustered::Index(values) => {
9137 write!(f, "CLUSTERED INDEX ({})", display_comma_separated(values))
9138 }
9139 }
9140 }
9141}
9142
9143#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
9145#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9146#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9147pub enum PartitionRangeDirection {
9148 Left,
9150 Right,
9152}
9153
9154#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9155#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9156#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9157pub enum SqlOption {
9159 Clustered(TableOptionsClustered),
9163 Ident(ObjectName),
9168 KeyValue {
9173 key: ObjectName,
9175 value: Expr,
9177 },
9178 Partition {
9185 column_name: Ident,
9187 range_direction: Option<PartitionRangeDirection>,
9189 for_values: Vec<Expr>,
9191 },
9192 Comment(CommentDef),
9194 TableSpace(TablespaceOption),
9197 NamedParenthesizedList(NamedParenthesizedList),
9204}
9205
9206impl fmt::Display for SqlOption {
9207 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9208 match self {
9209 SqlOption::Clustered(c) => write!(f, "{c}"),
9210 SqlOption::Ident(ident) => {
9211 write!(f, "{ident}")
9212 }
9213 SqlOption::KeyValue { key: name, value } => {
9214 write!(f, "{name} = {value}")
9215 }
9216 SqlOption::Partition {
9217 column_name,
9218 range_direction,
9219 for_values,
9220 } => {
9221 let direction = match range_direction {
9222 Some(PartitionRangeDirection::Left) => " LEFT",
9223 Some(PartitionRangeDirection::Right) => " RIGHT",
9224 None => "",
9225 };
9226
9227 write!(
9228 f,
9229 "PARTITION ({} RANGE{} FOR VALUES ({}))",
9230 column_name,
9231 direction,
9232 display_comma_separated(for_values)
9233 )
9234 }
9235 SqlOption::TableSpace(tablespace_option) => {
9236 write!(f, "TABLESPACE {}", tablespace_option.name)?;
9237 match tablespace_option.storage {
9238 Some(StorageType::Disk) => write!(f, " STORAGE DISK"),
9239 Some(StorageType::Memory) => write!(f, " STORAGE MEMORY"),
9240 None => Ok(()),
9241 }
9242 }
9243 SqlOption::Comment(comment) => match comment {
9244 CommentDef::WithEq(comment) => {
9245 write!(f, "COMMENT = '{comment}'")
9246 }
9247 CommentDef::WithoutEq(comment) => {
9248 write!(f, "COMMENT '{comment}'")
9249 }
9250 },
9251 SqlOption::NamedParenthesizedList(value) => {
9252 write!(f, "{} = ", value.key)?;
9253 if let Some(key) = &value.name {
9254 write!(f, "{key}")?;
9255 }
9256 if !value.values.is_empty() {
9257 write!(f, "({})", display_comma_separated(&value.values))?
9258 }
9259 Ok(())
9260 }
9261 }
9262 }
9263}
9264
9265#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
9266#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9267#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9268pub enum StorageType {
9270 Disk,
9272 Memory,
9274}
9275
9276#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
9277#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9278#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9279pub struct TablespaceOption {
9282 pub name: String,
9284 pub storage: Option<StorageType>,
9286}
9287
9288#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9289#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9290#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9291pub struct SecretOption {
9293 pub key: Ident,
9295 pub value: Ident,
9297}
9298
9299impl fmt::Display for SecretOption {
9300 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9301 write!(f, "{} {}", self.key, self.value)
9302 }
9303}
9304
9305#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9309#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9310#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9311pub struct CreateServerStatement {
9312 pub name: ObjectName,
9314 pub if_not_exists: bool,
9316 pub server_type: Option<Ident>,
9318 pub version: Option<Ident>,
9320 pub foreign_data_wrapper: ObjectName,
9322 pub options: Option<Vec<CreateServerOption>>,
9324}
9325
9326impl fmt::Display for CreateServerStatement {
9327 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
9328 let CreateServerStatement {
9329 name,
9330 if_not_exists,
9331 server_type,
9332 version,
9333 foreign_data_wrapper,
9334 options,
9335 } = self;
9336
9337 write!(
9338 f,
9339 "CREATE SERVER {if_not_exists}{name} ",
9340 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
9341 )?;
9342
9343 if let Some(st) = server_type {
9344 write!(f, "TYPE {st} ")?;
9345 }
9346
9347 if let Some(v) = version {
9348 write!(f, "VERSION {v} ")?;
9349 }
9350
9351 write!(f, "FOREIGN DATA WRAPPER {foreign_data_wrapper}")?;
9352
9353 if let Some(o) = options {
9354 write!(f, " OPTIONS ({o})", o = display_comma_separated(o))?;
9355 }
9356
9357 Ok(())
9358 }
9359}
9360
9361#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9363#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9364#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9365pub struct CreateServerOption {
9366 pub key: Ident,
9368 pub value: Ident,
9370}
9371
9372impl fmt::Display for CreateServerOption {
9373 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9374 write!(f, "{} {}", self.key, self.value)
9375 }
9376}
9377
9378#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9379#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9380#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9381pub enum AttachDuckDBDatabaseOption {
9383 ReadOnly(Option<bool>),
9385 Type(Ident),
9387}
9388
9389impl fmt::Display for AttachDuckDBDatabaseOption {
9390 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9391 match self {
9392 AttachDuckDBDatabaseOption::ReadOnly(Some(true)) => write!(f, "READ_ONLY true"),
9393 AttachDuckDBDatabaseOption::ReadOnly(Some(false)) => write!(f, "READ_ONLY false"),
9394 AttachDuckDBDatabaseOption::ReadOnly(None) => write!(f, "READ_ONLY"),
9395 AttachDuckDBDatabaseOption::Type(t) => write!(f, "TYPE {t}"),
9396 }
9397 }
9398}
9399
9400#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9401#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9402#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9403pub enum TransactionMode {
9405 AccessMode(TransactionAccessMode),
9407 IsolationLevel(TransactionIsolationLevel),
9409}
9410
9411impl fmt::Display for TransactionMode {
9412 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9413 use TransactionMode::*;
9414 match self {
9415 AccessMode(access_mode) => write!(f, "{access_mode}"),
9416 IsolationLevel(iso_level) => write!(f, "ISOLATION LEVEL {iso_level}"),
9417 }
9418 }
9419}
9420
9421#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9422#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9423#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9424pub enum TransactionAccessMode {
9426 ReadOnly,
9428 ReadWrite,
9430}
9431
9432impl fmt::Display for TransactionAccessMode {
9433 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9434 use TransactionAccessMode::*;
9435 f.write_str(match self {
9436 ReadOnly => "READ ONLY",
9437 ReadWrite => "READ WRITE",
9438 })
9439 }
9440}
9441
9442#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9443#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9444#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9445pub enum TransactionIsolationLevel {
9447 ReadUncommitted,
9449 ReadCommitted,
9451 RepeatableRead,
9453 Serializable,
9455 Snapshot,
9457}
9458
9459impl fmt::Display for TransactionIsolationLevel {
9460 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9461 use TransactionIsolationLevel::*;
9462 f.write_str(match self {
9463 ReadUncommitted => "READ UNCOMMITTED",
9464 ReadCommitted => "READ COMMITTED",
9465 RepeatableRead => "REPEATABLE READ",
9466 Serializable => "SERIALIZABLE",
9467 Snapshot => "SNAPSHOT",
9468 })
9469 }
9470}
9471
9472#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9477#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9478#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9479pub enum TransactionModifier {
9480 Deferred,
9482 Immediate,
9484 Exclusive,
9486 Try,
9488 Catch,
9490}
9491
9492impl fmt::Display for TransactionModifier {
9493 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9494 use TransactionModifier::*;
9495 f.write_str(match self {
9496 Deferred => "DEFERRED",
9497 Immediate => "IMMEDIATE",
9498 Exclusive => "EXCLUSIVE",
9499 Try => "TRY",
9500 Catch => "CATCH",
9501 })
9502 }
9503}
9504
9505#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9506#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9507#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9508pub enum ShowStatementFilter {
9510 Like(String),
9512 ILike(String),
9514 Where(Expr),
9516 NoKeyword(String),
9518}
9519
9520impl fmt::Display for ShowStatementFilter {
9521 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9522 use ShowStatementFilter::*;
9523 match self {
9524 Like(pattern) => write!(f, "LIKE '{}'", value::escape_single_quote_string(pattern)),
9525 ILike(pattern) => write!(f, "ILIKE {}", value::escape_single_quote_string(pattern)),
9526 Where(expr) => write!(f, "WHERE {expr}"),
9527 NoKeyword(pattern) => write!(f, "'{}'", value::escape_single_quote_string(pattern)),
9528 }
9529 }
9530}
9531
9532#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9533#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9534#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9535pub enum ShowStatementInClause {
9537 IN,
9539 FROM,
9541}
9542
9543impl fmt::Display for ShowStatementInClause {
9544 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9545 use ShowStatementInClause::*;
9546 match self {
9547 FROM => write!(f, "FROM"),
9548 IN => write!(f, "IN"),
9549 }
9550 }
9551}
9552
9553#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9558#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9559#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9560pub enum SqliteOnConflict {
9561 Rollback,
9563 Abort,
9565 Fail,
9567 Ignore,
9569 Replace,
9571}
9572
9573impl fmt::Display for SqliteOnConflict {
9574 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9575 use SqliteOnConflict::*;
9576 match self {
9577 Rollback => write!(f, "OR ROLLBACK"),
9578 Abort => write!(f, "OR ABORT"),
9579 Fail => write!(f, "OR FAIL"),
9580 Ignore => write!(f, "OR IGNORE"),
9581 Replace => write!(f, "OR REPLACE"),
9582 }
9583 }
9584}
9585
9586#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9592#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9593#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9594pub enum MysqlInsertPriority {
9595 LowPriority,
9597 Delayed,
9599 HighPriority,
9601}
9602
9603impl fmt::Display for crate::ast::MysqlInsertPriority {
9604 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9605 use MysqlInsertPriority::*;
9606 match self {
9607 LowPriority => write!(f, "LOW_PRIORITY"),
9608 Delayed => write!(f, "DELAYED"),
9609 HighPriority => write!(f, "HIGH_PRIORITY"),
9610 }
9611 }
9612}
9613
9614#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9615#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9616#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9617pub enum CopySource {
9619 Table {
9621 table_name: ObjectName,
9623 columns: Vec<Ident>,
9626 },
9627 Query(Box<Query>),
9629}
9630
9631#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9632#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9633#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9634pub enum CopyTarget {
9636 Stdin,
9638 Stdout,
9640 File {
9642 filename: String,
9644 },
9645 Program {
9647 command: String,
9649 },
9650}
9651
9652impl fmt::Display for CopyTarget {
9653 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9654 use CopyTarget::*;
9655 match self {
9656 Stdin => write!(f, "STDIN"),
9657 Stdout => write!(f, "STDOUT"),
9658 File { filename } => write!(f, "'{}'", value::escape_single_quote_string(filename)),
9659 Program { command } => write!(
9660 f,
9661 "PROGRAM '{}'",
9662 value::escape_single_quote_string(command)
9663 ),
9664 }
9665 }
9666}
9667
9668#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9669#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9670#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9671pub struct CopyPayload {
9674 pub data: String,
9678 pub terminated: bool,
9680}
9681
9682#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9683#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9684#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9685pub enum OnCommit {
9687 DeleteRows,
9689 PreserveRows,
9691 Drop,
9693}
9694
9695#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9699#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9700#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9701pub enum CopyOption {
9702 Format(Ident),
9704 Freeze(bool),
9706 Delimiter(char),
9708 Null(String),
9710 Header(bool),
9712 Quote(char),
9714 Escape(char),
9716 ForceQuote(Vec<Ident>),
9718 ForceNotNull(Vec<Ident>),
9720 ForceNull(Vec<Ident>),
9722 Encoding(String),
9724}
9725
9726impl fmt::Display for CopyOption {
9727 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9728 use CopyOption::*;
9729 match self {
9730 Format(name) => write!(f, "FORMAT {name}"),
9731 Freeze(true) => write!(f, "FREEZE"),
9732 Freeze(false) => write!(f, "FREEZE FALSE"),
9733 Delimiter(char) => write!(f, "DELIMITER '{char}'"),
9734 Null(string) => write!(f, "NULL '{}'", value::escape_single_quote_string(string)),
9735 Header(true) => write!(f, "HEADER"),
9736 Header(false) => write!(f, "HEADER FALSE"),
9737 Quote(char) => write!(f, "QUOTE '{char}'"),
9738 Escape(char) => write!(f, "ESCAPE '{char}'"),
9739 ForceQuote(columns) => write!(f, "FORCE_QUOTE ({})", display_comma_separated(columns)),
9740 ForceNotNull(columns) => {
9741 write!(f, "FORCE_NOT_NULL ({})", display_comma_separated(columns))
9742 }
9743 ForceNull(columns) => write!(f, "FORCE_NULL ({})", display_comma_separated(columns)),
9744 Encoding(name) => write!(f, "ENCODING '{}'", value::escape_single_quote_string(name)),
9745 }
9746 }
9747}
9748
9749#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9754#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9755#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9756pub enum CopyLegacyOption {
9757 AcceptAnyDate,
9759 AcceptInvChars(Option<String>),
9761 AddQuotes,
9763 AllowOverwrite,
9765 Binary,
9767 BlankAsNull,
9769 Bzip2,
9771 CleanPath,
9773 CompUpdate {
9775 preset: bool,
9777 enabled: Option<bool>,
9779 },
9780 Csv(Vec<CopyLegacyCsvOption>),
9782 DateFormat(Option<String>),
9784 Delimiter(char),
9786 EmptyAsNull,
9788 Encrypted {
9790 auto: bool,
9792 },
9793 Escape,
9795 Extension(String),
9797 FixedWidth(String),
9799 Gzip,
9801 Header,
9803 IamRole(IamRoleKind),
9805 IgnoreHeader(u64),
9807 Json(Option<String>),
9809 Manifest {
9811 verbose: bool,
9813 },
9814 MaxFileSize(FileSize),
9816 Null(String),
9818 Parallel(Option<bool>),
9820 Parquet,
9822 PartitionBy(UnloadPartitionBy),
9824 Region(String),
9826 RemoveQuotes,
9828 RowGroupSize(FileSize),
9830 StatUpdate(Option<bool>),
9832 TimeFormat(Option<String>),
9834 TruncateColumns,
9836 Zstd,
9838 Credentials(String),
9841}
9842
9843impl fmt::Display for CopyLegacyOption {
9844 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9845 use CopyLegacyOption::*;
9846 match self {
9847 AcceptAnyDate => write!(f, "ACCEPTANYDATE"),
9848 AcceptInvChars(ch) => {
9849 write!(f, "ACCEPTINVCHARS")?;
9850 if let Some(ch) = ch {
9851 write!(f, " '{}'", value::escape_single_quote_string(ch))?;
9852 }
9853 Ok(())
9854 }
9855 AddQuotes => write!(f, "ADDQUOTES"),
9856 AllowOverwrite => write!(f, "ALLOWOVERWRITE"),
9857 Binary => write!(f, "BINARY"),
9858 BlankAsNull => write!(f, "BLANKSASNULL"),
9859 Bzip2 => write!(f, "BZIP2"),
9860 CleanPath => write!(f, "CLEANPATH"),
9861 CompUpdate { preset, enabled } => {
9862 write!(f, "COMPUPDATE")?;
9863 if *preset {
9864 write!(f, " PRESET")?;
9865 } else if let Some(enabled) = enabled {
9866 write!(
9867 f,
9868 "{}",
9869 match enabled {
9870 true => " TRUE",
9871 false => " FALSE",
9872 }
9873 )?;
9874 }
9875 Ok(())
9876 }
9877 Csv(opts) => {
9878 write!(f, "CSV")?;
9879 if !opts.is_empty() {
9880 write!(f, " {}", display_separated(opts, " "))?;
9881 }
9882 Ok(())
9883 }
9884 DateFormat(fmt) => {
9885 write!(f, "DATEFORMAT")?;
9886 if let Some(fmt) = fmt {
9887 write!(f, " '{}'", value::escape_single_quote_string(fmt))?;
9888 }
9889 Ok(())
9890 }
9891 Delimiter(char) => write!(f, "DELIMITER '{char}'"),
9892 EmptyAsNull => write!(f, "EMPTYASNULL"),
9893 Encrypted { auto } => write!(f, "ENCRYPTED{}", if *auto { " AUTO" } else { "" }),
9894 Escape => write!(f, "ESCAPE"),
9895 Extension(ext) => write!(f, "EXTENSION '{}'", value::escape_single_quote_string(ext)),
9896 FixedWidth(spec) => write!(
9897 f,
9898 "FIXEDWIDTH '{}'",
9899 value::escape_single_quote_string(spec)
9900 ),
9901 Gzip => write!(f, "GZIP"),
9902 Header => write!(f, "HEADER"),
9903 IamRole(role) => write!(f, "IAM_ROLE {role}"),
9904 IgnoreHeader(num_rows) => write!(f, "IGNOREHEADER {num_rows}"),
9905 Json(opt) => {
9906 write!(f, "JSON")?;
9907 if let Some(opt) = opt {
9908 write!(f, " AS '{}'", value::escape_single_quote_string(opt))?;
9909 }
9910 Ok(())
9911 }
9912 Manifest { verbose } => write!(f, "MANIFEST{}", if *verbose { " VERBOSE" } else { "" }),
9913 MaxFileSize(file_size) => write!(f, "MAXFILESIZE {file_size}"),
9914 Null(string) => write!(f, "NULL '{}'", value::escape_single_quote_string(string)),
9915 Parallel(enabled) => {
9916 write!(
9917 f,
9918 "PARALLEL{}",
9919 match enabled {
9920 Some(true) => " TRUE",
9921 Some(false) => " FALSE",
9922 _ => "",
9923 }
9924 )
9925 }
9926 Parquet => write!(f, "PARQUET"),
9927 PartitionBy(p) => write!(f, "{p}"),
9928 Region(region) => write!(f, "REGION '{}'", value::escape_single_quote_string(region)),
9929 RemoveQuotes => write!(f, "REMOVEQUOTES"),
9930 RowGroupSize(file_size) => write!(f, "ROWGROUPSIZE {file_size}"),
9931 StatUpdate(enabled) => {
9932 write!(
9933 f,
9934 "STATUPDATE{}",
9935 match enabled {
9936 Some(true) => " TRUE",
9937 Some(false) => " FALSE",
9938 _ => "",
9939 }
9940 )
9941 }
9942 TimeFormat(fmt) => {
9943 write!(f, "TIMEFORMAT")?;
9944 if let Some(fmt) = fmt {
9945 write!(f, " '{}'", value::escape_single_quote_string(fmt))?;
9946 }
9947 Ok(())
9948 }
9949 TruncateColumns => write!(f, "TRUNCATECOLUMNS"),
9950 Zstd => write!(f, "ZSTD"),
9951 Credentials(s) => write!(f, "CREDENTIALS '{}'", value::escape_single_quote_string(s)),
9952 }
9953 }
9954}
9955
9956#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9960#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9961#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9962pub struct FileSize {
9963 pub size: ValueWithSpan,
9965 pub unit: Option<FileSizeUnit>,
9967}
9968
9969impl fmt::Display for FileSize {
9970 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9971 write!(f, "{}", self.size)?;
9972 if let Some(unit) = &self.unit {
9973 write!(f, " {unit}")?;
9974 }
9975 Ok(())
9976 }
9977}
9978
9979#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9981#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9982#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9983pub enum FileSizeUnit {
9984 MB,
9986 GB,
9988}
9989
9990impl fmt::Display for FileSizeUnit {
9991 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9992 match self {
9993 FileSizeUnit::MB => write!(f, "MB"),
9994 FileSizeUnit::GB => write!(f, "GB"),
9995 }
9996 }
9997}
9998
9999#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10005#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10006#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10007pub struct UnloadPartitionBy {
10008 pub columns: Vec<Ident>,
10010 pub include: bool,
10012}
10013
10014impl fmt::Display for UnloadPartitionBy {
10015 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10016 write!(
10017 f,
10018 "PARTITION BY ({}){}",
10019 display_comma_separated(&self.columns),
10020 if self.include { " INCLUDE" } else { "" }
10021 )
10022 }
10023}
10024
10025#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10029#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10030#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10031pub enum IamRoleKind {
10032 Default,
10034 Arn(String),
10036}
10037
10038impl fmt::Display for IamRoleKind {
10039 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10040 match self {
10041 IamRoleKind::Default => write!(f, "DEFAULT"),
10042 IamRoleKind::Arn(arn) => write!(f, "'{arn}'"),
10043 }
10044 }
10045}
10046
10047#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10051#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10052#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10053pub enum CopyLegacyCsvOption {
10054 Header,
10056 Quote(char),
10058 Escape(char),
10060 ForceQuote(Vec<Ident>),
10062 ForceNotNull(Vec<Ident>),
10064}
10065
10066impl fmt::Display for CopyLegacyCsvOption {
10067 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10068 use CopyLegacyCsvOption::*;
10069 match self {
10070 Header => write!(f, "HEADER"),
10071 Quote(char) => write!(f, "QUOTE '{char}'"),
10072 Escape(char) => write!(f, "ESCAPE '{char}'"),
10073 ForceQuote(columns) => write!(f, "FORCE QUOTE {}", display_comma_separated(columns)),
10074 ForceNotNull(columns) => {
10075 write!(f, "FORCE NOT NULL {}", display_comma_separated(columns))
10076 }
10077 }
10078 }
10079}
10080
10081#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10083#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10084#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10085pub enum DiscardObject {
10086 ALL,
10088 PLANS,
10090 SEQUENCES,
10092 TEMP,
10094}
10095
10096impl fmt::Display for DiscardObject {
10097 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10098 match self {
10099 DiscardObject::ALL => f.write_str("ALL"),
10100 DiscardObject::PLANS => f.write_str("PLANS"),
10101 DiscardObject::SEQUENCES => f.write_str("SEQUENCES"),
10102 DiscardObject::TEMP => f.write_str("TEMP"),
10103 }
10104 }
10105}
10106
10107#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10109#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10110#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10111pub enum FlushType {
10112 BinaryLogs,
10114 EngineLogs,
10116 ErrorLogs,
10118 GeneralLogs,
10120 Hosts,
10122 Logs,
10124 Privileges,
10126 OptimizerCosts,
10128 RelayLogs,
10130 SlowLogs,
10132 Status,
10134 UserResources,
10136 Tables,
10138}
10139
10140impl fmt::Display for FlushType {
10141 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10142 match self {
10143 FlushType::BinaryLogs => f.write_str("BINARY LOGS"),
10144 FlushType::EngineLogs => f.write_str("ENGINE LOGS"),
10145 FlushType::ErrorLogs => f.write_str("ERROR LOGS"),
10146 FlushType::GeneralLogs => f.write_str("GENERAL LOGS"),
10147 FlushType::Hosts => f.write_str("HOSTS"),
10148 FlushType::Logs => f.write_str("LOGS"),
10149 FlushType::Privileges => f.write_str("PRIVILEGES"),
10150 FlushType::OptimizerCosts => f.write_str("OPTIMIZER_COSTS"),
10151 FlushType::RelayLogs => f.write_str("RELAY LOGS"),
10152 FlushType::SlowLogs => f.write_str("SLOW LOGS"),
10153 FlushType::Status => f.write_str("STATUS"),
10154 FlushType::UserResources => f.write_str("USER_RESOURCES"),
10155 FlushType::Tables => f.write_str("TABLES"),
10156 }
10157 }
10158}
10159
10160#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10162#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10163#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10164pub enum FlushLocation {
10165 NoWriteToBinlog,
10167 Local,
10169}
10170
10171impl fmt::Display for FlushLocation {
10172 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10173 match self {
10174 FlushLocation::NoWriteToBinlog => f.write_str("NO_WRITE_TO_BINLOG"),
10175 FlushLocation::Local => f.write_str("LOCAL"),
10176 }
10177 }
10178}
10179
10180#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10182#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10183#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10184pub enum ContextModifier {
10185 Local,
10187 Session,
10189 Global,
10191}
10192
10193impl fmt::Display for ContextModifier {
10194 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10195 match self {
10196 Self::Local => {
10197 write!(f, "LOCAL ")
10198 }
10199 Self::Session => {
10200 write!(f, "SESSION ")
10201 }
10202 Self::Global => {
10203 write!(f, "GLOBAL ")
10204 }
10205 }
10206 }
10207}
10208
10209#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10211#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10212pub enum DropFunctionOption {
10213 Restrict,
10215 Cascade,
10217}
10218
10219impl fmt::Display for DropFunctionOption {
10220 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10221 match self {
10222 DropFunctionOption::Restrict => write!(f, "RESTRICT "),
10223 DropFunctionOption::Cascade => write!(f, "CASCADE "),
10224 }
10225 }
10226}
10227
10228#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10230#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10231#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10232pub struct FunctionDesc {
10233 pub name: ObjectName,
10235 pub args: Option<Vec<OperateFunctionArg>>,
10237}
10238
10239impl fmt::Display for FunctionDesc {
10240 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10241 write!(f, "{}", self.name)?;
10242 if let Some(args) = &self.args {
10243 write!(f, "({})", display_comma_separated(args))?;
10244 }
10245 Ok(())
10246 }
10247}
10248
10249#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10251#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10252#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10253pub struct OperateFunctionArg {
10254 pub mode: Option<ArgMode>,
10256 pub name: Option<Ident>,
10258 pub data_type: DataType,
10260 pub default_expr: Option<Expr>,
10262}
10263
10264impl OperateFunctionArg {
10265 pub fn unnamed(data_type: DataType) -> Self {
10267 Self {
10268 mode: None,
10269 name: None,
10270 data_type,
10271 default_expr: None,
10272 }
10273 }
10274
10275 pub fn with_name(name: &str, data_type: DataType) -> Self {
10277 Self {
10278 mode: None,
10279 name: Some(name.into()),
10280 data_type,
10281 default_expr: None,
10282 }
10283 }
10284}
10285
10286impl fmt::Display for OperateFunctionArg {
10287 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10288 if let Some(mode) = &self.mode {
10289 write!(f, "{mode} ")?;
10290 }
10291 if let Some(name) = &self.name {
10292 write!(f, "{name} ")?;
10293 }
10294 write!(f, "{}", self.data_type)?;
10295 if let Some(default_expr) = &self.default_expr {
10296 write!(f, " = {default_expr}")?;
10297 }
10298 Ok(())
10299 }
10300}
10301
10302#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10304#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10305#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10306pub enum ArgMode {
10307 In,
10309 Out,
10311 InOut,
10313 Variadic,
10315}
10316
10317impl fmt::Display for ArgMode {
10318 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10319 match self {
10320 ArgMode::In => write!(f, "IN"),
10321 ArgMode::Out => write!(f, "OUT"),
10322 ArgMode::InOut => write!(f, "INOUT"),
10323 ArgMode::Variadic => write!(f, "VARIADIC"),
10324 }
10325 }
10326}
10327
10328#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10330#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10331#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10332pub enum FunctionBehavior {
10333 Immutable,
10335 Stable,
10337 Volatile,
10339}
10340
10341impl fmt::Display for FunctionBehavior {
10342 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10343 match self {
10344 FunctionBehavior::Immutable => write!(f, "IMMUTABLE"),
10345 FunctionBehavior::Stable => write!(f, "STABLE"),
10346 FunctionBehavior::Volatile => write!(f, "VOLATILE"),
10347 }
10348 }
10349}
10350
10351#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10355#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10356#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10357pub enum FunctionSecurity {
10358 Definer,
10360 Invoker,
10362}
10363
10364impl fmt::Display for FunctionSecurity {
10365 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10366 match self {
10367 FunctionSecurity::Definer => write!(f, "SECURITY DEFINER"),
10368 FunctionSecurity::Invoker => write!(f, "SECURITY INVOKER"),
10369 }
10370 }
10371}
10372
10373#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10377#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10378#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10379pub enum FunctionSetValue {
10380 Default,
10382 Values(Vec<Expr>),
10384 FromCurrent,
10386}
10387
10388#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10392#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10393#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10394pub struct FunctionDefinitionSetParam {
10395 pub name: ObjectName,
10397 pub value: FunctionSetValue,
10399}
10400
10401impl fmt::Display for FunctionDefinitionSetParam {
10402 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10403 write!(f, "SET {} ", self.name)?;
10404 match &self.value {
10405 FunctionSetValue::Default => write!(f, "= DEFAULT"),
10406 FunctionSetValue::Values(values) => {
10407 write!(f, "= {}", display_comma_separated(values))
10408 }
10409 FunctionSetValue::FromCurrent => write!(f, "FROM CURRENT"),
10410 }
10411 }
10412}
10413
10414#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10416#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10417#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10418pub enum FunctionCalledOnNull {
10419 CalledOnNullInput,
10421 ReturnsNullOnNullInput,
10423 Strict,
10425}
10426
10427impl fmt::Display for FunctionCalledOnNull {
10428 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10429 match self {
10430 FunctionCalledOnNull::CalledOnNullInput => write!(f, "CALLED ON NULL INPUT"),
10431 FunctionCalledOnNull::ReturnsNullOnNullInput => write!(f, "RETURNS NULL ON NULL INPUT"),
10432 FunctionCalledOnNull::Strict => write!(f, "STRICT"),
10433 }
10434 }
10435}
10436
10437#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10439#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10440#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10441pub enum FunctionParallel {
10442 Unsafe,
10444 Restricted,
10446 Safe,
10448}
10449
10450impl FunctionParallel {
10451 pub fn as_str(&self) -> &'static str {
10453 match self {
10454 FunctionParallel::Unsafe => "UNSAFE",
10455 FunctionParallel::Restricted => "RESTRICTED",
10456 FunctionParallel::Safe => "SAFE",
10457 }
10458 }
10459}
10460
10461impl fmt::Display for FunctionParallel {
10462 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10463 write!(f, "PARALLEL {}", self.as_str())
10464 }
10465}
10466
10467#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10471#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10472#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10473pub enum FunctionDeterminismSpecifier {
10474 Deterministic,
10476 NotDeterministic,
10478}
10479
10480impl fmt::Display for FunctionDeterminismSpecifier {
10481 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10482 match self {
10483 FunctionDeterminismSpecifier::Deterministic => {
10484 write!(f, "DETERMINISTIC")
10485 }
10486 FunctionDeterminismSpecifier::NotDeterministic => {
10487 write!(f, "NOT DETERMINISTIC")
10488 }
10489 }
10490 }
10491}
10492
10493#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10500#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10501#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10502pub enum CreateFunctionBody {
10503 AsBeforeOptions {
10516 body: Expr,
10518 link_symbol: Option<Expr>,
10527 },
10528 AsAfterOptions(Expr),
10540 AsBeginEnd(BeginEndStatements),
10556 Return(Expr),
10567 BeginAtomic(BeginEndStatements),
10571
10572 AsReturnExpr(Expr),
10583
10584 AsReturnSelect(Select),
10595}
10596
10597#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10599#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10600#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10601pub enum CreateProcedureBody {
10602 As(ConditionalStatements),
10604 BeginAtomic(BeginEndStatements),
10608}
10609
10610#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10611#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10612#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10613pub enum CreateFunctionUsing {
10615 Jar(String),
10617 File(String),
10619 Archive(String),
10621}
10622
10623impl fmt::Display for CreateFunctionUsing {
10624 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10625 write!(f, "USING ")?;
10626 match self {
10627 CreateFunctionUsing::Jar(uri) => write!(f, "JAR '{uri}'"),
10628 CreateFunctionUsing::File(uri) => write!(f, "FILE '{uri}'"),
10629 CreateFunctionUsing::Archive(uri) => write!(f, "ARCHIVE '{uri}'"),
10630 }
10631 }
10632}
10633
10634#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10639#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10640#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10641pub struct MacroArg {
10642 pub name: Ident,
10644 pub default_expr: Option<Expr>,
10646}
10647
10648impl MacroArg {
10649 pub fn new(name: &str) -> Self {
10651 Self {
10652 name: name.into(),
10653 default_expr: None,
10654 }
10655 }
10656}
10657
10658impl fmt::Display for MacroArg {
10659 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10660 write!(f, "{}", self.name)?;
10661 if let Some(default_expr) = &self.default_expr {
10662 write!(f, " := {default_expr}")?;
10663 }
10664 Ok(())
10665 }
10666}
10667
10668#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10669#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10670#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10671pub enum MacroDefinition {
10673 Expr(Expr),
10675 Table(Box<Query>),
10677}
10678
10679impl fmt::Display for MacroDefinition {
10680 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10681 match self {
10682 MacroDefinition::Expr(expr) => write!(f, "{expr}")?,
10683 MacroDefinition::Table(query) => write!(f, "{query}")?,
10684 }
10685 Ok(())
10686 }
10687}
10688
10689#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10693#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10694#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10695pub enum SchemaName {
10696 Simple(ObjectName),
10698 UnnamedAuthorization(Ident),
10700 NamedAuthorization(ObjectName, Ident),
10702}
10703
10704impl fmt::Display for SchemaName {
10705 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10706 match self {
10707 SchemaName::Simple(name) => {
10708 write!(f, "{name}")
10709 }
10710 SchemaName::UnnamedAuthorization(authorization) => {
10711 write!(f, "AUTHORIZATION {authorization}")
10712 }
10713 SchemaName::NamedAuthorization(name, authorization) => {
10714 write!(f, "{name} AUTHORIZATION {authorization}")
10715 }
10716 }
10717 }
10718}
10719
10720#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10724#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10725#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10726pub enum SearchModifier {
10727 InNaturalLanguageMode,
10729 InNaturalLanguageModeWithQueryExpansion,
10731 InBooleanMode,
10733 WithQueryExpansion,
10735}
10736
10737impl fmt::Display for SearchModifier {
10738 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10739 match self {
10740 Self::InNaturalLanguageMode => {
10741 write!(f, "IN NATURAL LANGUAGE MODE")?;
10742 }
10743 Self::InNaturalLanguageModeWithQueryExpansion => {
10744 write!(f, "IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION")?;
10745 }
10746 Self::InBooleanMode => {
10747 write!(f, "IN BOOLEAN MODE")?;
10748 }
10749 Self::WithQueryExpansion => {
10750 write!(f, "WITH QUERY EXPANSION")?;
10751 }
10752 }
10753
10754 Ok(())
10755 }
10756}
10757
10758#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10760#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10761#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10762pub struct LockTable {
10763 pub table: Ident,
10765 pub alias: Option<Ident>,
10767 pub lock_type: LockTableType,
10769}
10770
10771impl fmt::Display for LockTable {
10772 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10773 let Self {
10774 table: tbl_name,
10775 alias,
10776 lock_type,
10777 } = self;
10778
10779 write!(f, "{tbl_name} ")?;
10780 if let Some(alias) = alias {
10781 write!(f, "AS {alias} ")?;
10782 }
10783 write!(f, "{lock_type}")?;
10784 Ok(())
10785 }
10786}
10787
10788#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10789#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10790#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10791pub enum LockTableType {
10793 Read {
10795 local: bool,
10797 },
10798 Write {
10800 low_priority: bool,
10802 },
10803}
10804
10805impl fmt::Display for LockTableType {
10806 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10807 match self {
10808 Self::Read { local } => {
10809 write!(f, "READ")?;
10810 if *local {
10811 write!(f, " LOCAL")?;
10812 }
10813 }
10814 Self::Write { low_priority } => {
10815 if *low_priority {
10816 write!(f, "LOW_PRIORITY ")?;
10817 }
10818 write!(f, "WRITE")?;
10819 }
10820 }
10821
10822 Ok(())
10823 }
10824}
10825
10826#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10827#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10828#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10829pub struct HiveSetLocation {
10831 pub has_set: bool,
10833 pub location: Ident,
10835}
10836
10837impl fmt::Display for HiveSetLocation {
10838 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10839 if self.has_set {
10840 write!(f, "SET ")?;
10841 }
10842 write!(f, "LOCATION {}", self.location)
10843 }
10844}
10845
10846#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10848#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10849#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10850pub enum MySQLColumnPosition {
10852 First,
10854 After(Ident),
10856}
10857
10858impl Display for MySQLColumnPosition {
10859 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10860 match self {
10861 MySQLColumnPosition::First => write!(f, "FIRST"),
10862 MySQLColumnPosition::After(ident) => write!(f, "AFTER {ident}"),
10863 }
10864 }
10865}
10866
10867#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10869#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10870#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10871pub enum CreateViewAlgorithm {
10873 Undefined,
10875 Merge,
10877 TempTable,
10879}
10880
10881impl Display for CreateViewAlgorithm {
10882 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10883 match self {
10884 CreateViewAlgorithm::Undefined => write!(f, "UNDEFINED"),
10885 CreateViewAlgorithm::Merge => write!(f, "MERGE"),
10886 CreateViewAlgorithm::TempTable => write!(f, "TEMPTABLE"),
10887 }
10888 }
10889}
10890#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10892#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10893#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10894pub enum CreateViewSecurity {
10896 Definer,
10898 Invoker,
10900}
10901
10902impl Display for CreateViewSecurity {
10903 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10904 match self {
10905 CreateViewSecurity::Definer => write!(f, "DEFINER"),
10906 CreateViewSecurity::Invoker => write!(f, "INVOKER"),
10907 }
10908 }
10909}
10910
10911#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10915#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10916#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10917pub struct CreateViewParams {
10918 pub algorithm: Option<CreateViewAlgorithm>,
10920 pub definer: Option<GranteeName>,
10922 pub security: Option<CreateViewSecurity>,
10924}
10925
10926impl Display for CreateViewParams {
10927 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10928 let CreateViewParams {
10929 algorithm,
10930 definer,
10931 security,
10932 } = self;
10933 if let Some(algorithm) = algorithm {
10934 write!(f, "ALGORITHM = {algorithm} ")?;
10935 }
10936 if let Some(definers) = definer {
10937 write!(f, "DEFINER = {definers} ")?;
10938 }
10939 if let Some(security) = security {
10940 write!(f, "SQL SECURITY {security} ")?;
10941 }
10942 Ok(())
10943 }
10944}
10945
10946#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10947#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10948#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10949pub struct NamedParenthesizedList {
10957 pub key: Ident,
10959 pub name: Option<Ident>,
10961 pub values: Vec<Ident>,
10963}
10964
10965#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10970#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10971#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10972pub struct RowAccessPolicy {
10973 pub policy: ObjectName,
10975 pub on: Vec<Ident>,
10977}
10978
10979impl RowAccessPolicy {
10980 pub fn new(policy: ObjectName, on: Vec<Ident>) -> Self {
10982 Self { policy, on }
10983 }
10984}
10985
10986impl Display for RowAccessPolicy {
10987 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10988 write!(
10989 f,
10990 "WITH ROW ACCESS POLICY {} ON ({})",
10991 self.policy,
10992 display_comma_separated(self.on.as_slice())
10993 )
10994 }
10995}
10996
10997#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11001#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11002#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11003pub struct StorageLifecyclePolicy {
11004 pub policy: ObjectName,
11006 pub on: Vec<Ident>,
11008}
11009
11010impl Display for StorageLifecyclePolicy {
11011 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11012 write!(
11013 f,
11014 "WITH STORAGE LIFECYCLE POLICY {} ON ({})",
11015 self.policy,
11016 display_comma_separated(self.on.as_slice())
11017 )
11018 }
11019}
11020
11021#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11025#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11026#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11027pub struct Tag {
11028 pub key: ObjectName,
11030 pub value: String,
11032}
11033
11034impl Tag {
11035 pub fn new(key: ObjectName, value: String) -> Self {
11037 Self { key, value }
11038 }
11039}
11040
11041impl Display for Tag {
11042 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11043 write!(f, "{}='{}'", self.key, self.value)
11044 }
11045}
11046
11047#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11051#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11052#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11053pub struct ContactEntry {
11054 pub purpose: String,
11056 pub contact: String,
11058}
11059
11060impl Display for ContactEntry {
11061 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11062 write!(f, "{} = {}", self.purpose, self.contact)
11063 }
11064}
11065
11066#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11068#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11069#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11070pub enum CommentDef {
11071 WithEq(String),
11074 WithoutEq(String),
11076}
11077
11078impl Display for CommentDef {
11079 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11080 match self {
11081 CommentDef::WithEq(comment) | CommentDef::WithoutEq(comment) => write!(f, "{comment}"),
11082 }
11083 }
11084}
11085
11086#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11101#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11102#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11103pub enum WrappedCollection<T> {
11104 NoWrapping(T),
11106 Parentheses(T),
11108}
11109
11110impl<T> Display for WrappedCollection<Vec<T>>
11111where
11112 T: Display,
11113{
11114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11115 match self {
11116 WrappedCollection::NoWrapping(inner) => {
11117 write!(f, "{}", display_comma_separated(inner.as_slice()))
11118 }
11119 WrappedCollection::Parentheses(inner) => {
11120 write!(f, "({})", display_comma_separated(inner.as_slice()))
11121 }
11122 }
11123 }
11124}
11125
11126#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11150#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11151#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11152pub struct UtilityOption {
11153 pub name: Ident,
11155 pub arg: Option<Expr>,
11157}
11158
11159impl Display for UtilityOption {
11160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11161 if let Some(ref arg) = self.arg {
11162 write!(f, "{} {}", self.name, arg)
11163 } else {
11164 write!(f, "{}", self.name)
11165 }
11166 }
11167}
11168
11169#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11173#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11174#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11175pub struct ShowStatementOptions {
11176 pub show_in: Option<ShowStatementIn>,
11178 pub starts_with: Option<ValueWithSpan>,
11180 pub limit: Option<Expr>,
11182 pub limit_from: Option<ValueWithSpan>,
11184 pub filter_position: Option<ShowStatementFilterPosition>,
11186}
11187
11188impl Display for ShowStatementOptions {
11189 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11190 let (like_in_infix, like_in_suffix) = match &self.filter_position {
11191 Some(ShowStatementFilterPosition::Infix(filter)) => {
11192 (format!(" {filter}"), "".to_string())
11193 }
11194 Some(ShowStatementFilterPosition::Suffix(filter)) => {
11195 ("".to_string(), format!(" {filter}"))
11196 }
11197 None => ("".to_string(), "".to_string()),
11198 };
11199 write!(
11200 f,
11201 "{like_in_infix}{show_in}{starts_with}{limit}{from}{like_in_suffix}",
11202 show_in = match &self.show_in {
11203 Some(i) => format!(" {i}"),
11204 None => String::new(),
11205 },
11206 starts_with = match &self.starts_with {
11207 Some(s) => format!(" STARTS WITH {s}"),
11208 None => String::new(),
11209 },
11210 limit = match &self.limit {
11211 Some(l) => format!(" LIMIT {l}"),
11212 None => String::new(),
11213 },
11214 from = match &self.limit_from {
11215 Some(f) => format!(" FROM {f}"),
11216 None => String::new(),
11217 }
11218 )?;
11219 Ok(())
11220 }
11221}
11222
11223#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11224#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11225#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11226pub enum ShowStatementFilterPosition {
11228 Infix(ShowStatementFilter), Suffix(ShowStatementFilter), }
11233
11234#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11235#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11236#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11237pub enum ShowStatementInParentType {
11239 Account,
11241 Database,
11243 Schema,
11245 Table,
11247 View,
11249}
11250
11251impl fmt::Display for ShowStatementInParentType {
11252 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11253 match self {
11254 ShowStatementInParentType::Account => write!(f, "ACCOUNT"),
11255 ShowStatementInParentType::Database => write!(f, "DATABASE"),
11256 ShowStatementInParentType::Schema => write!(f, "SCHEMA"),
11257 ShowStatementInParentType::Table => write!(f, "TABLE"),
11258 ShowStatementInParentType::View => write!(f, "VIEW"),
11259 }
11260 }
11261}
11262
11263#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11264#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11265#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11266pub struct ShowStatementIn {
11268 pub clause: ShowStatementInClause,
11270 pub parent_type: Option<ShowStatementInParentType>,
11272 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
11274 pub parent_name: Option<ObjectName>,
11275}
11276
11277impl fmt::Display for ShowStatementIn {
11278 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11279 write!(f, "{}", self.clause)?;
11280 if let Some(parent_type) = &self.parent_type {
11281 write!(f, " {parent_type}")?;
11282 }
11283 if let Some(parent_name) = &self.parent_name {
11284 write!(f, " {parent_name}")?;
11285 }
11286 Ok(())
11287 }
11288}
11289
11290#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11292#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11293#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11294pub struct ShowCharset {
11295 pub is_shorthand: bool,
11298 pub filter: Option<ShowStatementFilter>,
11300}
11301
11302impl fmt::Display for ShowCharset {
11303 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11304 write!(f, "SHOW")?;
11305 if self.is_shorthand {
11306 write!(f, " CHARSET")?;
11307 } else {
11308 write!(f, " CHARACTER SET")?;
11309 }
11310 if let Some(filter) = &self.filter {
11311 write!(f, " {filter}")?;
11312 }
11313 Ok(())
11314 }
11315}
11316
11317#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11318#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11319#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11320pub struct ShowObjects {
11322 pub terse: bool,
11324 pub show_options: ShowStatementOptions,
11326}
11327
11328#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11338#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11339#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11340pub enum JsonNullClause {
11341 NullOnNull,
11343 AbsentOnNull,
11345}
11346
11347impl Display for JsonNullClause {
11348 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11349 match self {
11350 JsonNullClause::NullOnNull => write!(f, "NULL ON NULL"),
11351 JsonNullClause::AbsentOnNull => write!(f, "ABSENT ON NULL"),
11352 }
11353 }
11354}
11355
11356#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11363#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11364#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11365pub struct JsonReturningClause {
11366 pub data_type: DataType,
11368}
11369
11370impl Display for JsonReturningClause {
11371 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11372 write!(f, "RETURNING {}", self.data_type)
11373 }
11374}
11375
11376#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11378#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11379#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11380pub struct RenameTable {
11381 pub old_name: ObjectName,
11383 pub new_name: ObjectName,
11385}
11386
11387impl fmt::Display for RenameTable {
11388 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11389 write!(f, "{} TO {}", self.old_name, self.new_name)?;
11390 Ok(())
11391 }
11392}
11393
11394#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11396#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11397#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11398pub enum TableObject {
11399 TableName(#[cfg_attr(feature = "visitor", visit(with = "visit_relation"))] ObjectName),
11405
11406 TableFunction(Function),
11413
11414 TableQuery(Box<Query>),
11423}
11424
11425impl fmt::Display for TableObject {
11426 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11427 match self {
11428 Self::TableName(table_name) => write!(f, "{table_name}"),
11429 Self::TableFunction(func) => write!(f, "FUNCTION {func}"),
11430 Self::TableQuery(table_query) => write!(f, "({table_query})"),
11431 }
11432 }
11433}
11434
11435#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11437#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11438#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11439pub struct SetSessionAuthorizationParam {
11440 pub scope: ContextModifier,
11442 pub kind: SetSessionAuthorizationParamKind,
11444}
11445
11446impl fmt::Display for SetSessionAuthorizationParam {
11447 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11448 write!(f, "{}", self.kind)
11449 }
11450}
11451
11452#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11454#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11455#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11456pub enum SetSessionAuthorizationParamKind {
11457 Default,
11459
11460 User(Ident),
11462}
11463
11464impl fmt::Display for SetSessionAuthorizationParamKind {
11465 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11466 match self {
11467 SetSessionAuthorizationParamKind::Default => write!(f, "DEFAULT"),
11468 SetSessionAuthorizationParamKind::User(name) => write!(f, "{}", name),
11469 }
11470 }
11471}
11472
11473#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11474#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11475#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11476pub enum SetSessionParamKind {
11478 Generic(SetSessionParamGeneric),
11480 IdentityInsert(SetSessionParamIdentityInsert),
11482 Offsets(SetSessionParamOffsets),
11484 Statistics(SetSessionParamStatistics),
11486}
11487
11488impl fmt::Display for SetSessionParamKind {
11489 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11490 match self {
11491 SetSessionParamKind::Generic(x) => write!(f, "{x}"),
11492 SetSessionParamKind::IdentityInsert(x) => write!(f, "{x}"),
11493 SetSessionParamKind::Offsets(x) => write!(f, "{x}"),
11494 SetSessionParamKind::Statistics(x) => write!(f, "{x}"),
11495 }
11496 }
11497}
11498
11499#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11500#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11501#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11502pub struct SetSessionParamGeneric {
11504 pub names: Vec<String>,
11506 pub value: String,
11508}
11509
11510impl fmt::Display for SetSessionParamGeneric {
11511 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11512 write!(f, "{} {}", display_comma_separated(&self.names), self.value)
11513 }
11514}
11515
11516#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11517#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11518#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11519pub struct SetSessionParamIdentityInsert {
11521 pub obj: ObjectName,
11523 pub value: SessionParamValue,
11525}
11526
11527impl fmt::Display for SetSessionParamIdentityInsert {
11528 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11529 write!(f, "IDENTITY_INSERT {} {}", self.obj, self.value)
11530 }
11531}
11532
11533#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11534#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11535#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11536pub struct SetSessionParamOffsets {
11538 pub keywords: Vec<String>,
11540 pub value: SessionParamValue,
11542}
11543
11544impl fmt::Display for SetSessionParamOffsets {
11545 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11546 write!(
11547 f,
11548 "OFFSETS {} {}",
11549 display_comma_separated(&self.keywords),
11550 self.value
11551 )
11552 }
11553}
11554
11555#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11556#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11557#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11558pub struct SetSessionParamStatistics {
11560 pub topic: SessionParamStatsTopic,
11562 pub value: SessionParamValue,
11564}
11565
11566impl fmt::Display for SetSessionParamStatistics {
11567 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11568 write!(f, "STATISTICS {} {}", self.topic, self.value)
11569 }
11570}
11571
11572#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11573#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11574#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11575pub enum SessionParamStatsTopic {
11577 IO,
11579 Profile,
11581 Time,
11583 Xml,
11585}
11586
11587impl fmt::Display for SessionParamStatsTopic {
11588 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11589 match self {
11590 SessionParamStatsTopic::IO => write!(f, "IO"),
11591 SessionParamStatsTopic::Profile => write!(f, "PROFILE"),
11592 SessionParamStatsTopic::Time => write!(f, "TIME"),
11593 SessionParamStatsTopic::Xml => write!(f, "XML"),
11594 }
11595 }
11596}
11597
11598#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11599#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11600#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11601pub enum SessionParamValue {
11603 On,
11605 Off,
11607}
11608
11609impl fmt::Display for SessionParamValue {
11610 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11611 match self {
11612 SessionParamValue::On => write!(f, "ON"),
11613 SessionParamValue::Off => write!(f, "OFF"),
11614 }
11615 }
11616}
11617
11618#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11625#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11626#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11627pub enum StorageSerializationPolicy {
11628 Compatible,
11630 Optimized,
11632}
11633
11634impl Display for StorageSerializationPolicy {
11635 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11636 match self {
11637 StorageSerializationPolicy::Compatible => write!(f, "COMPATIBLE"),
11638 StorageSerializationPolicy::Optimized => write!(f, "OPTIMIZED"),
11639 }
11640 }
11641}
11642
11643#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11650#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11651#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11652pub enum CatalogSyncNamespaceMode {
11653 Nest,
11655 Flatten,
11657}
11658
11659impl Display for CatalogSyncNamespaceMode {
11660 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11661 match self {
11662 CatalogSyncNamespaceMode::Nest => write!(f, "NEST"),
11663 CatalogSyncNamespaceMode::Flatten => write!(f, "FLATTEN"),
11664 }
11665 }
11666}
11667
11668#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11670#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11671#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11672pub enum CopyIntoSnowflakeKind {
11673 Table,
11676 Location,
11679}
11680
11681#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11682#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11683#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11684pub struct PrintStatement {
11686 pub message: Box<Expr>,
11688}
11689
11690impl fmt::Display for PrintStatement {
11691 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11692 write!(f, "PRINT {}", self.message)
11693 }
11694}
11695
11696#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11700#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11701#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11702pub enum WaitForType {
11703 Delay,
11705 Time,
11707}
11708
11709impl fmt::Display for WaitForType {
11710 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11711 match self {
11712 WaitForType::Delay => write!(f, "DELAY"),
11713 WaitForType::Time => write!(f, "TIME"),
11714 }
11715 }
11716}
11717
11718#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11722#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11723#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11724pub struct WaitForStatement {
11725 pub wait_type: WaitForType,
11727 pub expr: Expr,
11729}
11730
11731impl fmt::Display for WaitForStatement {
11732 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11733 write!(f, "WAITFOR {} {}", self.wait_type, self.expr)
11734 }
11735}
11736
11737#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11742#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11743#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11744pub struct ReturnStatement {
11745 pub value: Option<ReturnStatementValue>,
11747}
11748
11749impl fmt::Display for ReturnStatement {
11750 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11751 match &self.value {
11752 Some(ReturnStatementValue::Expr(expr)) => write!(f, "RETURN {expr}"),
11753 None => write!(f, "RETURN"),
11754 }
11755 }
11756}
11757
11758#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11760#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11761#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11762pub enum ReturnStatementValue {
11763 Expr(Expr),
11765}
11766
11767#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11769#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11770#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11771pub struct OpenStatement {
11772 pub cursor_name: Ident,
11774}
11775
11776impl fmt::Display for OpenStatement {
11777 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11778 write!(f, "OPEN {}", self.cursor_name)
11779 }
11780}
11781
11782#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11786#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11787#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11788pub enum NullInclusion {
11789 IncludeNulls,
11791 ExcludeNulls,
11793}
11794
11795impl fmt::Display for NullInclusion {
11796 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11797 match self {
11798 NullInclusion::IncludeNulls => write!(f, "INCLUDE NULLS"),
11799 NullInclusion::ExcludeNulls => write!(f, "EXCLUDE NULLS"),
11800 }
11801 }
11802}
11803
11804#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11812#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11813#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11814pub struct MemberOf {
11815 pub value: Box<Expr>,
11817 pub array: Box<Expr>,
11819}
11820
11821impl fmt::Display for MemberOf {
11822 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11823 write!(f, "{} MEMBER OF({})", self.value, self.array)
11824 }
11825}
11826
11827#[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 ExportData {
11832 pub options: Vec<SqlOption>,
11834 pub query: Box<Query>,
11836 pub connection: Option<ObjectName>,
11838}
11839
11840impl fmt::Display for ExportData {
11841 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11842 if let Some(connection) = &self.connection {
11843 write!(
11844 f,
11845 "EXPORT DATA WITH CONNECTION {connection} OPTIONS({}) AS {}",
11846 display_comma_separated(&self.options),
11847 self.query
11848 )
11849 } else {
11850 write!(
11851 f,
11852 "EXPORT DATA OPTIONS({}) AS {}",
11853 display_comma_separated(&self.options),
11854 self.query
11855 )
11856 }
11857 }
11858}
11859#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11868#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11869#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11870pub struct CreateUser {
11871 pub or_replace: bool,
11873 pub if_not_exists: bool,
11875 pub name: Ident,
11877 pub options: KeyValueOptions,
11879 pub with_tags: bool,
11881 pub tags: KeyValueOptions,
11883}
11884
11885impl fmt::Display for CreateUser {
11886 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11887 write!(f, "CREATE")?;
11888 if self.or_replace {
11889 write!(f, " OR REPLACE")?;
11890 }
11891 write!(f, " USER")?;
11892 if self.if_not_exists {
11893 write!(f, " IF NOT EXISTS")?;
11894 }
11895 write!(f, " {}", self.name)?;
11896 if !self.options.options.is_empty() {
11897 write!(f, " {}", self.options)?;
11898 }
11899 if !self.tags.options.is_empty() {
11900 if self.with_tags {
11901 write!(f, " WITH")?;
11902 }
11903 write!(f, " TAG ({})", self.tags)?;
11904 }
11905 Ok(())
11906 }
11907}
11908
11909#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11917#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11918#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11919pub struct CreateWarehouse {
11920 pub or_replace: bool,
11922 pub if_not_exists: bool,
11924 pub name: ObjectName,
11926 pub options: KeyValueOptions,
11928}
11929
11930impl fmt::Display for CreateWarehouse {
11931 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11932 write!(f, "CREATE")?;
11933 if self.or_replace {
11934 write!(f, " OR REPLACE")?;
11935 }
11936 write!(f, " WAREHOUSE")?;
11937 if self.if_not_exists {
11938 write!(f, " IF NOT EXISTS")?;
11939 }
11940 write!(f, " {}", self.name)?;
11941 if !self.options.options.is_empty() {
11942 write!(f, " {}", self.options)?;
11943 }
11944 Ok(())
11945 }
11946}
11947
11948#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11960#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11961#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11962pub struct AlterUser {
11963 pub if_exists: bool,
11965 pub name: Ident,
11967 pub rename_to: Option<Ident>,
11970 pub reset_password: bool,
11972 pub abort_all_queries: bool,
11974 pub add_role_delegation: Option<AlterUserAddRoleDelegation>,
11976 pub remove_role_delegation: Option<AlterUserRemoveRoleDelegation>,
11978 pub enroll_mfa: bool,
11980 pub set_default_mfa_method: Option<MfaMethodKind>,
11982 pub remove_mfa_method: Option<MfaMethodKind>,
11984 pub modify_mfa_method: Option<AlterUserModifyMfaMethod>,
11986 pub add_mfa_method_otp: Option<AlterUserAddMfaMethodOtp>,
11988 pub set_policy: Option<AlterUserSetPolicy>,
11990 pub unset_policy: Option<UserPolicyKind>,
11992 pub set_tag: KeyValueOptions,
11994 pub unset_tag: Vec<String>,
11996 pub set_props: KeyValueOptions,
11998 pub unset_props: Vec<String>,
12000 pub password: Option<AlterUserPassword>,
12002}
12003
12004#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12008#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12009#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12010pub struct AlterUserAddRoleDelegation {
12011 pub role: Ident,
12013 pub integration: Ident,
12015}
12016
12017#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12021#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12022#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12023pub struct AlterUserRemoveRoleDelegation {
12024 pub role: Option<Ident>,
12026 pub integration: Ident,
12028}
12029
12030#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12034#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12035#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12036pub struct AlterUserAddMfaMethodOtp {
12037 pub count: Option<ValueWithSpan>,
12039}
12040
12041#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12045#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12046#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12047pub struct AlterUserModifyMfaMethod {
12048 pub method: MfaMethodKind,
12050 pub comment: String,
12052}
12053
12054#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12056#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12057#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12058pub enum MfaMethodKind {
12059 PassKey,
12061 Totp,
12063 Duo,
12065}
12066
12067impl fmt::Display for MfaMethodKind {
12068 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12069 match self {
12070 MfaMethodKind::PassKey => write!(f, "PASSKEY"),
12071 MfaMethodKind::Totp => write!(f, "TOTP"),
12072 MfaMethodKind::Duo => write!(f, "DUO"),
12073 }
12074 }
12075}
12076
12077#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12081#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12082#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12083pub struct AlterUserSetPolicy {
12084 pub policy_kind: UserPolicyKind,
12086 pub policy: Ident,
12088}
12089
12090#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12092#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12093#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12094pub enum UserPolicyKind {
12095 Authentication,
12097 Password,
12099 Session,
12101}
12102
12103impl fmt::Display for UserPolicyKind {
12104 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12105 match self {
12106 UserPolicyKind::Authentication => write!(f, "AUTHENTICATION"),
12107 UserPolicyKind::Password => write!(f, "PASSWORD"),
12108 UserPolicyKind::Session => write!(f, "SESSION"),
12109 }
12110 }
12111}
12112
12113impl fmt::Display for AlterUser {
12114 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12115 write!(f, "ALTER")?;
12116 write!(f, " USER")?;
12117 if self.if_exists {
12118 write!(f, " IF EXISTS")?;
12119 }
12120 write!(f, " {}", self.name)?;
12121 if let Some(new_name) = &self.rename_to {
12122 write!(f, " RENAME TO {new_name}")?;
12123 }
12124 if self.reset_password {
12125 write!(f, " RESET PASSWORD")?;
12126 }
12127 if self.abort_all_queries {
12128 write!(f, " ABORT ALL QUERIES")?;
12129 }
12130 if let Some(role_delegation) = &self.add_role_delegation {
12131 let role = &role_delegation.role;
12132 let integration = &role_delegation.integration;
12133 write!(
12134 f,
12135 " ADD DELEGATED AUTHORIZATION OF ROLE {role} TO SECURITY INTEGRATION {integration}"
12136 )?;
12137 }
12138 if let Some(role_delegation) = &self.remove_role_delegation {
12139 write!(f, " REMOVE DELEGATED")?;
12140 match &role_delegation.role {
12141 Some(role) => write!(f, " AUTHORIZATION OF ROLE {role}")?,
12142 None => write!(f, " AUTHORIZATIONS")?,
12143 }
12144 let integration = &role_delegation.integration;
12145 write!(f, " FROM SECURITY INTEGRATION {integration}")?;
12146 }
12147 if self.enroll_mfa {
12148 write!(f, " ENROLL MFA")?;
12149 }
12150 if let Some(method) = &self.set_default_mfa_method {
12151 write!(f, " SET DEFAULT_MFA_METHOD {method}")?
12152 }
12153 if let Some(method) = &self.remove_mfa_method {
12154 write!(f, " REMOVE MFA METHOD {method}")?;
12155 }
12156 if let Some(modify) = &self.modify_mfa_method {
12157 let method = &modify.method;
12158 let comment = &modify.comment;
12159 write!(
12160 f,
12161 " MODIFY MFA METHOD {method} SET COMMENT '{}'",
12162 value::escape_single_quote_string(comment)
12163 )?;
12164 }
12165 if let Some(add_mfa_method_otp) = &self.add_mfa_method_otp {
12166 write!(f, " ADD MFA METHOD OTP")?;
12167 if let Some(count) = &add_mfa_method_otp.count {
12168 write!(f, " COUNT = {count}")?;
12169 }
12170 }
12171 if let Some(policy) = &self.set_policy {
12172 let policy_kind = &policy.policy_kind;
12173 let name = &policy.policy;
12174 write!(f, " SET {policy_kind} POLICY {name}")?;
12175 }
12176 if let Some(policy_kind) = &self.unset_policy {
12177 write!(f, " UNSET {policy_kind} POLICY")?;
12178 }
12179 if !self.set_tag.options.is_empty() {
12180 write!(f, " SET TAG {}", self.set_tag)?;
12181 }
12182 if !self.unset_tag.is_empty() {
12183 write!(f, " UNSET TAG {}", display_comma_separated(&self.unset_tag))?;
12184 }
12185 let has_props = !self.set_props.options.is_empty();
12186 if has_props {
12187 write!(f, " SET")?;
12188 write!(f, " {}", self.set_props)?;
12189 }
12190 if !self.unset_props.is_empty() {
12191 write!(f, " UNSET {}", display_comma_separated(&self.unset_props))?;
12192 }
12193 if let Some(password) = &self.password {
12194 write!(f, " {}", password)?;
12195 }
12196 Ok(())
12197 }
12198}
12199
12200#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12204#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12205#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12206pub struct AlterUserPassword {
12207 pub encrypted: bool,
12209 pub password: Option<String>,
12211}
12212
12213impl Display for AlterUserPassword {
12214 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12215 if self.encrypted {
12216 write!(f, "ENCRYPTED ")?;
12217 }
12218 write!(f, "PASSWORD")?;
12219 match &self.password {
12220 None => write!(f, " NULL")?,
12221 Some(password) => write!(f, " '{}'", value::escape_single_quote_string(password))?,
12222 }
12223 Ok(())
12224 }
12225}
12226
12227#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12232#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12233#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12234pub enum CreateTableLikeKind {
12235 Parenthesized(CreateTableLike),
12240 Plain(CreateTableLike),
12246}
12247
12248#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12249#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12250#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12251pub enum CreateTableLikeDefaults {
12253 Including,
12255 Excluding,
12257}
12258
12259impl fmt::Display for CreateTableLikeDefaults {
12260 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12261 match self {
12262 CreateTableLikeDefaults::Including => write!(f, "INCLUDING DEFAULTS"),
12263 CreateTableLikeDefaults::Excluding => write!(f, "EXCLUDING DEFAULTS"),
12264 }
12265 }
12266}
12267
12268#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12269#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12270#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12271pub struct CreateTableLike {
12273 pub name: ObjectName,
12275 pub defaults: Option<CreateTableLikeDefaults>,
12277}
12278
12279impl fmt::Display for CreateTableLike {
12280 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12281 write!(f, "LIKE {}", self.name)?;
12282 if let Some(defaults) = &self.defaults {
12283 write!(f, " {defaults}")?;
12284 }
12285 Ok(())
12286 }
12287}
12288
12289#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12293#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12294#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12295pub enum RefreshModeKind {
12296 Auto,
12298 Full,
12300 Incremental,
12302}
12303
12304impl fmt::Display for RefreshModeKind {
12305 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12306 match self {
12307 RefreshModeKind::Auto => write!(f, "AUTO"),
12308 RefreshModeKind::Full => write!(f, "FULL"),
12309 RefreshModeKind::Incremental => write!(f, "INCREMENTAL"),
12310 }
12311 }
12312}
12313
12314#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12318#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12319#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12320pub enum InitializeKind {
12321 OnCreate,
12323 OnSchedule,
12325}
12326
12327impl fmt::Display for InitializeKind {
12328 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12329 match self {
12330 InitializeKind::OnCreate => write!(f, "ON_CREATE"),
12331 InitializeKind::OnSchedule => write!(f, "ON_SCHEDULE"),
12332 }
12333 }
12334}
12335
12336#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12343#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12344#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12345pub struct VacuumStatement {
12346 pub full: bool,
12348 pub sort_only: bool,
12350 pub delete_only: bool,
12352 pub reindex: bool,
12354 pub recluster: bool,
12356 pub table_name: Option<ObjectName>,
12358 pub threshold: Option<ValueWithSpan>,
12360 pub boost: bool,
12362}
12363
12364impl fmt::Display for VacuumStatement {
12365 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12366 write!(
12367 f,
12368 "VACUUM{}{}{}{}{}",
12369 if self.full { " FULL" } else { "" },
12370 if self.sort_only { " SORT ONLY" } else { "" },
12371 if self.delete_only { " DELETE ONLY" } else { "" },
12372 if self.reindex { " REINDEX" } else { "" },
12373 if self.recluster { " RECLUSTER" } else { "" },
12374 )?;
12375 if let Some(table_name) = &self.table_name {
12376 write!(f, " {table_name}")?;
12377 }
12378 if let Some(threshold) = &self.threshold {
12379 write!(f, " TO {threshold} PERCENT")?;
12380 }
12381 if self.boost {
12382 write!(f, " BOOST")?;
12383 }
12384 Ok(())
12385 }
12386}
12387
12388#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12390#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12391#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12392pub enum Reset {
12393 ALL,
12395
12396 SessionAuthorization,
12398
12399 ConfigurationParameter(ObjectName),
12401}
12402
12403#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12408#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12409#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12410pub struct ResetStatement {
12411 pub reset: Reset,
12413}
12414
12415#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12419#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12420#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12421pub struct RefreshMaterializedView {
12422 pub concurrently: bool,
12424 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
12426 pub name: ObjectName,
12427 pub with_data: Option<bool>,
12429}
12430
12431impl fmt::Display for RefreshMaterializedView {
12432 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12433 f.write_str("REFRESH MATERIALIZED VIEW ")?;
12434 if self.concurrently {
12435 f.write_str("CONCURRENTLY ")?;
12436 }
12437 write!(f, "{}", self.name)?;
12438 match self.with_data {
12439 Some(true) => f.write_str(" WITH DATA"),
12440 Some(false) => f.write_str(" WITH NO DATA"),
12441 None => Ok(()),
12442 }
12443 }
12444}
12445
12446#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12452#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12453#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12454pub struct OptimizerHint {
12455 pub prefix: String,
12462 pub text: String,
12464 pub style: OptimizerHintStyle,
12469}
12470
12471#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12473#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12474#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12475pub enum OptimizerHintStyle {
12476 SingleLine {
12479 prefix: String,
12481 },
12482 MultiLine,
12485}
12486
12487impl fmt::Display for OptimizerHint {
12488 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
12489 match &self.style {
12490 OptimizerHintStyle::SingleLine { prefix } => {
12491 f.write_str(prefix)?;
12492 f.write_str(&self.prefix)?;
12493 f.write_str("+")?;
12494 f.write_str(&self.text)?;
12495 f.write_str("\n")
12496 }
12497 OptimizerHintStyle::MultiLine => {
12498 f.write_str("/*")?;
12499 f.write_str(&self.prefix)?;
12500 f.write_str("+")?;
12501 f.write_str(&self.text)?;
12502 f.write_str("*/")
12503 }
12504 }
12505 }
12506}
12507
12508impl fmt::Display for ResetStatement {
12509 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12510 match &self.reset {
12511 Reset::ALL => write!(f, "RESET ALL"),
12512 Reset::SessionAuthorization => write!(f, "RESET SESSION AUTHORIZATION"),
12513 Reset::ConfigurationParameter(param) => write!(f, "RESET {}", param),
12514 }
12515 }
12516}
12517
12518impl From<Set> for Statement {
12519 fn from(s: Set) -> Self {
12520 Self::Set(s)
12521 }
12522}
12523
12524impl From<Query> for Statement {
12525 fn from(q: Query) -> Self {
12526 Box::new(q).into()
12527 }
12528}
12529
12530impl From<Box<Query>> for Statement {
12531 fn from(q: Box<Query>) -> Self {
12532 Self::Query(q)
12533 }
12534}
12535
12536impl From<Insert> for Statement {
12537 fn from(i: Insert) -> Self {
12538 Self::Insert(i)
12539 }
12540}
12541
12542impl From<Update> for Statement {
12543 fn from(u: Update) -> Self {
12544 Self::Update(u)
12545 }
12546}
12547
12548impl From<CreateView> for Statement {
12549 fn from(cv: CreateView) -> Self {
12550 Self::CreateView(cv)
12551 }
12552}
12553
12554impl From<CreateRole> for Statement {
12555 fn from(cr: CreateRole) -> Self {
12556 Self::CreateRole(cr)
12557 }
12558}
12559
12560impl From<AlterTable> for Statement {
12561 fn from(at: AlterTable) -> Self {
12562 Self::AlterTable(at)
12563 }
12564}
12565
12566impl From<DropFunction> for Statement {
12567 fn from(df: DropFunction) -> Self {
12568 Self::DropFunction(df)
12569 }
12570}
12571
12572impl From<CreateExtension> for Statement {
12573 fn from(ce: CreateExtension) -> Self {
12574 Self::CreateExtension(ce)
12575 }
12576}
12577
12578impl From<CreateCollation> for Statement {
12579 fn from(c: CreateCollation) -> Self {
12580 Self::CreateCollation(c)
12581 }
12582}
12583
12584impl From<DropExtension> for Statement {
12585 fn from(de: DropExtension) -> Self {
12586 Self::DropExtension(de)
12587 }
12588}
12589
12590impl From<CaseStatement> for Statement {
12591 fn from(c: CaseStatement) -> Self {
12592 Self::Case(c)
12593 }
12594}
12595
12596impl From<IfStatement> for Statement {
12597 fn from(i: IfStatement) -> Self {
12598 Self::If(i)
12599 }
12600}
12601
12602impl From<WhileStatement> for Statement {
12603 fn from(w: WhileStatement) -> Self {
12604 Self::While(w)
12605 }
12606}
12607
12608impl From<RaiseStatement> for Statement {
12609 fn from(r: RaiseStatement) -> Self {
12610 Self::Raise(r)
12611 }
12612}
12613
12614impl From<ThrowStatement> for Statement {
12615 fn from(t: ThrowStatement) -> Self {
12616 Self::Throw(t)
12617 }
12618}
12619
12620impl From<Function> for Statement {
12621 fn from(f: Function) -> Self {
12622 Self::Call(f)
12623 }
12624}
12625
12626impl From<OpenStatement> for Statement {
12627 fn from(o: OpenStatement) -> Self {
12628 Self::Open(o)
12629 }
12630}
12631
12632impl From<Delete> for Statement {
12633 fn from(d: Delete) -> Self {
12634 Self::Delete(d)
12635 }
12636}
12637
12638impl From<CreateTable> for Statement {
12639 fn from(c: CreateTable) -> Self {
12640 Self::CreateTable(c)
12641 }
12642}
12643
12644impl From<CreateIndex> for Statement {
12645 fn from(c: CreateIndex) -> Self {
12646 Self::CreateIndex(c)
12647 }
12648}
12649
12650impl From<CreateServerStatement> for Statement {
12651 fn from(c: CreateServerStatement) -> Self {
12652 Self::CreateServer(c)
12653 }
12654}
12655
12656impl From<CreateConnector> for Statement {
12657 fn from(c: CreateConnector) -> Self {
12658 Self::CreateConnector(c)
12659 }
12660}
12661
12662impl From<CreateOperator> for Statement {
12663 fn from(c: CreateOperator) -> Self {
12664 Self::CreateOperator(c)
12665 }
12666}
12667
12668impl From<CreateOperatorFamily> for Statement {
12669 fn from(c: CreateOperatorFamily) -> Self {
12670 Self::CreateOperatorFamily(c)
12671 }
12672}
12673
12674impl From<CreateOperatorClass> for Statement {
12675 fn from(c: CreateOperatorClass) -> Self {
12676 Self::CreateOperatorClass(c)
12677 }
12678}
12679
12680impl From<CreateTextSearch> for Statement {
12681 fn from(c: CreateTextSearch) -> Self {
12682 Self::CreateTextSearch(c)
12683 }
12684}
12685
12686impl From<AlterSchema> for Statement {
12687 fn from(a: AlterSchema) -> Self {
12688 Self::AlterSchema(a)
12689 }
12690}
12691
12692impl From<AlterFunction> for Statement {
12693 fn from(a: AlterFunction) -> Self {
12694 Self::AlterFunction(a)
12695 }
12696}
12697
12698impl From<AlterType> for Statement {
12699 fn from(a: AlterType) -> Self {
12700 Self::AlterType(a)
12701 }
12702}
12703
12704impl From<AlterCollation> for Statement {
12705 fn from(a: AlterCollation) -> Self {
12706 Self::AlterCollation(a)
12707 }
12708}
12709
12710impl From<AlterView> for Statement {
12711 fn from(a: AlterView) -> Self {
12712 Self::AlterView(a)
12713 }
12714}
12715
12716impl From<AlterOperator> for Statement {
12717 fn from(a: AlterOperator) -> Self {
12718 Self::AlterOperator(a)
12719 }
12720}
12721
12722impl From<AlterOperatorFamily> for Statement {
12723 fn from(a: AlterOperatorFamily) -> Self {
12724 Self::AlterOperatorFamily(a)
12725 }
12726}
12727
12728impl From<AlterOperatorClass> for Statement {
12729 fn from(a: AlterOperatorClass) -> Self {
12730 Self::AlterOperatorClass(a)
12731 }
12732}
12733
12734impl From<AlterTextSearch> for Statement {
12735 fn from(a: AlterTextSearch) -> Self {
12736 Self::AlterTextSearch(a)
12737 }
12738}
12739
12740impl From<Merge> for Statement {
12741 fn from(m: Merge) -> Self {
12742 Self::Merge(m)
12743 }
12744}
12745
12746impl From<AlterUser> for Statement {
12747 fn from(a: AlterUser) -> Self {
12748 Self::AlterUser(a)
12749 }
12750}
12751
12752impl From<DropDomain> for Statement {
12753 fn from(d: DropDomain) -> Self {
12754 Self::DropDomain(d)
12755 }
12756}
12757
12758impl From<ShowCharset> for Statement {
12759 fn from(s: ShowCharset) -> Self {
12760 Self::ShowCharset(s)
12761 }
12762}
12763
12764impl From<ShowObjects> for Statement {
12765 fn from(s: ShowObjects) -> Self {
12766 Self::ShowObjects(s)
12767 }
12768}
12769
12770impl From<Use> for Statement {
12771 fn from(u: Use) -> Self {
12772 Self::Use(u)
12773 }
12774}
12775
12776impl From<CreateFunction> for Statement {
12777 fn from(c: CreateFunction) -> Self {
12778 Self::CreateFunction(c)
12779 }
12780}
12781
12782impl From<CreateTrigger> for Statement {
12783 fn from(c: CreateTrigger) -> Self {
12784 Self::CreateTrigger(c)
12785 }
12786}
12787
12788impl From<DropTrigger> for Statement {
12789 fn from(d: DropTrigger) -> Self {
12790 Self::DropTrigger(d)
12791 }
12792}
12793
12794impl From<DropOperator> for Statement {
12795 fn from(d: DropOperator) -> Self {
12796 Self::DropOperator(d)
12797 }
12798}
12799
12800impl From<DropOperatorFamily> for Statement {
12801 fn from(d: DropOperatorFamily) -> Self {
12802 Self::DropOperatorFamily(d)
12803 }
12804}
12805
12806impl From<DropOperatorClass> for Statement {
12807 fn from(d: DropOperatorClass) -> Self {
12808 Self::DropOperatorClass(d)
12809 }
12810}
12811
12812impl From<DenyStatement> for Statement {
12813 fn from(d: DenyStatement) -> Self {
12814 Self::Deny(d)
12815 }
12816}
12817
12818impl From<CreateDomain> for Statement {
12819 fn from(c: CreateDomain) -> Self {
12820 Self::CreateDomain(c)
12821 }
12822}
12823
12824impl From<RenameTable> for Statement {
12825 fn from(r: RenameTable) -> Self {
12826 vec![r].into()
12827 }
12828}
12829
12830impl From<Vec<RenameTable>> for Statement {
12831 fn from(r: Vec<RenameTable>) -> Self {
12832 Self::RenameTable(r)
12833 }
12834}
12835
12836impl From<PrintStatement> for Statement {
12837 fn from(p: PrintStatement) -> Self {
12838 Self::Print(p)
12839 }
12840}
12841
12842impl From<ReturnStatement> for Statement {
12843 fn from(r: ReturnStatement) -> Self {
12844 Self::Return(r)
12845 }
12846}
12847
12848impl From<ExportData> for Statement {
12849 fn from(e: ExportData) -> Self {
12850 Self::ExportData(e)
12851 }
12852}
12853
12854impl From<CreateUser> for Statement {
12855 fn from(c: CreateUser) -> Self {
12856 Self::CreateUser(c)
12857 }
12858}
12859
12860impl From<CreateWarehouse> for Statement {
12861 fn from(c: CreateWarehouse) -> Self {
12862 Self::CreateWarehouse(c)
12863 }
12864}
12865
12866impl From<VacuumStatement> for Statement {
12867 fn from(v: VacuumStatement) -> Self {
12868 Self::Vacuum(v)
12869 }
12870}
12871
12872impl From<ResetStatement> for Statement {
12873 fn from(r: ResetStatement) -> Self {
12874 Self::Reset(r)
12875 }
12876}
12877
12878impl From<RefreshMaterializedView> for Statement {
12879 fn from(r: RefreshMaterializedView) -> Self {
12880 Self::RefreshMaterializedView(r)
12881 }
12882}
12883
12884#[cfg(test)]
12885mod tests {
12886 use crate::tokenizer::Location;
12887
12888 use super::*;
12889
12890 #[test]
12891 fn test_window_frame_default() {
12892 let window_frame = WindowFrame::default();
12893 assert_eq!(WindowFrameBound::Preceding(None), window_frame.start_bound);
12894 }
12895
12896 #[test]
12897 fn test_grouping_sets_display() {
12898 let grouping_sets = Expr::GroupingSets(vec![
12900 vec![Expr::Identifier(Ident::new("a"))],
12901 vec![Expr::Identifier(Ident::new("b"))],
12902 ]);
12903 assert_eq!("GROUPING SETS ((a), (b))", format!("{grouping_sets}"));
12904
12905 let grouping_sets = Expr::GroupingSets(vec![vec![
12907 Expr::Identifier(Ident::new("a")),
12908 Expr::Identifier(Ident::new("b")),
12909 ]]);
12910 assert_eq!("GROUPING SETS ((a, b))", format!("{grouping_sets}"));
12911
12912 let grouping_sets = Expr::GroupingSets(vec![
12914 vec![
12915 Expr::Identifier(Ident::new("a")),
12916 Expr::Identifier(Ident::new("b")),
12917 ],
12918 vec![
12919 Expr::Identifier(Ident::new("c")),
12920 Expr::Identifier(Ident::new("d")),
12921 ],
12922 ]);
12923 assert_eq!("GROUPING SETS ((a, b), (c, d))", format!("{grouping_sets}"));
12924 }
12925
12926 #[test]
12927 fn test_rollup_display() {
12928 let rollup = Expr::Rollup(vec![vec![Expr::Identifier(Ident::new("a"))]]);
12929 assert_eq!("ROLLUP (a)", format!("{rollup}"));
12930
12931 let rollup = Expr::Rollup(vec![vec![
12932 Expr::Identifier(Ident::new("a")),
12933 Expr::Identifier(Ident::new("b")),
12934 ]]);
12935 assert_eq!("ROLLUP ((a, b))", format!("{rollup}"));
12936
12937 let rollup = Expr::Rollup(vec![
12938 vec![Expr::Identifier(Ident::new("a"))],
12939 vec![Expr::Identifier(Ident::new("b"))],
12940 ]);
12941 assert_eq!("ROLLUP (a, b)", format!("{rollup}"));
12942
12943 let rollup = Expr::Rollup(vec![
12944 vec![Expr::Identifier(Ident::new("a"))],
12945 vec![
12946 Expr::Identifier(Ident::new("b")),
12947 Expr::Identifier(Ident::new("c")),
12948 ],
12949 vec![Expr::Identifier(Ident::new("d"))],
12950 ]);
12951 assert_eq!("ROLLUP (a, (b, c), d)", format!("{rollup}"));
12952 }
12953
12954 #[test]
12955 fn test_cube_display() {
12956 let cube = Expr::Cube(vec![vec![Expr::Identifier(Ident::new("a"))]]);
12957 assert_eq!("CUBE (a)", format!("{cube}"));
12958
12959 let cube = Expr::Cube(vec![vec![
12960 Expr::Identifier(Ident::new("a")),
12961 Expr::Identifier(Ident::new("b")),
12962 ]]);
12963 assert_eq!("CUBE ((a, b))", format!("{cube}"));
12964
12965 let cube = Expr::Cube(vec![
12966 vec![Expr::Identifier(Ident::new("a"))],
12967 vec![Expr::Identifier(Ident::new("b"))],
12968 ]);
12969 assert_eq!("CUBE (a, b)", format!("{cube}"));
12970
12971 let cube = Expr::Cube(vec![
12972 vec![Expr::Identifier(Ident::new("a"))],
12973 vec![
12974 Expr::Identifier(Ident::new("b")),
12975 Expr::Identifier(Ident::new("c")),
12976 ],
12977 vec![Expr::Identifier(Ident::new("d"))],
12978 ]);
12979 assert_eq!("CUBE (a, (b, c), d)", format!("{cube}"));
12980 }
12981
12982 #[test]
12983 fn test_interval_display() {
12984 let interval = Expr::Interval(Interval {
12985 value: Box::new(Expr::Value(
12986 Value::SingleQuotedString(String::from("123:45.67")).with_empty_span(),
12987 )),
12988 leading_field: Some(DateTimeField::Minute),
12989 leading_precision: Some(10),
12990 last_field: Some(DateTimeField::Second),
12991 fractional_seconds_precision: Some(9),
12992 });
12993 assert_eq!(
12994 "INTERVAL '123:45.67' MINUTE (10) TO SECOND (9)",
12995 format!("{interval}"),
12996 );
12997
12998 let interval = Expr::Interval(Interval {
12999 value: Box::new(Expr::Value(
13000 Value::SingleQuotedString(String::from("5")).with_empty_span(),
13001 )),
13002 leading_field: Some(DateTimeField::Second),
13003 leading_precision: Some(1),
13004 last_field: None,
13005 fractional_seconds_precision: Some(3),
13006 });
13007 assert_eq!("INTERVAL '5' SECOND (1, 3)", format!("{interval}"));
13008 }
13009
13010 #[test]
13011 fn test_one_or_many_with_parens_deref() {
13012 use core::ops::Index;
13013
13014 let one = OneOrManyWithParens::One("a");
13015
13016 assert_eq!(one.deref(), &["a"]);
13017 assert_eq!(<OneOrManyWithParens<_> as Deref>::deref(&one), &["a"]);
13018
13019 assert_eq!(one[0], "a");
13020 assert_eq!(one.index(0), &"a");
13021 assert_eq!(
13022 <<OneOrManyWithParens<_> as Deref>::Target as Index<usize>>::index(&one, 0),
13023 &"a"
13024 );
13025
13026 assert_eq!(one.len(), 1);
13027 assert_eq!(<OneOrManyWithParens<_> as Deref>::Target::len(&one), 1);
13028
13029 let many1 = OneOrManyWithParens::Many(vec!["b"]);
13030
13031 assert_eq!(many1.deref(), &["b"]);
13032 assert_eq!(<OneOrManyWithParens<_> as Deref>::deref(&many1), &["b"]);
13033
13034 assert_eq!(many1[0], "b");
13035 assert_eq!(many1.index(0), &"b");
13036 assert_eq!(
13037 <<OneOrManyWithParens<_> as Deref>::Target as Index<usize>>::index(&many1, 0),
13038 &"b"
13039 );
13040
13041 assert_eq!(many1.len(), 1);
13042 assert_eq!(<OneOrManyWithParens<_> as Deref>::Target::len(&many1), 1);
13043
13044 let many2 = OneOrManyWithParens::Many(vec!["c", "d"]);
13045
13046 assert_eq!(many2.deref(), &["c", "d"]);
13047 assert_eq!(
13048 <OneOrManyWithParens<_> as Deref>::deref(&many2),
13049 &["c", "d"]
13050 );
13051
13052 assert_eq!(many2[0], "c");
13053 assert_eq!(many2.index(0), &"c");
13054 assert_eq!(
13055 <<OneOrManyWithParens<_> as Deref>::Target as Index<usize>>::index(&many2, 0),
13056 &"c"
13057 );
13058
13059 assert_eq!(many2[1], "d");
13060 assert_eq!(many2.index(1), &"d");
13061 assert_eq!(
13062 <<OneOrManyWithParens<_> as Deref>::Target as Index<usize>>::index(&many2, 1),
13063 &"d"
13064 );
13065
13066 assert_eq!(many2.len(), 2);
13067 assert_eq!(<OneOrManyWithParens<_> as Deref>::Target::len(&many2), 2);
13068 }
13069
13070 #[test]
13071 fn test_one_or_many_with_parens_as_ref() {
13072 let one = OneOrManyWithParens::One("a");
13073
13074 assert_eq!(one.as_ref(), &["a"]);
13075 assert_eq!(<OneOrManyWithParens<_> as AsRef<_>>::as_ref(&one), &["a"]);
13076
13077 let many1 = OneOrManyWithParens::Many(vec!["b"]);
13078
13079 assert_eq!(many1.as_ref(), &["b"]);
13080 assert_eq!(<OneOrManyWithParens<_> as AsRef<_>>::as_ref(&many1), &["b"]);
13081
13082 let many2 = OneOrManyWithParens::Many(vec!["c", "d"]);
13083
13084 assert_eq!(many2.as_ref(), &["c", "d"]);
13085 assert_eq!(
13086 <OneOrManyWithParens<_> as AsRef<_>>::as_ref(&many2),
13087 &["c", "d"]
13088 );
13089 }
13090
13091 #[test]
13092 fn test_one_or_many_with_parens_ref_into_iter() {
13093 let one = OneOrManyWithParens::One("a");
13094
13095 assert_eq!(Vec::from_iter(&one), vec![&"a"]);
13096
13097 let many1 = OneOrManyWithParens::Many(vec!["b"]);
13098
13099 assert_eq!(Vec::from_iter(&many1), vec![&"b"]);
13100
13101 let many2 = OneOrManyWithParens::Many(vec!["c", "d"]);
13102
13103 assert_eq!(Vec::from_iter(&many2), vec![&"c", &"d"]);
13104 }
13105
13106 #[test]
13107 fn test_one_or_many_with_parens_value_into_iter() {
13108 use core::iter::once;
13109
13110 fn test_steps<I>(ours: OneOrManyWithParens<usize>, inner: I, n: usize)
13112 where
13113 I: IntoIterator<Item = usize, IntoIter: DoubleEndedIterator + Clone> + Clone,
13114 {
13115 fn checks<I>(ours: OneOrManyWithParensIntoIter<usize>, inner: I)
13116 where
13117 I: Iterator<Item = usize> + Clone + DoubleEndedIterator,
13118 {
13119 assert_eq!(ours.size_hint(), inner.size_hint());
13120 assert_eq!(ours.clone().count(), inner.clone().count());
13121
13122 assert_eq!(
13123 ours.clone().fold(1, |a, v| a + v),
13124 inner.clone().fold(1, |a, v| a + v)
13125 );
13126
13127 assert_eq!(Vec::from_iter(ours.clone()), Vec::from_iter(inner.clone()));
13128 assert_eq!(
13129 Vec::from_iter(ours.clone().rev()),
13130 Vec::from_iter(inner.clone().rev())
13131 );
13132 }
13133
13134 let mut ours_next = ours.clone().into_iter();
13135 let mut inner_next = inner.clone().into_iter();
13136
13137 for _ in 0..n {
13138 checks(ours_next.clone(), inner_next.clone());
13139
13140 assert_eq!(ours_next.next(), inner_next.next());
13141 }
13142
13143 let mut ours_next_back = ours.clone().into_iter();
13144 let mut inner_next_back = inner.clone().into_iter();
13145
13146 for _ in 0..n {
13147 checks(ours_next_back.clone(), inner_next_back.clone());
13148
13149 assert_eq!(ours_next_back.next_back(), inner_next_back.next_back());
13150 }
13151
13152 let mut ours_mixed = ours.clone().into_iter();
13153 let mut inner_mixed = inner.clone().into_iter();
13154
13155 for i in 0..n {
13156 checks(ours_mixed.clone(), inner_mixed.clone());
13157
13158 if i % 2 == 0 {
13159 assert_eq!(ours_mixed.next_back(), inner_mixed.next_back());
13160 } else {
13161 assert_eq!(ours_mixed.next(), inner_mixed.next());
13162 }
13163 }
13164
13165 let mut ours_mixed2 = ours.into_iter();
13166 let mut inner_mixed2 = inner.into_iter();
13167
13168 for i in 0..n {
13169 checks(ours_mixed2.clone(), inner_mixed2.clone());
13170
13171 if i % 2 == 0 {
13172 assert_eq!(ours_mixed2.next(), inner_mixed2.next());
13173 } else {
13174 assert_eq!(ours_mixed2.next_back(), inner_mixed2.next_back());
13175 }
13176 }
13177 }
13178
13179 test_steps(OneOrManyWithParens::One(1), once(1), 3);
13180 test_steps(OneOrManyWithParens::Many(vec![2]), vec![2], 3);
13181 test_steps(OneOrManyWithParens::Many(vec![3, 4]), vec![3, 4], 4);
13182 }
13183
13184 #[test]
13187 fn test_ident_ord() {
13188 let mut a = Ident::with_span(Span::new(Location::new(1, 1), Location::new(1, 1)), "a");
13189 let mut b = Ident::with_span(Span::new(Location::new(2, 2), Location::new(2, 2)), "b");
13190
13191 assert!(a < b);
13192 std::mem::swap(&mut a.span, &mut b.span);
13193 assert!(a < b);
13194 }
13195}