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 sqlparser_derive::{Visit, VisitMut};
44
45use crate::{
46 display_utils::SpaceOrNewline,
47 tokenizer::{Span, Token},
48};
49use crate::{
50 display_utils::{Indent, NewLine},
51 keywords::Keyword,
52};
53
54pub use self::data_type::{
55 ArrayElemTypeDef, BinaryLength, CharLengthUnits, CharacterLength, DataType, EnumMember,
56 ExactNumberInfo, IntervalFields, StructBracketKind, TimezoneInfo,
57};
58pub use self::dcl::{
59 AlterRoleOperation, CreateRole, Grant, ResetConfig, Revoke, RoleOption, SecondaryRoles,
60 SetConfigValue, Use,
61};
62pub use self::ddl::{
63 Alignment, AlterCollation, AlterCollationOperation, AlterColumnOperation, AlterColumnStorage,
64 AlterConnectorOwner, AlterFunction, AlterFunctionAction, AlterFunctionKind,
65 AlterFunctionOperation, AlterIndexOperation, AlterOperator, AlterOperatorClass,
66 AlterOperatorClassOperation, AlterOperatorFamily, AlterOperatorFamilyOperation,
67 AlterOperatorOperation, AlterPolicy, AlterPolicyOperation, AlterSchema, AlterSchemaOperation,
68 AlterTable, AlterTableAlgorithm, AlterTableLock, AlterTableOperation, AlterTableType,
69 AlterType, AlterTypeAddValue, AlterTypeAddValuePosition, AlterTypeOperation, AlterTypeRename,
70 AlterTypeRenameValue, ClusteredBy, ColumnDef, ColumnOption, ColumnOptionDef, ColumnOptions,
71 ColumnPolicy, ColumnPolicyProperty, ConstraintCharacteristics, CreateCollation,
72 CreateCollationDefinition, CreateConnector, CreateDomain, CreateExtension, CreateFunction,
73 CreateIndex, CreateOperator, CreateOperatorClass, CreateOperatorFamily, CreatePolicy,
74 CreatePolicyCommand, CreatePolicyType, CreateTable, CreateTrigger, CreateView, Deduplicate,
75 DeferrableInitial, DistStyle, DropBehavior, DropExtension, DropFunction, DropOperator,
76 DropOperatorClass, DropOperatorFamily, DropOperatorSignature, DropPolicy, DropTrigger,
77 ForValues, FunctionReturnType, GeneratedAs, GeneratedExpressionMode, IdentityParameters,
78 IdentityProperty, IdentityPropertyFormatKind, IdentityPropertyKind, IdentityPropertyOrder,
79 IndexColumn, IndexOption, IndexType, KeyOrIndexDisplay, Msck, NullsDistinctOption,
80 OperatorArgTypes, OperatorClassItem, OperatorFamilyDropItem, OperatorFamilyItem,
81 OperatorOption, OperatorPurpose, Owner, Partition, PartitionBoundValue, ProcedureParam,
82 ReferentialAction, RenameTableNameKind, ReplicaIdentity, TagsColumnOption, TriggerObjectKind,
83 Truncate, UserDefinedTypeCompositeAttributeDef, UserDefinedTypeInternalLength,
84 UserDefinedTypeRangeOption, UserDefinedTypeRepresentation, UserDefinedTypeSqlDefinitionOption,
85 UserDefinedTypeStorage, ViewColumnDef, WithData,
86};
87pub use self::dml::{
88 Delete, Insert, Merge, MergeAction, MergeClause, MergeClauseKind, MergeInsertExpr,
89 MergeInsertKind, MergeUpdateExpr, MergeUpdateKind, MultiTableInsertIntoClause,
90 MultiTableInsertType, MultiTableInsertValue, MultiTableInsertValues,
91 MultiTableInsertWhenClause, OutputClause, Update,
92};
93pub use self::operator::{BinaryOperator, UnaryOperator};
94pub use self::query::{
95 AfterMatchSkip, ConnectByKind, Cte, CteAsMaterialized, Distinct, EmptyMatchesMode,
96 ExceptSelectItem, ExcludeSelectItem, ExprWithAlias, ExprWithAliasAndOrderBy, Fetch, ForClause,
97 ForJson, ForXml, FormatClause, GroupByExpr, GroupByWithModifier, IdentWithAlias,
98 IlikeSelectItem, InputFormatClause, Interpolate, InterpolateExpr, Join, JoinConstraint,
99 JoinOperator, JsonTableColumn, JsonTableColumnErrorHandling, JsonTableNamedColumn,
100 JsonTableNestedColumn, LateralView, LimitClause, LockClause, LockType, MatchRecognizePattern,
101 MatchRecognizeSymbol, Measure, NamedWindowDefinition, NamedWindowExpr, NonBlock, Offset,
102 OffsetRows, OpenJsonTableColumn, OrderBy, OrderByExpr, OrderByKind, OrderByOptions,
103 OrderBySort, PipeOperator, PivotValueSource, ProjectionSelect, Query, RenameSelectItem,
104 RepetitionQuantifier, ReplaceSelectElement, ReplaceSelectItem, RowsPerMatch, Select,
105 SelectFlavor, SelectInto, SelectItem, SelectItemQualifiedWildcardKind, SelectModifiers,
106 SetExpr, SetOperator, SetQuantifier, Setting, SymbolDefinition, Table, TableAlias,
107 TableAliasColumnDef, TableFactor, TableFunctionArgs, TableIndexHintForClause,
108 TableIndexHintType, TableIndexHints, TableIndexType, TableSample, TableSampleBucket,
109 TableSampleKind, TableSampleMethod, TableSampleModifier, TableSampleQuantity, TableSampleSeed,
110 TableSampleSeedModifier, TableSampleUnit, TableVersion, TableWithJoins, Top, TopQuantity,
111 UpdateTableFromKind, ValueTableMode, Values, WildcardAdditionalOptions, With, WithFill,
112 XmlNamespaceDefinition, XmlPassingArgument, XmlPassingClause, XmlTableColumn,
113 XmlTableColumnOption,
114};
115
116pub use self::trigger::{
117 TriggerEvent, TriggerExecBody, TriggerExecBodyType, TriggerObject, TriggerPeriod,
118 TriggerReferencing, TriggerReferencingType,
119};
120
121pub use self::value::{
122 escape_double_quote_string, escape_quoted_string, DateTimeField, DollarQuotedString,
123 NormalizationForm, QuoteDelimitedString, TrimWhereField, Value, ValueWithSpan,
124};
125
126use crate::ast::helpers::key_value_options::KeyValueOptions;
127use crate::ast::helpers::stmt_data_loading::StageParamsObject;
128
129#[cfg(feature = "visitor")]
130pub use visitor::*;
131
132pub use self::data_type::GeometricTypeKind;
133
134mod data_type;
135mod dcl;
136mod ddl;
137mod dml;
138pub mod helpers;
140pub mod table_constraints;
141pub use table_constraints::{
142 CheckConstraint, ConstraintUsingIndex, ForeignKeyConstraint, FullTextOrSpatialConstraint,
143 IndexConstraint, PrimaryKeyConstraint, TableConstraint, UniqueConstraint,
144};
145mod operator;
146mod query;
147mod spans;
148pub use spans::Spanned;
149
150pub mod comments;
151mod trigger;
152mod value;
153
154#[cfg(feature = "visitor")]
155mod visitor;
156
157pub struct DisplaySeparated<'a, T>
159where
160 T: fmt::Display,
161{
162 slice: &'a [T],
163 sep: &'static str,
164}
165
166impl<T> fmt::Display for DisplaySeparated<'_, T>
167where
168 T: fmt::Display,
169{
170 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
171 let mut delim = "";
172 for t in self.slice {
173 f.write_str(delim)?;
174 delim = self.sep;
175 t.fmt(f)?;
176 }
177 Ok(())
178 }
179}
180
181pub(crate) fn display_separated<'a, T>(slice: &'a [T], sep: &'static str) -> DisplaySeparated<'a, T>
182where
183 T: fmt::Display,
184{
185 DisplaySeparated { slice, sep }
186}
187
188pub(crate) fn display_comma_separated<T>(slice: &[T]) -> DisplaySeparated<'_, T>
189where
190 T: fmt::Display,
191{
192 DisplaySeparated { slice, sep: ", " }
193}
194
195fn format_statement_list(f: &mut fmt::Formatter, statements: &[Statement]) -> fmt::Result {
198 write!(f, "{}", display_separated(statements, "; "))?;
199 write!(f, ";")
202}
203
204#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
206#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
207#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
208pub struct Parens<T> {
209 pub opening_token: AttachedToken,
211 pub content: T,
213 pub closing_token: AttachedToken,
215}
216
217impl<T> Parens<T> {
218 pub fn with_empty_span(content: T) -> Self {
221 Self {
222 opening_token: AttachedToken::empty(),
223 content,
224 closing_token: AttachedToken::empty(),
225 }
226 }
227}
228
229impl<T> Deref for Parens<T> {
230 type Target = T;
231
232 fn deref(&self) -> &Self::Target {
233 &self.content
234 }
235}
236
237impl<T> DerefMut for Parens<T> {
238 fn deref_mut(&mut self) -> &mut Self::Target {
239 &mut self.content
240 }
241}
242
243#[derive(Debug, Clone)]
245#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
246#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
247pub struct Ident {
248 pub value: String,
250 pub quote_style: Option<char>,
253 pub span: Span,
255}
256
257impl PartialEq for Ident {
258 fn eq(&self, other: &Self) -> bool {
259 let Ident {
260 value,
261 quote_style,
262 span: _,
264 } = self;
265
266 value == &other.value && quote_style == &other.quote_style
267 }
268}
269
270impl core::hash::Hash for Ident {
271 fn hash<H: hash::Hasher>(&self, state: &mut H) {
272 let Ident {
273 value,
274 quote_style,
275 span: _,
277 } = self;
278
279 value.hash(state);
280 quote_style.hash(state);
281 }
282}
283
284impl Eq for Ident {}
285
286impl PartialOrd for Ident {
287 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
288 Some(self.cmp(other))
289 }
290}
291
292impl Ord for Ident {
293 fn cmp(&self, other: &Self) -> Ordering {
294 let Ident {
295 value,
296 quote_style,
297 span: _,
299 } = self;
300
301 let Ident {
302 value: other_value,
303 quote_style: other_quote_style,
304 span: _,
306 } = other;
307
308 value
310 .cmp(other_value)
311 .then_with(|| quote_style.cmp(other_quote_style))
312 }
313}
314
315impl Ident {
316 pub fn new<S>(value: S) -> Self
318 where
319 S: Into<String>,
320 {
321 Ident {
322 value: value.into(),
323 quote_style: None,
324 span: Span::empty(),
325 }
326 }
327
328 pub fn with_quote<S>(quote: char, value: S) -> Self
331 where
332 S: Into<String>,
333 {
334 assert!(quote == '\'' || quote == '"' || quote == '`' || quote == '[');
335 Ident {
336 value: value.into(),
337 quote_style: Some(quote),
338 span: Span::empty(),
339 }
340 }
341
342 pub fn with_span<S>(span: Span, value: S) -> Self
344 where
345 S: Into<String>,
346 {
347 Ident {
348 value: value.into(),
349 quote_style: None,
350 span,
351 }
352 }
353
354 pub fn with_quote_and_span<S>(quote: char, span: Span, value: S) -> Self
356 where
357 S: Into<String>,
358 {
359 assert!(quote == '\'' || quote == '"' || quote == '`' || quote == '[');
360 Ident {
361 value: value.into(),
362 quote_style: Some(quote),
363 span,
364 }
365 }
366}
367
368impl From<&str> for Ident {
369 fn from(value: &str) -> Self {
370 Ident {
371 value: value.to_string(),
372 quote_style: None,
373 span: Span::empty(),
374 }
375 }
376}
377
378impl fmt::Display for Ident {
379 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
380 match self.quote_style {
381 Some(q) if q == '"' || q == '\'' || q == '`' => {
382 let escaped = value::escape_quoted_string(&self.value, q);
383 write!(f, "{q}{escaped}{q}")
384 }
385 Some('[') => write!(f, "[{}]", self.value),
386 None => f.write_str(&self.value),
387 _ => panic!("unexpected quote style"),
388 }
389 }
390}
391
392#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
394#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
395#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
396pub struct ObjectName(pub Vec<ObjectNamePart>);
397
398impl From<Vec<Ident>> for ObjectName {
399 fn from(idents: Vec<Ident>) -> Self {
400 ObjectName(idents.into_iter().map(ObjectNamePart::Identifier).collect())
401 }
402}
403
404impl From<Ident> for ObjectName {
405 fn from(ident: Ident) -> Self {
406 ObjectName(vec![ObjectNamePart::Identifier(ident)])
407 }
408}
409
410impl fmt::Display for ObjectName {
411 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
412 write!(f, "{}", display_separated(&self.0, "."))
413 }
414}
415
416#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
418#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
419#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
420pub enum ObjectNamePart {
421 Identifier(Ident),
423 Function(ObjectNamePartFunction),
425}
426
427impl ObjectNamePart {
428 pub fn as_ident(&self) -> Option<&Ident> {
430 match self {
431 ObjectNamePart::Identifier(ident) => Some(ident),
432 ObjectNamePart::Function(_) => None,
433 }
434 }
435}
436
437impl fmt::Display for ObjectNamePart {
438 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
439 match self {
440 ObjectNamePart::Identifier(ident) => write!(f, "{ident}"),
441 ObjectNamePart::Function(func) => write!(f, "{func}"),
442 }
443 }
444}
445
446#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
451#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
452#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
453pub struct ObjectNamePartFunction {
454 pub name: Ident,
456 pub args: Vec<FunctionArg>,
458}
459
460impl fmt::Display for ObjectNamePartFunction {
461 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
462 write!(f, "{}(", self.name)?;
463 write!(f, "{})", display_comma_separated(&self.args))
464 }
465}
466
467#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
470#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
471#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
472pub struct Array {
473 pub elem: Vec<Expr>,
475
476 pub named: bool,
478}
479
480impl fmt::Display for Array {
481 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
482 write!(
483 f,
484 "{}[{}]",
485 if self.named { "ARRAY" } else { "" },
486 display_comma_separated(&self.elem)
487 )
488 }
489}
490
491#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
500#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
501#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
502pub struct Interval {
503 pub value: Box<Expr>,
505 pub leading_field: Option<DateTimeField>,
507 pub leading_precision: Option<u64>,
509 pub last_field: Option<DateTimeField>,
511 pub fractional_seconds_precision: Option<u64>,
515}
516
517impl fmt::Display for Interval {
518 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
519 let value = self.value.as_ref();
520 match (
521 &self.leading_field,
522 self.leading_precision,
523 self.fractional_seconds_precision,
524 ) {
525 (
526 Some(DateTimeField::Second),
527 Some(leading_precision),
528 Some(fractional_seconds_precision),
529 ) => {
530 assert!(self.last_field.is_none());
533 write!(
534 f,
535 "INTERVAL {value} SECOND ({leading_precision}, {fractional_seconds_precision})"
536 )
537 }
538 _ => {
539 write!(f, "INTERVAL {value}")?;
540 if let Some(leading_field) = &self.leading_field {
541 write!(f, " {leading_field}")?;
542 }
543 if let Some(leading_precision) = self.leading_precision {
544 write!(f, " ({leading_precision})")?;
545 }
546 if let Some(last_field) = &self.last_field {
547 write!(f, " TO {last_field}")?;
548 }
549 if let Some(fractional_seconds_precision) = self.fractional_seconds_precision {
550 write!(f, " ({fractional_seconds_precision})")?;
551 }
552 Ok(())
553 }
554 }
555 }
556}
557
558#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
562#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
563#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
564pub struct StructField {
565 pub field_name: Option<Ident>,
567 pub field_type: DataType,
569 pub options: Option<Vec<SqlOption>>,
572}
573
574impl fmt::Display for StructField {
575 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
576 if let Some(name) = &self.field_name {
577 write!(f, "{name} {}", self.field_type)?;
578 } else {
579 write!(f, "{}", self.field_type)?;
580 }
581 if let Some(options) = &self.options {
582 write!(f, " OPTIONS({})", display_separated(options, ", "))
583 } else {
584 Ok(())
585 }
586 }
587}
588
589#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
593#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
594#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
595pub struct UnionField {
596 pub field_name: Ident,
598 pub field_type: DataType,
600}
601
602impl fmt::Display for UnionField {
603 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
604 write!(f, "{} {}", self.field_name, self.field_type)
605 }
606}
607
608#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
612#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
613#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
614pub struct DictionaryField {
615 pub key: Ident,
617 pub value: Box<Expr>,
619}
620
621impl fmt::Display for DictionaryField {
622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
623 write!(f, "{}: {}", self.key, self.value)
624 }
625}
626
627#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
629#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
630#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
631pub struct Map {
632 pub entries: Vec<MapEntry>,
634}
635
636impl Display for Map {
637 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
638 write!(f, "MAP {{{}}}", display_comma_separated(&self.entries))
639 }
640}
641
642#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
646#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
647#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
648pub struct MapEntry {
649 pub key: Box<Expr>,
651 pub value: Box<Expr>,
653}
654
655impl fmt::Display for MapEntry {
656 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
657 write!(f, "{}: {}", self.key, self.value)
658 }
659}
660
661#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
664#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
665#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
666pub enum CastFormat {
667 Value(ValueWithSpan),
669 ValueAtTimeZone(ValueWithSpan, ValueWithSpan),
671}
672
673#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
675#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
676#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
677pub enum JsonPathElem {
678 Dot {
682 key: String,
684 quoted: bool,
686 },
687 Bracket {
692 key: Expr,
694 },
695 ColonBracket {
700 key: Expr,
702 },
703}
704
705#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
710#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
711#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
712pub struct JsonPath {
713 pub path: Vec<JsonPathElem>,
715}
716
717impl fmt::Display for JsonPath {
718 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
719 for (i, elem) in self.path.iter().enumerate() {
720 match elem {
721 JsonPathElem::Dot { key, quoted } => {
722 if i == 0 {
723 write!(f, ":")?;
724 } else {
725 write!(f, ".")?;
726 }
727
728 if *quoted {
729 write!(f, "\"{}\"", escape_double_quote_string(key))?;
730 } else {
731 write!(f, "{key}")?;
732 }
733 }
734 JsonPathElem::Bracket { key } => {
735 write!(f, "[{key}]")?;
736 }
737 JsonPathElem::ColonBracket { key } => {
738 write!(f, ":[{key}]")?;
739 }
740 }
741 }
742 Ok(())
743 }
744}
745
746#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
748#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
749#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
750pub enum CastKind {
751 Cast,
753 TryCast,
758 SafeCast,
762 DoubleColon,
764}
765
766#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
770#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
771#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
772pub enum ConstraintReferenceMatchKind {
773 Full,
775 Partial,
777 Simple,
779}
780
781impl fmt::Display for ConstraintReferenceMatchKind {
782 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
783 match self {
784 Self::Full => write!(f, "MATCH FULL"),
785 Self::Partial => write!(f, "MATCH PARTIAL"),
786 Self::Simple => write!(f, "MATCH SIMPLE"),
787 }
788 }
789}
790
791#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
798#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
799#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
800pub enum ExtractSyntax {
801 From,
803 Comma,
805}
806
807#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
816#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
817#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
818pub enum CeilFloorKind {
819 DateTimeField(DateTimeField),
821 Scale(ValueWithSpan),
823}
824
825#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
828#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
829#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
830pub struct CaseWhen {
831 pub condition: Expr,
833 pub result: Expr,
835}
836
837impl fmt::Display for CaseWhen {
838 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
839 f.write_str("WHEN ")?;
840 self.condition.fmt(f)?;
841 f.write_str(" THEN")?;
842 SpaceOrNewline.fmt(f)?;
843 Indent(&self.result).fmt(f)?;
844 Ok(())
845 }
846}
847
848#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
866#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
867#[cfg_attr(
868 feature = "visitor",
869 derive(Visit, VisitMut),
870 visit(with = "visit_expr")
871)]
872pub enum Expr {
873 Identifier(Ident),
875 CompoundIdentifier(Vec<Ident>),
877 CompoundFieldAccess {
896 root: Box<Expr>,
898 access_chain: Vec<AccessExpr>,
900 },
901 JsonAccess {
907 value: Box<Expr>,
909 path: JsonPath,
911 },
912 IsFalse(Box<Expr>),
914 IsNotFalse(Box<Expr>),
916 IsTrue(Box<Expr>),
918 IsNotTrue(Box<Expr>),
920 IsNull(Box<Expr>),
922 IsNotNull(Box<Expr>),
924 IsUnknown(Box<Expr>),
926 IsNotUnknown(Box<Expr>),
928 IsDistinctFrom(Box<Expr>, Box<Expr>),
930 IsNotDistinctFrom(Box<Expr>, Box<Expr>),
932 IsNormalized {
934 expr: Box<Expr>,
936 form: Option<NormalizationForm>,
938 negated: bool,
940 },
941 InList {
943 expr: Box<Expr>,
945 list: Vec<Expr>,
947 negated: bool,
949 },
950 InSubquery {
952 expr: Box<Expr>,
954 subquery: Box<Query>,
956 negated: bool,
958 },
959 InUnnest {
961 expr: Box<Expr>,
963 array_expr: Box<Expr>,
965 negated: bool,
967 },
968 Between {
970 expr: Box<Expr>,
972 negated: bool,
974 low: Box<Expr>,
976 high: Box<Expr>,
978 },
979 BinaryOp {
981 left: Box<Expr>,
983 op: BinaryOperator,
985 right: Box<Expr>,
987 },
988 Like {
990 negated: bool,
992 any: bool,
995 expr: Box<Expr>,
997 pattern: Box<Expr>,
999 escape_char: Option<ValueWithSpan>,
1001 },
1002 ILike {
1004 negated: bool,
1006 any: bool,
1009 expr: Box<Expr>,
1011 pattern: Box<Expr>,
1013 escape_char: Option<ValueWithSpan>,
1015 },
1016 SimilarTo {
1018 negated: bool,
1020 expr: Box<Expr>,
1022 pattern: Box<Expr>,
1024 escape_char: Option<ValueWithSpan>,
1026 },
1027 RLike {
1029 negated: bool,
1031 expr: Box<Expr>,
1033 pattern: Box<Expr>,
1035 regexp: bool,
1037 },
1038 AnyOp {
1041 left: Box<Expr>,
1043 compare_op: BinaryOperator,
1045 right: Box<Expr>,
1047 is_some: bool,
1049 },
1050 AllOp {
1053 left: Box<Expr>,
1055 compare_op: BinaryOperator,
1057 right: Box<Expr>,
1059 },
1060
1061 UnaryOp {
1063 op: UnaryOperator,
1065 expr: Box<Expr>,
1067 },
1068 Convert {
1070 is_try: bool,
1073 expr: Box<Expr>,
1075 data_type: Option<DataType>,
1077 charset: Option<ObjectName>,
1079 target_before_value: bool,
1081 styles: Vec<Expr>,
1085 },
1086 Cast {
1088 kind: CastKind,
1090 expr: Box<Expr>,
1092 data_type: DataType,
1094 array: bool,
1100 format: Option<CastFormat>,
1104 },
1105 AtTimeZone {
1107 timestamp: Box<Expr>,
1109 time_zone: Box<Expr>,
1111 },
1112 Extract {
1120 field: DateTimeField,
1122 syntax: ExtractSyntax,
1124 expr: Box<Expr>,
1126 },
1127 Ceil {
1134 expr: Box<Expr>,
1136 field: CeilFloorKind,
1138 },
1139 Floor {
1146 expr: Box<Expr>,
1148 field: CeilFloorKind,
1150 },
1151 Position {
1155 expr: Box<Expr>,
1157 r#in: Box<Expr>,
1159 },
1160 Substring {
1168 expr: Box<Expr>,
1170 substring_from: Option<Box<Expr>>,
1172 substring_for: Option<Box<Expr>>,
1174
1175 special: bool,
1179
1180 shorthand: bool,
1183 },
1184 Trim {
1190 trim_where: Option<TrimWhereField>,
1192 trim_what: Option<Box<Expr>>,
1194 expr: Box<Expr>,
1196 trim_characters: Option<Vec<Expr>>,
1198 },
1199 Overlay {
1203 expr: Box<Expr>,
1205 overlay_what: Box<Expr>,
1207 overlay_from: Box<Expr>,
1209 overlay_for: Option<Box<Expr>>,
1211 },
1212 Collate {
1214 expr: Box<Expr>,
1216 collation: ObjectName,
1218 },
1219 Nested(Box<Expr>),
1221 Value(ValueWithSpan),
1223 Prefixed {
1227 prefix: Ident,
1229 value: Box<Expr>,
1232 },
1233 TypedString(TypedString),
1237 Function(Function),
1239 Case {
1245 case_token: AttachedToken,
1247 end_token: AttachedToken,
1249 operand: Option<Box<Expr>>,
1251 conditions: Vec<CaseWhen>,
1253 else_result: Option<Box<Expr>>,
1255 },
1256 Exists {
1259 subquery: Box<Query>,
1261 negated: bool,
1263 },
1264 Subquery(Box<Query>),
1267 GroupingSets(Vec<Vec<Expr>>),
1269 Cube(Vec<Vec<Expr>>),
1271 Rollup(Vec<Vec<Expr>>),
1273 Tuple(Vec<Expr>),
1275 Struct {
1284 values: Vec<Expr>,
1286 fields: Vec<StructField>,
1288 },
1289 Named {
1297 expr: Box<Expr>,
1299 name: Ident,
1301 },
1302 Dictionary(Vec<DictionaryField>),
1310 Map(Map),
1318 Array(Array),
1320 Interval(Interval),
1322 MatchAgainst {
1333 columns: Vec<ObjectName>,
1335 match_value: ValueWithSpan,
1337 opt_search_modifier: Option<SearchModifier>,
1339 },
1340 Wildcard(AttachedToken),
1342 QualifiedWildcard(ObjectName, AttachedToken),
1345 OuterJoin(Box<Expr>),
1360 Prior(Box<Expr>),
1362 Lambda(LambdaFunction),
1373 MemberOf(MemberOf),
1375}
1376
1377impl Expr {
1378 pub fn value(value: impl Into<ValueWithSpan>) -> Self {
1380 Expr::Value(value.into())
1381 }
1382}
1383
1384#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1386#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1387#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1388pub enum Subscript {
1389 Index {
1391 index: Expr,
1393 },
1394
1395 Slice {
1417 lower_bound: Option<Expr>,
1419 upper_bound: Option<Expr>,
1421 stride: Option<Expr>,
1423 },
1424}
1425
1426impl fmt::Display for Subscript {
1427 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1428 match self {
1429 Subscript::Index { index } => write!(f, "{index}"),
1430 Subscript::Slice {
1431 lower_bound,
1432 upper_bound,
1433 stride,
1434 } => {
1435 if let Some(lower) = lower_bound {
1436 write!(f, "{lower}")?;
1437 }
1438 write!(f, ":")?;
1439 if let Some(upper) = upper_bound {
1440 write!(f, "{upper}")?;
1441 }
1442 if let Some(stride) = stride {
1443 write!(f, ":")?;
1444 write!(f, "{stride}")?;
1445 }
1446 Ok(())
1447 }
1448 }
1449 }
1450}
1451
1452#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1455#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1456#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1457pub enum AccessExpr {
1458 Dot(Expr),
1460 Subscript(Subscript),
1462}
1463
1464impl fmt::Display for AccessExpr {
1465 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1466 match self {
1467 AccessExpr::Dot(expr) => write!(f, ".{expr}"),
1468 AccessExpr::Subscript(subscript) => write!(f, "[{subscript}]"),
1469 }
1470 }
1471}
1472
1473#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1475#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1476#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1477pub struct LambdaFunction {
1478 pub params: OneOrManyWithParens<LambdaFunctionParameter>,
1480 pub body: Box<Expr>,
1482 pub syntax: LambdaSyntax,
1484}
1485
1486impl fmt::Display for LambdaFunction {
1487 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1488 match self.syntax {
1489 LambdaSyntax::Arrow => write!(f, "{} -> {}", self.params, self.body),
1490 LambdaSyntax::LambdaKeyword => {
1491 write!(f, "lambda ")?;
1494 match &self.params {
1495 OneOrManyWithParens::One(p) => write!(f, "{p}")?,
1496 OneOrManyWithParens::Many(ps) => write!(f, "{}", display_comma_separated(ps))?,
1497 };
1498 write!(f, " : {}", self.body)
1499 }
1500 }
1501 }
1502}
1503
1504#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1506#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1507#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1508pub struct LambdaFunctionParameter {
1509 pub name: Ident,
1511 pub data_type: Option<DataType>,
1514}
1515
1516impl fmt::Display for LambdaFunctionParameter {
1517 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1518 match &self.data_type {
1519 Some(dt) => write!(f, "{} {}", self.name, dt),
1520 None => write!(f, "{}", self.name),
1521 }
1522 }
1523}
1524
1525#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Copy)]
1527#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1528#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1529pub enum LambdaSyntax {
1530 Arrow,
1537 LambdaKeyword,
1542}
1543
1544#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1567#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1568#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1569pub enum OneOrManyWithParens<T> {
1570 One(T),
1572 Many(Vec<T>),
1574}
1575
1576impl<T> Deref for OneOrManyWithParens<T> {
1577 type Target = [T];
1578
1579 fn deref(&self) -> &[T] {
1580 match self {
1581 OneOrManyWithParens::One(one) => core::slice::from_ref(one),
1582 OneOrManyWithParens::Many(many) => many,
1583 }
1584 }
1585}
1586
1587impl<T> AsRef<[T]> for OneOrManyWithParens<T> {
1588 fn as_ref(&self) -> &[T] {
1589 self
1590 }
1591}
1592
1593impl<'a, T> IntoIterator for &'a OneOrManyWithParens<T> {
1594 type Item = &'a T;
1595 type IntoIter = core::slice::Iter<'a, T>;
1596
1597 fn into_iter(self) -> Self::IntoIter {
1598 self.iter()
1599 }
1600}
1601
1602#[derive(Debug, Clone)]
1604pub struct OneOrManyWithParensIntoIter<T> {
1605 inner: OneOrManyWithParensIntoIterInner<T>,
1606}
1607
1608#[derive(Debug, Clone)]
1609enum OneOrManyWithParensIntoIterInner<T> {
1610 One(core::iter::Once<T>),
1611 Many(<Vec<T> as IntoIterator>::IntoIter),
1612}
1613
1614impl<T> core::iter::FusedIterator for OneOrManyWithParensIntoIter<T>
1615where
1616 core::iter::Once<T>: core::iter::FusedIterator,
1617 <Vec<T> as IntoIterator>::IntoIter: core::iter::FusedIterator,
1618{
1619}
1620
1621impl<T> core::iter::ExactSizeIterator for OneOrManyWithParensIntoIter<T>
1622where
1623 core::iter::Once<T>: core::iter::ExactSizeIterator,
1624 <Vec<T> as IntoIterator>::IntoIter: core::iter::ExactSizeIterator,
1625{
1626}
1627
1628impl<T> core::iter::Iterator for OneOrManyWithParensIntoIter<T> {
1629 type Item = T;
1630
1631 fn next(&mut self) -> Option<Self::Item> {
1632 match &mut self.inner {
1633 OneOrManyWithParensIntoIterInner::One(one) => one.next(),
1634 OneOrManyWithParensIntoIterInner::Many(many) => many.next(),
1635 }
1636 }
1637
1638 fn size_hint(&self) -> (usize, Option<usize>) {
1639 match &self.inner {
1640 OneOrManyWithParensIntoIterInner::One(one) => one.size_hint(),
1641 OneOrManyWithParensIntoIterInner::Many(many) => many.size_hint(),
1642 }
1643 }
1644
1645 fn count(self) -> usize
1646 where
1647 Self: Sized,
1648 {
1649 match self.inner {
1650 OneOrManyWithParensIntoIterInner::One(one) => one.count(),
1651 OneOrManyWithParensIntoIterInner::Many(many) => many.count(),
1652 }
1653 }
1654
1655 fn fold<B, F>(mut self, init: B, f: F) -> B
1656 where
1657 Self: Sized,
1658 F: FnMut(B, Self::Item) -> B,
1659 {
1660 match &mut self.inner {
1661 OneOrManyWithParensIntoIterInner::One(one) => one.fold(init, f),
1662 OneOrManyWithParensIntoIterInner::Many(many) => many.fold(init, f),
1663 }
1664 }
1665}
1666
1667impl<T> core::iter::DoubleEndedIterator for OneOrManyWithParensIntoIter<T> {
1668 fn next_back(&mut self) -> Option<Self::Item> {
1669 match &mut self.inner {
1670 OneOrManyWithParensIntoIterInner::One(one) => one.next_back(),
1671 OneOrManyWithParensIntoIterInner::Many(many) => many.next_back(),
1672 }
1673 }
1674}
1675
1676impl<T> IntoIterator for OneOrManyWithParens<T> {
1677 type Item = T;
1678
1679 type IntoIter = OneOrManyWithParensIntoIter<T>;
1680
1681 fn into_iter(self) -> Self::IntoIter {
1682 let inner = match self {
1683 OneOrManyWithParens::One(one) => {
1684 OneOrManyWithParensIntoIterInner::One(core::iter::once(one))
1685 }
1686 OneOrManyWithParens::Many(many) => {
1687 OneOrManyWithParensIntoIterInner::Many(many.into_iter())
1688 }
1689 };
1690
1691 OneOrManyWithParensIntoIter { inner }
1692 }
1693}
1694
1695impl<T> fmt::Display for OneOrManyWithParens<T>
1696where
1697 T: fmt::Display,
1698{
1699 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1700 match self {
1701 OneOrManyWithParens::One(value) => write!(f, "{value}"),
1702 OneOrManyWithParens::Many(values) => {
1703 write!(f, "({})", display_comma_separated(values))
1704 }
1705 }
1706 }
1707}
1708
1709impl fmt::Display for CastFormat {
1710 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1711 match self {
1712 CastFormat::Value(v) => write!(f, "{v}"),
1713 CastFormat::ValueAtTimeZone(v, tz) => write!(f, "{v} AT TIME ZONE {tz}"),
1714 }
1715 }
1716}
1717
1718impl fmt::Display for Expr {
1719 #[cfg_attr(feature = "recursive-protection", recursive::recursive)]
1720 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1721 match self {
1722 Expr::Identifier(s) => write!(f, "{s}"),
1723 Expr::Wildcard(_) => f.write_str("*"),
1724 Expr::QualifiedWildcard(prefix, _) => write!(f, "{prefix}.*"),
1725 Expr::CompoundIdentifier(s) => write!(f, "{}", display_separated(s, ".")),
1726 Expr::CompoundFieldAccess { root, access_chain } => {
1727 write!(f, "{root}")?;
1728 for field in access_chain {
1729 write!(f, "{field}")?;
1730 }
1731 Ok(())
1732 }
1733 Expr::IsTrue(ast) => write!(f, "{ast} IS TRUE"),
1734 Expr::IsNotTrue(ast) => write!(f, "{ast} IS NOT TRUE"),
1735 Expr::IsFalse(ast) => write!(f, "{ast} IS FALSE"),
1736 Expr::IsNotFalse(ast) => write!(f, "{ast} IS NOT FALSE"),
1737 Expr::IsNull(ast) => write!(f, "{ast} IS NULL"),
1738 Expr::IsNotNull(ast) => write!(f, "{ast} IS NOT NULL"),
1739 Expr::IsUnknown(ast) => write!(f, "{ast} IS UNKNOWN"),
1740 Expr::IsNotUnknown(ast) => write!(f, "{ast} IS NOT UNKNOWN"),
1741 Expr::InList {
1742 expr,
1743 list,
1744 negated,
1745 } => write!(
1746 f,
1747 "{} {}IN ({})",
1748 expr,
1749 if *negated { "NOT " } else { "" },
1750 display_comma_separated(list)
1751 ),
1752 Expr::InSubquery {
1753 expr,
1754 subquery,
1755 negated,
1756 } => write!(
1757 f,
1758 "{} {}IN ({})",
1759 expr,
1760 if *negated { "NOT " } else { "" },
1761 subquery
1762 ),
1763 Expr::InUnnest {
1764 expr,
1765 array_expr,
1766 negated,
1767 } => write!(
1768 f,
1769 "{} {}IN UNNEST({})",
1770 expr,
1771 if *negated { "NOT " } else { "" },
1772 array_expr
1773 ),
1774 Expr::Between {
1775 expr,
1776 negated,
1777 low,
1778 high,
1779 } => write!(
1780 f,
1781 "{} {}BETWEEN {} AND {}",
1782 expr,
1783 if *negated { "NOT " } else { "" },
1784 low,
1785 high
1786 ),
1787 Expr::BinaryOp { left, op, right } => write!(f, "{left} {op} {right}"),
1788 Expr::Like {
1789 negated,
1790 expr,
1791 pattern,
1792 escape_char,
1793 any,
1794 } => match escape_char {
1795 Some(ch) => write!(
1796 f,
1797 "{} {}LIKE {}{} ESCAPE {}",
1798 expr,
1799 if *negated { "NOT " } else { "" },
1800 if *any { "ANY " } else { "" },
1801 pattern,
1802 ch
1803 ),
1804 _ => write!(
1805 f,
1806 "{} {}LIKE {}{}",
1807 expr,
1808 if *negated { "NOT " } else { "" },
1809 if *any { "ANY " } else { "" },
1810 pattern
1811 ),
1812 },
1813 Expr::ILike {
1814 negated,
1815 expr,
1816 pattern,
1817 escape_char,
1818 any,
1819 } => match escape_char {
1820 Some(ch) => write!(
1821 f,
1822 "{} {}ILIKE {}{} ESCAPE {}",
1823 expr,
1824 if *negated { "NOT " } else { "" },
1825 if *any { "ANY" } else { "" },
1826 pattern,
1827 ch
1828 ),
1829 _ => write!(
1830 f,
1831 "{} {}ILIKE {}{}",
1832 expr,
1833 if *negated { "NOT " } else { "" },
1834 if *any { "ANY " } else { "" },
1835 pattern
1836 ),
1837 },
1838 Expr::RLike {
1839 negated,
1840 expr,
1841 pattern,
1842 regexp,
1843 } => write!(
1844 f,
1845 "{} {}{} {}",
1846 expr,
1847 if *negated { "NOT " } else { "" },
1848 if *regexp { "REGEXP" } else { "RLIKE" },
1849 pattern
1850 ),
1851 Expr::IsNormalized {
1852 expr,
1853 form,
1854 negated,
1855 } => {
1856 let not_ = if *negated { "NOT " } else { "" };
1857 if let Some(form) = form {
1858 write!(f, "{} IS {}{} NORMALIZED", expr, not_, form)
1859 } else {
1860 write!(f, "{expr} IS {not_}NORMALIZED")
1861 }
1862 }
1863 Expr::SimilarTo {
1864 negated,
1865 expr,
1866 pattern,
1867 escape_char,
1868 } => match escape_char {
1869 Some(ch) => write!(
1870 f,
1871 "{} {}SIMILAR TO {} ESCAPE {}",
1872 expr,
1873 if *negated { "NOT " } else { "" },
1874 pattern,
1875 ch
1876 ),
1877 _ => write!(
1878 f,
1879 "{} {}SIMILAR TO {}",
1880 expr,
1881 if *negated { "NOT " } else { "" },
1882 pattern
1883 ),
1884 },
1885 Expr::AnyOp {
1886 left,
1887 compare_op,
1888 right,
1889 is_some,
1890 } => {
1891 let add_parens = !matches!(right.as_ref(), Expr::Subquery(_));
1892 write!(
1893 f,
1894 "{left} {compare_op} {}{}{right}{}",
1895 if *is_some { "SOME" } else { "ANY" },
1896 if add_parens { "(" } else { "" },
1897 if add_parens { ")" } else { "" },
1898 )
1899 }
1900 Expr::AllOp {
1901 left,
1902 compare_op,
1903 right,
1904 } => {
1905 let add_parens = !matches!(right.as_ref(), Expr::Subquery(_));
1906 write!(
1907 f,
1908 "{left} {compare_op} ALL{}{right}{}",
1909 if add_parens { "(" } else { "" },
1910 if add_parens { ")" } else { "" },
1911 )
1912 }
1913 Expr::UnaryOp { op, expr } => {
1914 if op == &UnaryOperator::PGPostfixFactorial {
1915 write!(f, "{expr}{op}")
1916 } else if matches!(
1917 op,
1918 UnaryOperator::Not
1919 | UnaryOperator::Hash
1920 | UnaryOperator::AtDashAt
1921 | UnaryOperator::DoubleAt
1922 | UnaryOperator::QuestionDash
1923 | UnaryOperator::QuestionPipe
1924 ) {
1925 write!(f, "{op} {expr}")
1926 } else {
1927 write!(f, "{op}{expr}")
1928 }
1929 }
1930 Expr::Convert {
1931 is_try,
1932 expr,
1933 target_before_value,
1934 data_type,
1935 charset,
1936 styles,
1937 } => {
1938 write!(f, "{}CONVERT(", if *is_try { "TRY_" } else { "" })?;
1939 if let Some(data_type) = data_type {
1940 if let Some(charset) = charset {
1941 write!(f, "{expr}, {data_type} CHARACTER SET {charset}")
1942 } else if *target_before_value {
1943 write!(f, "{data_type}, {expr}")
1944 } else {
1945 write!(f, "{expr}, {data_type}")
1946 }
1947 } else if let Some(charset) = charset {
1948 write!(f, "{expr} USING {charset}")
1949 } else {
1950 write!(f, "{expr}") }?;
1952 if !styles.is_empty() {
1953 write!(f, ", {}", display_comma_separated(styles))?;
1954 }
1955 write!(f, ")")
1956 }
1957 Expr::Cast {
1958 kind,
1959 expr,
1960 data_type,
1961 array,
1962 format,
1963 } => match kind {
1964 CastKind::Cast => {
1965 write!(f, "CAST({expr} AS {data_type}")?;
1966 if *array {
1967 write!(f, " ARRAY")?;
1968 }
1969 if let Some(format) = format {
1970 write!(f, " FORMAT {format}")?;
1971 }
1972 write!(f, ")")
1973 }
1974 CastKind::TryCast => {
1975 if let Some(format) = format {
1976 write!(f, "TRY_CAST({expr} AS {data_type} FORMAT {format})")
1977 } else {
1978 write!(f, "TRY_CAST({expr} AS {data_type})")
1979 }
1980 }
1981 CastKind::SafeCast => {
1982 if let Some(format) = format {
1983 write!(f, "SAFE_CAST({expr} AS {data_type} FORMAT {format})")
1984 } else {
1985 write!(f, "SAFE_CAST({expr} AS {data_type})")
1986 }
1987 }
1988 CastKind::DoubleColon => {
1989 write!(f, "{expr}::{data_type}")
1990 }
1991 },
1992 Expr::Extract {
1993 field,
1994 syntax,
1995 expr,
1996 } => match syntax {
1997 ExtractSyntax::From => write!(f, "EXTRACT({field} FROM {expr})"),
1998 ExtractSyntax::Comma => write!(f, "EXTRACT({field}, {expr})"),
1999 },
2000 Expr::Ceil { expr, field } => match field {
2001 CeilFloorKind::DateTimeField(DateTimeField::NoDateTime) => {
2002 write!(f, "CEIL({expr})")
2003 }
2004 CeilFloorKind::DateTimeField(dt_field) => write!(f, "CEIL({expr} TO {dt_field})"),
2005 CeilFloorKind::Scale(s) => write!(f, "CEIL({expr}, {s})"),
2006 },
2007 Expr::Floor { expr, field } => match field {
2008 CeilFloorKind::DateTimeField(DateTimeField::NoDateTime) => {
2009 write!(f, "FLOOR({expr})")
2010 }
2011 CeilFloorKind::DateTimeField(dt_field) => write!(f, "FLOOR({expr} TO {dt_field})"),
2012 CeilFloorKind::Scale(s) => write!(f, "FLOOR({expr}, {s})"),
2013 },
2014 Expr::Position { expr, r#in } => write!(f, "POSITION({expr} IN {in})"),
2015 Expr::Collate { expr, collation } => write!(f, "{expr} COLLATE {collation}"),
2016 Expr::Nested(ast) => write!(f, "({ast})"),
2017 Expr::Value(v) => write!(f, "{v}"),
2018 Expr::Prefixed { prefix, value } => write!(f, "{prefix} {value}"),
2019 Expr::TypedString(ts) => ts.fmt(f),
2020 Expr::Function(fun) => fun.fmt(f),
2021 Expr::Case {
2022 case_token: _,
2023 end_token: _,
2024 operand,
2025 conditions,
2026 else_result,
2027 } => {
2028 f.write_str("CASE")?;
2029 if let Some(operand) = operand {
2030 f.write_str(" ")?;
2031 operand.fmt(f)?;
2032 }
2033 for when in conditions {
2034 SpaceOrNewline.fmt(f)?;
2035 Indent(when).fmt(f)?;
2036 }
2037 if let Some(else_result) = else_result {
2038 SpaceOrNewline.fmt(f)?;
2039 Indent("ELSE").fmt(f)?;
2040 SpaceOrNewline.fmt(f)?;
2041 Indent(Indent(else_result)).fmt(f)?;
2042 }
2043 SpaceOrNewline.fmt(f)?;
2044 f.write_str("END")
2045 }
2046 Expr::Exists { subquery, negated } => write!(
2047 f,
2048 "{}EXISTS ({})",
2049 if *negated { "NOT " } else { "" },
2050 subquery
2051 ),
2052 Expr::Subquery(s) => write!(f, "({s})"),
2053 Expr::GroupingSets(sets) => {
2054 write!(f, "GROUPING SETS (")?;
2055 let mut sep = "";
2056 for set in sets {
2057 write!(f, "{sep}")?;
2058 sep = ", ";
2059 write!(f, "({})", display_comma_separated(set))?;
2060 }
2061 write!(f, ")")
2062 }
2063 Expr::Cube(sets) => {
2064 write!(f, "CUBE (")?;
2065 let mut sep = "";
2066 for set in sets {
2067 write!(f, "{sep}")?;
2068 sep = ", ";
2069 if set.len() == 1 {
2070 write!(f, "{}", set[0])?;
2071 } else {
2072 write!(f, "({})", display_comma_separated(set))?;
2073 }
2074 }
2075 write!(f, ")")
2076 }
2077 Expr::Rollup(sets) => {
2078 write!(f, "ROLLUP (")?;
2079 let mut sep = "";
2080 for set in sets {
2081 write!(f, "{sep}")?;
2082 sep = ", ";
2083 if set.len() == 1 {
2084 write!(f, "{}", set[0])?;
2085 } else {
2086 write!(f, "({})", display_comma_separated(set))?;
2087 }
2088 }
2089 write!(f, ")")
2090 }
2091 Expr::Substring {
2092 expr,
2093 substring_from,
2094 substring_for,
2095 special,
2096 shorthand,
2097 } => {
2098 f.write_str("SUBSTR")?;
2099 if !*shorthand {
2100 f.write_str("ING")?;
2101 }
2102 write!(f, "({expr}")?;
2103 if let Some(from_part) = substring_from {
2104 if *special {
2105 write!(f, ", {from_part}")?;
2106 } else {
2107 write!(f, " FROM {from_part}")?;
2108 }
2109 }
2110 if let Some(for_part) = substring_for {
2111 if *special {
2112 write!(f, ", {for_part}")?;
2113 } else {
2114 write!(f, " FOR {for_part}")?;
2115 }
2116 }
2117
2118 write!(f, ")")
2119 }
2120 Expr::Overlay {
2121 expr,
2122 overlay_what,
2123 overlay_from,
2124 overlay_for,
2125 } => {
2126 write!(
2127 f,
2128 "OVERLAY({expr} PLACING {overlay_what} FROM {overlay_from}"
2129 )?;
2130 if let Some(for_part) = overlay_for {
2131 write!(f, " FOR {for_part}")?;
2132 }
2133
2134 write!(f, ")")
2135 }
2136 Expr::IsDistinctFrom(a, b) => write!(f, "{a} IS DISTINCT FROM {b}"),
2137 Expr::IsNotDistinctFrom(a, b) => write!(f, "{a} IS NOT DISTINCT FROM {b}"),
2138 Expr::Trim {
2139 expr,
2140 trim_where,
2141 trim_what,
2142 trim_characters,
2143 } => {
2144 write!(f, "TRIM(")?;
2145 if let Some(ident) = trim_where {
2146 write!(f, "{ident} ")?;
2147 }
2148 if let Some(trim_char) = trim_what {
2149 write!(f, "{trim_char} FROM {expr}")?;
2150 } else {
2151 write!(f, "{expr}")?;
2152 }
2153 if let Some(characters) = trim_characters {
2154 write!(f, ", {}", display_comma_separated(characters))?;
2155 }
2156
2157 write!(f, ")")
2158 }
2159 Expr::Tuple(exprs) => {
2160 write!(f, "({})", display_comma_separated(exprs))
2161 }
2162 Expr::Struct { values, fields } => {
2163 if !fields.is_empty() {
2164 write!(
2165 f,
2166 "STRUCT<{}>({})",
2167 display_comma_separated(fields),
2168 display_comma_separated(values)
2169 )
2170 } else {
2171 write!(f, "STRUCT({})", display_comma_separated(values))
2172 }
2173 }
2174 Expr::Named { expr, name } => {
2175 write!(f, "{expr} AS {name}")
2176 }
2177 Expr::Dictionary(fields) => {
2178 write!(f, "{{{}}}", display_comma_separated(fields))
2179 }
2180 Expr::Map(map) => {
2181 write!(f, "{map}")
2182 }
2183 Expr::Array(set) => {
2184 write!(f, "{set}")
2185 }
2186 Expr::JsonAccess { value, path } => {
2187 write!(f, "{value}{path}")
2188 }
2189 Expr::AtTimeZone {
2190 timestamp,
2191 time_zone,
2192 } => {
2193 write!(f, "{timestamp} AT TIME ZONE {time_zone}")
2194 }
2195 Expr::Interval(interval) => {
2196 write!(f, "{interval}")
2197 }
2198 Expr::MatchAgainst {
2199 columns,
2200 match_value: match_expr,
2201 opt_search_modifier,
2202 } => {
2203 write!(f, "MATCH ({}) AGAINST ", display_comma_separated(columns),)?;
2204
2205 if let Some(search_modifier) = opt_search_modifier {
2206 write!(f, "({match_expr} {search_modifier})")?;
2207 } else {
2208 write!(f, "({match_expr})")?;
2209 }
2210
2211 Ok(())
2212 }
2213 Expr::OuterJoin(expr) => {
2214 write!(f, "{expr} (+)")
2215 }
2216 Expr::Prior(expr) => write!(f, "PRIOR {expr}"),
2217 Expr::Lambda(lambda) => write!(f, "{lambda}"),
2218 Expr::MemberOf(member_of) => write!(f, "{member_of}"),
2219 }
2220 }
2221}
2222
2223#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2232#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2233#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2234pub enum WindowType {
2235 WindowSpec(WindowSpec),
2237 NamedWindow(Ident),
2239}
2240
2241impl Display for WindowType {
2242 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2243 match self {
2244 WindowType::WindowSpec(spec) => {
2245 f.write_str("(")?;
2246 NewLine.fmt(f)?;
2247 Indent(spec).fmt(f)?;
2248 NewLine.fmt(f)?;
2249 f.write_str(")")
2250 }
2251 WindowType::NamedWindow(name) => name.fmt(f),
2252 }
2253 }
2254}
2255
2256#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2258#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2259#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2260pub struct WindowSpec {
2261 pub window_name: Option<Ident>,
2269 pub partition_by: Vec<Expr>,
2271 pub order_by: Vec<OrderByExpr>,
2273 pub window_frame: Option<WindowFrame>,
2275}
2276
2277impl fmt::Display for WindowSpec {
2278 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2279 let mut is_first = true;
2280 if let Some(window_name) = &self.window_name {
2281 if !is_first {
2282 SpaceOrNewline.fmt(f)?;
2283 }
2284 is_first = false;
2285 write!(f, "{window_name}")?;
2286 }
2287 if !self.partition_by.is_empty() {
2288 if !is_first {
2289 SpaceOrNewline.fmt(f)?;
2290 }
2291 is_first = false;
2292 write!(
2293 f,
2294 "PARTITION BY {}",
2295 display_comma_separated(&self.partition_by)
2296 )?;
2297 }
2298 if !self.order_by.is_empty() {
2299 if !is_first {
2300 SpaceOrNewline.fmt(f)?;
2301 }
2302 is_first = false;
2303 write!(f, "ORDER BY {}", display_comma_separated(&self.order_by))?;
2304 }
2305 if let Some(window_frame) = &self.window_frame {
2306 if !is_first {
2307 SpaceOrNewline.fmt(f)?;
2308 }
2309 if let Some(end_bound) = &window_frame.end_bound {
2310 write!(
2311 f,
2312 "{} BETWEEN {} AND {}",
2313 window_frame.units, window_frame.start_bound, end_bound
2314 )?;
2315 } else {
2316 write!(f, "{} {}", window_frame.units, window_frame.start_bound)?;
2317 }
2318 }
2319 Ok(())
2320 }
2321}
2322
2323#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2329#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2330#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2331pub struct WindowFrame {
2332 pub units: WindowFrameUnits,
2334 pub start_bound: WindowFrameBound,
2336 pub end_bound: Option<WindowFrameBound>,
2340 }
2342
2343impl Default for WindowFrame {
2344 fn default() -> Self {
2348 Self {
2349 units: WindowFrameUnits::Range,
2350 start_bound: WindowFrameBound::Preceding(None),
2351 end_bound: None,
2352 }
2353 }
2354}
2355
2356#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2357#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2358#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2359pub enum WindowFrameUnits {
2361 Rows,
2363 Range,
2365 Groups,
2367}
2368
2369impl fmt::Display for WindowFrameUnits {
2370 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2371 f.write_str(match self {
2372 WindowFrameUnits::Rows => "ROWS",
2373 WindowFrameUnits::Range => "RANGE",
2374 WindowFrameUnits::Groups => "GROUPS",
2375 })
2376 }
2377}
2378
2379#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2383#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2384#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2385pub enum NullTreatment {
2387 IgnoreNulls,
2389 RespectNulls,
2391}
2392
2393impl fmt::Display for NullTreatment {
2394 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2395 f.write_str(match self {
2396 NullTreatment::IgnoreNulls => "IGNORE NULLS",
2397 NullTreatment::RespectNulls => "RESPECT NULLS",
2398 })
2399 }
2400}
2401
2402#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2404#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2405#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2406pub enum WindowFrameBound {
2407 CurrentRow,
2409 Preceding(Option<Box<Expr>>),
2411 Following(Option<Box<Expr>>),
2413}
2414
2415impl fmt::Display for WindowFrameBound {
2416 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2417 match self {
2418 WindowFrameBound::CurrentRow => f.write_str("CURRENT ROW"),
2419 WindowFrameBound::Preceding(None) => f.write_str("UNBOUNDED PRECEDING"),
2420 WindowFrameBound::Following(None) => f.write_str("UNBOUNDED FOLLOWING"),
2421 WindowFrameBound::Preceding(Some(n)) => write!(f, "{n} PRECEDING"),
2422 WindowFrameBound::Following(Some(n)) => write!(f, "{n} FOLLOWING"),
2423 }
2424 }
2425}
2426
2427#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2428#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2429#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2430pub enum AddDropSync {
2432 ADD,
2434 DROP,
2436 SYNC,
2438}
2439
2440impl fmt::Display for AddDropSync {
2441 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2442 match self {
2443 AddDropSync::SYNC => f.write_str("SYNC PARTITIONS"),
2444 AddDropSync::DROP => f.write_str("DROP PARTITIONS"),
2445 AddDropSync::ADD => f.write_str("ADD PARTITIONS"),
2446 }
2447 }
2448}
2449
2450#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2451#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2452#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2453pub enum ShowCreateObject {
2455 Event,
2457 Function,
2459 Procedure,
2461 Table,
2463 Trigger,
2465 View,
2467}
2468
2469impl fmt::Display for ShowCreateObject {
2470 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2471 match self {
2472 ShowCreateObject::Event => f.write_str("EVENT"),
2473 ShowCreateObject::Function => f.write_str("FUNCTION"),
2474 ShowCreateObject::Procedure => f.write_str("PROCEDURE"),
2475 ShowCreateObject::Table => f.write_str("TABLE"),
2476 ShowCreateObject::Trigger => f.write_str("TRIGGER"),
2477 ShowCreateObject::View => f.write_str("VIEW"),
2478 }
2479 }
2480}
2481
2482#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2483#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2484#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2485pub enum CommentObject {
2487 Collation,
2489 Column,
2491 Database,
2493 Domain,
2495 Extension,
2497 Function,
2499 Index,
2501 MaterializedView,
2503 Procedure,
2505 Role,
2507 Schema,
2509 Sequence,
2511 Table,
2513 Type,
2515 User,
2517 View,
2519}
2520
2521impl fmt::Display for CommentObject {
2522 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2523 match self {
2524 CommentObject::Collation => f.write_str("COLLATION"),
2525 CommentObject::Column => f.write_str("COLUMN"),
2526 CommentObject::Database => f.write_str("DATABASE"),
2527 CommentObject::Domain => f.write_str("DOMAIN"),
2528 CommentObject::Extension => f.write_str("EXTENSION"),
2529 CommentObject::Function => f.write_str("FUNCTION"),
2530 CommentObject::Index => f.write_str("INDEX"),
2531 CommentObject::MaterializedView => f.write_str("MATERIALIZED VIEW"),
2532 CommentObject::Procedure => f.write_str("PROCEDURE"),
2533 CommentObject::Role => f.write_str("ROLE"),
2534 CommentObject::Schema => f.write_str("SCHEMA"),
2535 CommentObject::Sequence => f.write_str("SEQUENCE"),
2536 CommentObject::Table => f.write_str("TABLE"),
2537 CommentObject::Type => f.write_str("TYPE"),
2538 CommentObject::User => f.write_str("USER"),
2539 CommentObject::View => f.write_str("VIEW"),
2540 }
2541 }
2542}
2543
2544#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2545#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2546#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2547pub enum Password {
2549 Password(Expr),
2551 NullPassword,
2553}
2554
2555#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2572#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2573#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2574pub struct CaseStatement {
2575 pub case_token: AttachedToken,
2577 pub match_expr: Option<Expr>,
2579 pub when_blocks: Vec<ConditionalStatementBlock>,
2581 pub else_block: Option<ConditionalStatementBlock>,
2583 pub end_case_token: AttachedToken,
2585}
2586
2587impl fmt::Display for CaseStatement {
2588 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2589 let CaseStatement {
2590 case_token: _,
2591 match_expr,
2592 when_blocks,
2593 else_block,
2594 end_case_token: AttachedToken(end),
2595 } = self;
2596
2597 write!(f, "CASE")?;
2598
2599 if let Some(expr) = match_expr {
2600 write!(f, " {expr}")?;
2601 }
2602
2603 if !when_blocks.is_empty() {
2604 write!(f, " {}", display_separated(when_blocks, " "))?;
2605 }
2606
2607 if let Some(else_block) = else_block {
2608 write!(f, " {else_block}")?;
2609 }
2610
2611 write!(f, " END")?;
2612
2613 if let Token::Word(w) = &end.token {
2614 if w.keyword == Keyword::CASE {
2615 write!(f, " CASE")?;
2616 }
2617 }
2618
2619 Ok(())
2620 }
2621}
2622
2623#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2645#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2646#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2647pub struct IfStatement {
2648 pub if_block: ConditionalStatementBlock,
2650 pub elseif_blocks: Vec<ConditionalStatementBlock>,
2652 pub else_block: Option<ConditionalStatementBlock>,
2654 pub end_token: Option<AttachedToken>,
2656}
2657
2658impl fmt::Display for IfStatement {
2659 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2660 let IfStatement {
2661 if_block,
2662 elseif_blocks,
2663 else_block,
2664 end_token,
2665 } = self;
2666
2667 write!(f, "{if_block}")?;
2668
2669 for elseif_block in elseif_blocks {
2670 write!(f, " {elseif_block}")?;
2671 }
2672
2673 if let Some(else_block) = else_block {
2674 write!(f, " {else_block}")?;
2675 }
2676
2677 if let Some(AttachedToken(end_token)) = end_token {
2678 write!(f, " END {end_token}")?;
2679 }
2680
2681 Ok(())
2682 }
2683}
2684
2685#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2697#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2698#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2699pub struct WhileStatement {
2700 pub while_block: ConditionalStatementBlock,
2702}
2703
2704impl fmt::Display for WhileStatement {
2705 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2706 let WhileStatement { while_block } = self;
2707 write!(f, "{while_block}")?;
2708 Ok(())
2709 }
2710}
2711
2712#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2737#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2738#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2739pub struct ConditionalStatementBlock {
2740 pub start_token: AttachedToken,
2742 pub condition: Option<Expr>,
2744 pub then_token: Option<AttachedToken>,
2746 pub conditional_statements: ConditionalStatements,
2748}
2749
2750impl ConditionalStatementBlock {
2751 pub fn statements(&self) -> &Vec<Statement> {
2753 self.conditional_statements.statements()
2754 }
2755}
2756
2757impl fmt::Display for ConditionalStatementBlock {
2758 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2759 let ConditionalStatementBlock {
2760 start_token: AttachedToken(start_token),
2761 condition,
2762 then_token,
2763 conditional_statements,
2764 } = self;
2765
2766 write!(f, "{start_token}")?;
2767
2768 if let Some(condition) = condition {
2769 write!(f, " {condition}")?;
2770 }
2771
2772 if then_token.is_some() {
2773 write!(f, " THEN")?;
2774 }
2775
2776 if !conditional_statements.statements().is_empty() {
2777 write!(f, " {conditional_statements}")?;
2778 }
2779
2780 Ok(())
2781 }
2782}
2783
2784#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2786#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2787#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2788pub enum ConditionalStatements {
2790 Sequence {
2792 statements: Vec<Statement>,
2794 },
2795 BeginEnd(BeginEndStatements),
2797}
2798
2799impl ConditionalStatements {
2800 pub fn statements(&self) -> &Vec<Statement> {
2802 match self {
2803 ConditionalStatements::Sequence { statements } => statements,
2804 ConditionalStatements::BeginEnd(bes) => &bes.statements,
2805 }
2806 }
2807}
2808
2809impl fmt::Display for ConditionalStatements {
2810 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2811 match self {
2812 ConditionalStatements::Sequence { statements } => {
2813 if !statements.is_empty() {
2814 format_statement_list(f, statements)?;
2815 }
2816 Ok(())
2817 }
2818 ConditionalStatements::BeginEnd(bes) => write!(f, "{bes}"),
2819 }
2820 }
2821}
2822
2823#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2832#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2833#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2834pub struct BeginEndStatements {
2835 pub begin_token: AttachedToken,
2837 pub statements: Vec<Statement>,
2839 pub end_token: AttachedToken,
2841}
2842
2843impl fmt::Display for BeginEndStatements {
2844 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2845 let BeginEndStatements {
2846 begin_token: AttachedToken(begin_token),
2847 statements,
2848 end_token: AttachedToken(end_token),
2849 } = self;
2850
2851 if begin_token.token != Token::EOF {
2852 write!(f, "{begin_token} ")?;
2853 }
2854 if !statements.is_empty() {
2855 format_statement_list(f, statements)?;
2856 }
2857 if end_token.token != Token::EOF {
2858 write!(f, " {end_token}")?;
2859 }
2860 Ok(())
2861 }
2862}
2863
2864#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2876#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2877#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2878pub struct RaiseStatement {
2879 pub value: Option<RaiseStatementValue>,
2881}
2882
2883impl fmt::Display for RaiseStatement {
2884 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2885 let RaiseStatement { value } = self;
2886
2887 write!(f, "RAISE")?;
2888 if let Some(value) = value {
2889 write!(f, " {value}")?;
2890 }
2891
2892 Ok(())
2893 }
2894}
2895
2896#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2898#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2899#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2900pub enum RaiseStatementValue {
2901 UsingMessage(Expr),
2903 Expr(Expr),
2905}
2906
2907impl fmt::Display for RaiseStatementValue {
2908 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2909 match self {
2910 RaiseStatementValue::Expr(expr) => write!(f, "{expr}"),
2911 RaiseStatementValue::UsingMessage(expr) => write!(f, "USING MESSAGE = {expr}"),
2912 }
2913 }
2914}
2915
2916#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2924#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2925#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2926pub struct ThrowStatement {
2927 pub error_number: Option<Box<Expr>>,
2929 pub message: Option<Box<Expr>>,
2931 pub state: Option<Box<Expr>>,
2933}
2934
2935impl fmt::Display for ThrowStatement {
2936 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2937 let ThrowStatement {
2938 error_number,
2939 message,
2940 state,
2941 } = self;
2942
2943 write!(f, "THROW")?;
2944 if let (Some(error_number), Some(message), Some(state)) = (error_number, message, state) {
2945 write!(f, " {error_number}, {message}, {state}")?;
2946 }
2947 Ok(())
2948 }
2949}
2950
2951#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2959#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2960#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2961pub enum DeclareAssignment {
2962 Expr(Box<Expr>),
2964
2965 Default(Box<Expr>),
2967
2968 DuckAssignment(Box<Expr>),
2975
2976 For(Box<Expr>),
2983
2984 MsSqlAssignment(Box<Expr>),
2991}
2992
2993impl fmt::Display for DeclareAssignment {
2994 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2995 match self {
2996 DeclareAssignment::Expr(expr) => {
2997 write!(f, "{expr}")
2998 }
2999 DeclareAssignment::Default(expr) => {
3000 write!(f, "DEFAULT {expr}")
3001 }
3002 DeclareAssignment::DuckAssignment(expr) => {
3003 write!(f, ":= {expr}")
3004 }
3005 DeclareAssignment::MsSqlAssignment(expr) => {
3006 write!(f, "= {expr}")
3007 }
3008 DeclareAssignment::For(expr) => {
3009 write!(f, "FOR {expr}")
3010 }
3011 }
3012 }
3013}
3014
3015#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3017#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3018#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3019pub enum DeclareType {
3020 Cursor,
3026
3027 ResultSet,
3035
3036 Exception,
3044}
3045
3046impl fmt::Display for DeclareType {
3047 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3048 match self {
3049 DeclareType::Cursor => {
3050 write!(f, "CURSOR")
3051 }
3052 DeclareType::ResultSet => {
3053 write!(f, "RESULTSET")
3054 }
3055 DeclareType::Exception => {
3056 write!(f, "EXCEPTION")
3057 }
3058 }
3059 }
3060}
3061
3062#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3075#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3076#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3077pub struct Declare {
3078 pub names: Vec<Ident>,
3081 pub data_type: Option<DataType>,
3084 pub assignment: Option<DeclareAssignment>,
3086 pub declare_type: Option<DeclareType>,
3088 pub binary: Option<bool>,
3090 pub sensitive: Option<bool>,
3094 pub scroll: Option<bool>,
3098 pub hold: Option<bool>,
3102 pub for_query: Option<Box<Query>>,
3104}
3105
3106impl fmt::Display for Declare {
3107 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3108 let Declare {
3109 names,
3110 data_type,
3111 assignment,
3112 declare_type,
3113 binary,
3114 sensitive,
3115 scroll,
3116 hold,
3117 for_query,
3118 } = self;
3119 write!(f, "{}", display_comma_separated(names))?;
3120
3121 if let Some(true) = binary {
3122 write!(f, " BINARY")?;
3123 }
3124
3125 if let Some(sensitive) = sensitive {
3126 if *sensitive {
3127 write!(f, " INSENSITIVE")?;
3128 } else {
3129 write!(f, " ASENSITIVE")?;
3130 }
3131 }
3132
3133 if let Some(scroll) = scroll {
3134 if *scroll {
3135 write!(f, " SCROLL")?;
3136 } else {
3137 write!(f, " NO SCROLL")?;
3138 }
3139 }
3140
3141 if let Some(declare_type) = declare_type {
3142 write!(f, " {declare_type}")?;
3143 }
3144
3145 if let Some(hold) = hold {
3146 if *hold {
3147 write!(f, " WITH HOLD")?;
3148 } else {
3149 write!(f, " WITHOUT HOLD")?;
3150 }
3151 }
3152
3153 if let Some(query) = for_query {
3154 write!(f, " FOR {query}")?;
3155 }
3156
3157 if let Some(data_type) = data_type {
3158 write!(f, " {data_type}")?;
3159 }
3160
3161 if let Some(expr) = assignment {
3162 write!(f, " {expr}")?;
3163 }
3164 Ok(())
3165 }
3166}
3167
3168#[derive(Debug, Default, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3170#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3171#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3172pub enum CreateTableOptions {
3174 #[default]
3176 None,
3177 With(Vec<SqlOption>),
3179 Options(Vec<SqlOption>),
3181 Plain(Vec<SqlOption>),
3183 TableProperties(Vec<SqlOption>),
3185}
3186
3187impl fmt::Display for CreateTableOptions {
3188 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3189 match self {
3190 CreateTableOptions::With(with_options) => {
3191 write!(f, "WITH ({})", display_comma_separated(with_options))
3192 }
3193 CreateTableOptions::Options(options) => {
3194 write!(f, "OPTIONS({})", display_comma_separated(options))
3195 }
3196 CreateTableOptions::TableProperties(options) => {
3197 write!(f, "TBLPROPERTIES ({})", display_comma_separated(options))
3198 }
3199 CreateTableOptions::Plain(options) => {
3200 write!(f, "{}", display_separated(options, " "))
3201 }
3202 CreateTableOptions::None => Ok(()),
3203 }
3204 }
3205}
3206
3207#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3214#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3215#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3216pub enum FromTable {
3217 WithFromKeyword(Vec<TableWithJoins>),
3219 WithoutKeyword(Vec<TableWithJoins>),
3222}
3223impl Display for FromTable {
3224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3225 match self {
3226 FromTable::WithFromKeyword(tables) => {
3227 write!(f, "FROM {}", display_comma_separated(tables))
3228 }
3229 FromTable::WithoutKeyword(tables) => {
3230 write!(f, "{}", display_comma_separated(tables))
3231 }
3232 }
3233 }
3234}
3235
3236#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3237#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3238#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3239pub enum Set {
3241 SingleAssignment {
3245 scope: Option<ContextModifier>,
3247 hivevar: bool,
3249 variable: ObjectName,
3251 values: Vec<Expr>,
3253 },
3254 ParenthesizedAssignments {
3258 variables: Vec<ObjectName>,
3260 values: Vec<Expr>,
3262 },
3263 MultipleAssignments {
3267 assignments: Vec<SetAssignment>,
3269 },
3270 SetSessionAuthorization(SetSessionAuthorizationParam),
3279 SetSessionParam(SetSessionParamKind),
3283 SetRole {
3294 context_modifier: Option<ContextModifier>,
3296 role_name: Option<Ident>,
3298 },
3299 SetTimeZone {
3309 local: bool,
3311 value: Expr,
3313 },
3314 SetNames {
3318 charset_name: Ident,
3320 collation_name: Option<String>,
3322 },
3323 SetNamesDefault {},
3329 SetTransaction {
3333 modes: Vec<TransactionMode>,
3335 snapshot: Option<ValueWithSpan>,
3337 session: bool,
3339 },
3340}
3341
3342impl Display for Set {
3343 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3344 match self {
3345 Self::ParenthesizedAssignments { variables, values } => write!(
3346 f,
3347 "SET ({}) = ({})",
3348 display_comma_separated(variables),
3349 display_comma_separated(values)
3350 ),
3351 Self::MultipleAssignments { assignments } => {
3352 write!(f, "SET {}", display_comma_separated(assignments))
3353 }
3354 Self::SetRole {
3355 context_modifier,
3356 role_name,
3357 } => {
3358 let role_name = role_name.clone().unwrap_or_else(|| Ident::new("NONE"));
3359 write!(
3360 f,
3361 "SET {modifier}ROLE {role_name}",
3362 modifier = context_modifier.map(|m| format!("{m}")).unwrap_or_default()
3363 )
3364 }
3365 Self::SetSessionAuthorization(kind) => write!(f, "SET SESSION AUTHORIZATION {kind}"),
3366 Self::SetSessionParam(kind) => write!(f, "SET {kind}"),
3367 Self::SetTransaction {
3368 modes,
3369 snapshot,
3370 session,
3371 } => {
3372 if *session {
3373 write!(f, "SET SESSION CHARACTERISTICS AS TRANSACTION")?;
3374 } else {
3375 write!(f, "SET TRANSACTION")?;
3376 }
3377 if !modes.is_empty() {
3378 write!(f, " {}", display_comma_separated(modes))?;
3379 }
3380 if let Some(snapshot_id) = snapshot {
3381 write!(f, " SNAPSHOT {snapshot_id}")?;
3382 }
3383 Ok(())
3384 }
3385 Self::SetTimeZone { local, value } => {
3386 f.write_str("SET ")?;
3387 if *local {
3388 f.write_str("LOCAL ")?;
3389 }
3390 write!(f, "TIME ZONE {value}")
3391 }
3392 Self::SetNames {
3393 charset_name,
3394 collation_name,
3395 } => {
3396 write!(f, "SET NAMES {charset_name}")?;
3397
3398 if let Some(collation) = collation_name {
3399 f.write_str(" COLLATE ")?;
3400 f.write_str(collation)?;
3401 };
3402
3403 Ok(())
3404 }
3405 Self::SetNamesDefault {} => {
3406 f.write_str("SET NAMES DEFAULT")?;
3407
3408 Ok(())
3409 }
3410 Set::SingleAssignment {
3411 scope,
3412 hivevar,
3413 variable,
3414 values,
3415 } => {
3416 write!(
3417 f,
3418 "SET {}{}{} = {}",
3419 scope.map(|s| format!("{s}")).unwrap_or_default(),
3420 if *hivevar { "HIVEVAR:" } else { "" },
3421 variable,
3422 display_comma_separated(values)
3423 )
3424 }
3425 }
3426 }
3427}
3428
3429#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3435#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3436#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3437pub struct ExceptionWhen {
3438 pub idents: Vec<Ident>,
3440 pub statements: Vec<Statement>,
3442}
3443
3444impl Display for ExceptionWhen {
3445 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3446 write!(
3447 f,
3448 "WHEN {idents} THEN",
3449 idents = display_separated(&self.idents, " OR ")
3450 )?;
3451
3452 if !self.statements.is_empty() {
3453 write!(f, " ")?;
3454 format_statement_list(f, &self.statements)?;
3455 }
3456
3457 Ok(())
3458 }
3459}
3460
3461#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3468#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3469#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3470pub struct Analyze {
3471 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3472 pub table_name: Option<ObjectName>,
3474 pub partitions: Option<Vec<Expr>>,
3476 pub for_columns: bool,
3478 pub columns: Vec<Ident>,
3480 pub cache_metadata: bool,
3482 pub noscan: bool,
3484 pub compute_statistics: bool,
3486 pub has_table_keyword: bool,
3488}
3489
3490impl fmt::Display for Analyze {
3491 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3492 write!(f, "ANALYZE")?;
3493 if let Some(ref table_name) = self.table_name {
3494 if self.has_table_keyword {
3495 write!(f, " TABLE")?;
3496 }
3497 write!(f, " {table_name}")?;
3498 }
3499 if !self.for_columns && !self.columns.is_empty() {
3500 write!(f, " ({})", display_comma_separated(&self.columns))?;
3501 }
3502 if let Some(ref parts) = self.partitions {
3503 if !parts.is_empty() {
3504 write!(f, " PARTITION ({})", display_comma_separated(parts))?;
3505 }
3506 }
3507 if self.compute_statistics {
3508 write!(f, " COMPUTE STATISTICS")?;
3509 }
3510 if self.noscan {
3511 write!(f, " NOSCAN")?;
3512 }
3513 if self.cache_metadata {
3514 write!(f, " CACHE METADATA")?;
3515 }
3516 if self.for_columns {
3517 write!(f, " FOR COLUMNS")?;
3518 if !self.columns.is_empty() {
3519 write!(f, " {}", display_comma_separated(&self.columns))?;
3520 }
3521 }
3522 Ok(())
3523 }
3524}
3525
3526#[allow(clippy::large_enum_variant)]
3528#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3529#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3530#[cfg_attr(
3531 feature = "visitor",
3532 derive(Visit, VisitMut),
3533 visit(with = "visit_statement")
3534)]
3535pub enum Statement {
3536 Analyze(Analyze),
3541 Set(Set),
3543 Truncate(Truncate),
3548 Msck(Msck),
3553 Query(Box<Query>),
3557 Insert(Insert),
3561 Install {
3565 extension_name: Ident,
3567 },
3568 Load {
3572 extension_name: Ident,
3574 },
3575 Directory {
3578 overwrite: bool,
3580 local: bool,
3582 path: String,
3584 file_format: Option<FileFormat>,
3586 source: Box<Query>,
3588 },
3589 Case(CaseStatement),
3591 If(IfStatement),
3593 While(WhileStatement),
3595 Raise(RaiseStatement),
3597 Call(Function),
3601 Copy {
3605 source: CopySource,
3607 to: bool,
3609 target: CopyTarget,
3611 options: Vec<CopyOption>,
3613 legacy_options: Vec<CopyLegacyOption>,
3615 values: Vec<Option<String>>,
3617 },
3618 CopyIntoSnowflake {
3630 kind: CopyIntoSnowflakeKind,
3632 into: ObjectName,
3634 into_columns: Option<Vec<Ident>>,
3636 from_obj: Option<ObjectName>,
3638 from_obj_alias: Option<Ident>,
3640 stage_params: StageParamsObject,
3642 from_transformations: Option<Vec<StageLoadSelectItemKind>>,
3644 from_query: Option<Box<Query>>,
3646 files: Option<Vec<String>>,
3648 pattern: Option<String>,
3650 file_format: KeyValueOptions,
3652 copy_options: KeyValueOptions,
3654 validation_mode: Option<String>,
3656 partition: Option<Box<Expr>>,
3658 },
3659 Open(OpenStatement),
3664 Close {
3669 cursor: CloseCursor,
3671 },
3672 Update(Update),
3676 Delete(Delete),
3680 CreateView(CreateView),
3684 CreateTable(CreateTable),
3688 CreateVirtualTable {
3693 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3694 name: ObjectName,
3696 if_not_exists: bool,
3698 module_name: Ident,
3700 module_args: Vec<Ident>,
3702 },
3703 CreateIndex(CreateIndex),
3707 CreateRole(CreateRole),
3712 CreateSecret {
3717 or_replace: bool,
3719 temporary: Option<bool>,
3721 if_not_exists: bool,
3723 name: Option<Ident>,
3725 storage_specifier: Option<Ident>,
3727 secret_type: Ident,
3729 options: Vec<SecretOption>,
3731 },
3732 CreateServer(CreateServerStatement),
3734 CreatePolicy(CreatePolicy),
3739 CreateConnector(CreateConnector),
3744 CreateOperator(CreateOperator),
3749 CreateOperatorFamily(CreateOperatorFamily),
3754 CreateOperatorClass(CreateOperatorClass),
3759 AlterTable(AlterTable),
3763 AlterSchema(AlterSchema),
3768 AlterIndex {
3772 name: ObjectName,
3774 operation: AlterIndexOperation,
3776 },
3777 AlterView {
3781 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
3783 name: ObjectName,
3784 columns: Vec<Ident>,
3786 query: Box<Query>,
3788 with_options: Vec<SqlOption>,
3790 },
3791 AlterFunction(AlterFunction),
3798 AlterType(AlterType),
3803 AlterCollation(AlterCollation),
3808 AlterOperator(AlterOperator),
3813 AlterOperatorFamily(AlterOperatorFamily),
3818 AlterOperatorClass(AlterOperatorClass),
3823 AlterRole {
3827 name: Ident,
3829 operation: AlterRoleOperation,
3831 },
3832 AlterPolicy(AlterPolicy),
3837 AlterConnector {
3846 name: Ident,
3848 properties: Option<Vec<SqlOption>>,
3850 url: Option<String>,
3852 owner: Option<ddl::AlterConnectorOwner>,
3854 },
3855 AlterSession {
3861 set: bool,
3863 session_params: KeyValueOptions,
3865 },
3866 AttachDatabase {
3871 schema_name: Ident,
3873 database_file_name: Expr,
3875 database: bool,
3877 },
3878 AttachDuckDBDatabase {
3884 if_not_exists: bool,
3886 database: bool,
3888 database_path: Ident,
3890 database_alias: Option<Ident>,
3892 attach_options: Vec<AttachDuckDBDatabaseOption>,
3894 },
3895 DetachDuckDBDatabase {
3901 if_exists: bool,
3903 database: bool,
3905 database_alias: Ident,
3907 },
3908 Drop {
3912 object_type: ObjectType,
3914 if_exists: bool,
3916 names: Vec<ObjectName>,
3918 cascade: bool,
3921 restrict: bool,
3924 purge: bool,
3927 temporary: bool,
3929 table: Option<ObjectName>,
3932 },
3933 DropFunction(DropFunction),
3937 DropDomain(DropDomain),
3945 DropProcedure {
3949 if_exists: bool,
3951 proc_desc: Vec<FunctionDesc>,
3953 drop_behavior: Option<DropBehavior>,
3955 },
3956 DropSecret {
3960 if_exists: bool,
3962 temporary: Option<bool>,
3964 name: Ident,
3966 storage_specifier: Option<Ident>,
3968 },
3969 DropPolicy(DropPolicy),
3974 DropConnector {
3979 if_exists: bool,
3981 name: Ident,
3983 },
3984 Declare {
3992 stmts: Vec<Declare>,
3994 },
3995 CreateExtension(CreateExtension),
4004 CreateCollation(CreateCollation),
4010 DropExtension(DropExtension),
4016 DropOperator(DropOperator),
4022 DropOperatorFamily(DropOperatorFamily),
4028 DropOperatorClass(DropOperatorClass),
4034 Fetch {
4042 name: Ident,
4044 direction: FetchDirection,
4046 position: FetchPosition,
4048 into: Option<ObjectName>,
4050 },
4051 Flush {
4058 object_type: FlushType,
4060 location: Option<FlushLocation>,
4062 channel: Option<String>,
4064 read_lock: bool,
4066 export: bool,
4068 tables: Vec<ObjectName>,
4070 },
4071 Discard {
4078 object_type: DiscardObject,
4080 },
4081 ShowFunctions {
4085 filter: Option<ShowStatementFilter>,
4087 },
4088 ShowVariable {
4094 variable: Vec<Ident>,
4096 },
4097 ShowStatus {
4103 filter: Option<ShowStatementFilter>,
4105 global: bool,
4107 session: bool,
4109 },
4110 ShowVariables {
4116 filter: Option<ShowStatementFilter>,
4118 global: bool,
4120 session: bool,
4122 },
4123 ShowCreate {
4129 obj_type: ShowCreateObject,
4131 obj_name: ObjectName,
4133 },
4134 ShowColumns {
4138 extended: bool,
4140 full: bool,
4142 show_options: ShowStatementOptions,
4144 },
4145 ShowCatalogs {
4149 terse: bool,
4151 history: bool,
4153 show_options: ShowStatementOptions,
4155 },
4156 ShowDatabases {
4160 terse: bool,
4162 history: bool,
4164 show_options: ShowStatementOptions,
4166 },
4167 ShowProcessList {
4173 full: bool,
4175 },
4176 ShowSchemas {
4180 terse: bool,
4182 history: bool,
4184 show_options: ShowStatementOptions,
4186 },
4187 ShowCharset(ShowCharset),
4194 ShowObjects(ShowObjects),
4200 ShowTables {
4204 terse: bool,
4206 history: bool,
4208 extended: bool,
4210 full: bool,
4212 external: bool,
4214 show_options: ShowStatementOptions,
4216 },
4217 ShowViews {
4221 terse: bool,
4223 materialized: bool,
4225 show_options: ShowStatementOptions,
4227 },
4228 ShowCollation {
4234 filter: Option<ShowStatementFilter>,
4236 },
4237 Use(Use),
4241 StartTransaction {
4251 modes: Vec<TransactionMode>,
4253 begin: bool,
4255 transaction: Option<BeginTransactionKind>,
4257 modifier: Option<TransactionModifier>,
4259 statements: Vec<Statement>,
4268 exception: Option<Vec<ExceptionWhen>>,
4282 has_end_keyword: bool,
4284 },
4285 Comment {
4291 object_type: CommentObject,
4293 object_name: ObjectName,
4295 comment: Option<String>,
4297 if_exists: bool,
4300 },
4301 Commit {
4311 chain: bool,
4313 end: bool,
4315 modifier: Option<TransactionModifier>,
4317 },
4318 Rollback {
4322 chain: bool,
4324 savepoint: Option<Ident>,
4326 },
4327 CreateSchema {
4331 schema_name: SchemaName,
4333 if_not_exists: bool,
4335 with: Option<Vec<SqlOption>>,
4343 options: Option<Vec<SqlOption>>,
4351 default_collate_spec: Option<Expr>,
4359 clone: Option<ObjectName>,
4367 },
4368 CreateDatabase {
4374 db_name: ObjectName,
4376 if_not_exists: bool,
4378 location: Option<String>,
4380 managed_location: Option<String>,
4382 or_replace: bool,
4384 transient: bool,
4386 clone: Option<ObjectName>,
4388 data_retention_time_in_days: Option<u64>,
4390 max_data_extension_time_in_days: Option<u64>,
4392 external_volume: Option<String>,
4394 catalog: Option<String>,
4396 replace_invalid_characters: Option<bool>,
4398 default_ddl_collation: Option<String>,
4400 storage_serialization_policy: Option<StorageSerializationPolicy>,
4402 comment: Option<String>,
4404 default_charset: Option<String>,
4406 default_collation: Option<String>,
4408 catalog_sync: Option<String>,
4410 catalog_sync_namespace_mode: Option<CatalogSyncNamespaceMode>,
4412 catalog_sync_namespace_flatten_delimiter: Option<String>,
4414 with_tags: Option<Vec<Tag>>,
4416 with_contacts: Option<Vec<ContactEntry>>,
4418 },
4419 CreateFunction(CreateFunction),
4429 CreateTrigger(CreateTrigger),
4431 DropTrigger(DropTrigger),
4433 CreateProcedure {
4437 or_alter: bool,
4439 name: ObjectName,
4441 params: Option<Vec<ProcedureParam>>,
4443 language: Option<Ident>,
4445 body: ConditionalStatements,
4447 },
4448 CreateMacro {
4455 or_replace: bool,
4457 temporary: bool,
4459 name: ObjectName,
4461 args: Option<Vec<MacroArg>>,
4463 definition: MacroDefinition,
4465 },
4466 CreateStage {
4471 or_replace: bool,
4473 temporary: bool,
4475 if_not_exists: bool,
4477 name: ObjectName,
4479 stage_params: StageParamsObject,
4481 directory_table_params: KeyValueOptions,
4483 file_format: KeyValueOptions,
4485 copy_options: KeyValueOptions,
4487 comment: Option<String>,
4489 },
4490 Assert {
4494 condition: Expr,
4496 message: Option<Expr>,
4498 },
4499 Grant(Grant),
4503 Deny(DenyStatement),
4507 Revoke(Revoke),
4511 Deallocate {
4517 name: Ident,
4519 prepare: bool,
4521 },
4522 Execute {
4531 name: Option<ObjectName>,
4533 parameters: Vec<Expr>,
4535 has_parentheses: bool,
4537 immediate: bool,
4539 into: Vec<Ident>,
4541 using: Vec<ExprWithAlias>,
4543 output: bool,
4546 default: bool,
4549 },
4550 Prepare {
4556 name: Ident,
4558 data_types: Vec<DataType>,
4560 statement: Box<Statement>,
4562 },
4563 Kill {
4570 modifier: Option<KillType>,
4572 id: u64,
4575 },
4576 ExplainTable {
4581 describe_alias: DescribeAlias,
4583 hive_format: Option<HiveDescribeFormat>,
4585 has_table_keyword: bool,
4590 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4592 table_name: ObjectName,
4593 },
4594 Explain {
4598 describe_alias: DescribeAlias,
4600 analyze: bool,
4602 verbose: bool,
4604 query_plan: bool,
4609 estimate: bool,
4612 statement: Box<Statement>,
4614 format: Option<AnalyzeFormatKind>,
4616 options: Option<Vec<UtilityOption>>,
4618 },
4619 Savepoint {
4624 name: Ident,
4626 },
4627 ReleaseSavepoint {
4631 name: Ident,
4633 },
4634 Merge(Merge),
4643 Cache {
4651 table_flag: Option<ObjectName>,
4653 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4655 table_name: ObjectName,
4656 has_as: bool,
4658 options: Vec<SqlOption>,
4660 query: Option<Box<Query>>,
4662 },
4663 UNCache {
4667 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
4669 table_name: ObjectName,
4670 if_exists: bool,
4672 },
4673 CreateSequence {
4682 temporary: bool,
4684 if_not_exists: bool,
4686 name: ObjectName,
4688 data_type: Option<DataType>,
4690 sequence_options: Vec<SequenceOptions>,
4692 owned_by: Option<ObjectName>,
4694 },
4695 CreateDomain(CreateDomain),
4697 CreateType {
4701 name: ObjectName,
4703 representation: Option<UserDefinedTypeRepresentation>,
4705 },
4706 Pragma {
4710 name: ObjectName,
4712 value: Option<ValueWithSpan>,
4714 is_eq: bool,
4716 },
4717 Lock(Lock),
4723 LockTables {
4728 tables: Vec<LockTable>,
4730 },
4731 UnlockTables,
4736 Unload {
4748 query: Option<Box<Query>>,
4750 query_text: Option<String>,
4752 to: Ident,
4754 auth: Option<IamRoleKind>,
4756 with: Vec<SqlOption>,
4758 options: Vec<CopyLegacyOption>,
4760 },
4761 OptimizeTable {
4773 name: ObjectName,
4775 has_table_keyword: bool,
4777 on_cluster: Option<Ident>,
4780 partition: Option<Partition>,
4783 include_final: bool,
4786 deduplicate: Option<Deduplicate>,
4789 predicate: Option<Expr>,
4792 zorder: Option<Vec<Expr>>,
4795 },
4796 LISTEN {
4803 channel: Ident,
4805 },
4806 UNLISTEN {
4813 channel: Ident,
4815 },
4816 NOTIFY {
4823 channel: Ident,
4825 payload: Option<String>,
4827 },
4828 LoadData {
4837 local: bool,
4839 inpath: String,
4841 overwrite: bool,
4843 table_name: ObjectName,
4845 partitioned: Option<Vec<Expr>>,
4847 table_format: Option<HiveLoadDataFormat>,
4849 },
4850 RenameTable(Vec<RenameTable>),
4857 List(FileStagingCommand),
4860 Remove(FileStagingCommand),
4863 RaisError {
4870 message: Box<Expr>,
4872 severity: Box<Expr>,
4874 state: Box<Expr>,
4876 arguments: Vec<Expr>,
4878 options: Vec<RaisErrorOption>,
4880 },
4881 Throw(ThrowStatement),
4883 Print(PrintStatement),
4889 WaitFor(WaitForStatement),
4893 Return(ReturnStatement),
4899 ExportData(ExportData),
4908 CreateUser(CreateUser),
4913 AlterUser(AlterUser),
4918 Vacuum(VacuumStatement),
4925 Reset(ResetStatement),
4933}
4934
4935impl From<Analyze> for Statement {
4936 fn from(analyze: Analyze) -> Self {
4937 Statement::Analyze(analyze)
4938 }
4939}
4940
4941impl From<ddl::Truncate> for Statement {
4942 fn from(truncate: ddl::Truncate) -> Self {
4943 Statement::Truncate(truncate)
4944 }
4945}
4946
4947impl From<Lock> for Statement {
4948 fn from(lock: Lock) -> Self {
4949 Statement::Lock(lock)
4950 }
4951}
4952
4953impl From<ddl::Msck> for Statement {
4954 fn from(msck: ddl::Msck) -> Self {
4955 Statement::Msck(msck)
4956 }
4957}
4958
4959#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4965#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4966#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4967pub enum CurrentGrantsKind {
4968 CopyCurrentGrants,
4970 RevokeCurrentGrants,
4972}
4973
4974impl fmt::Display for CurrentGrantsKind {
4975 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4976 match self {
4977 CurrentGrantsKind::CopyCurrentGrants => write!(f, "COPY CURRENT GRANTS"),
4978 CurrentGrantsKind::RevokeCurrentGrants => write!(f, "REVOKE CURRENT GRANTS"),
4979 }
4980 }
4981}
4982
4983#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4984#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4985#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4986pub enum RaisErrorOption {
4989 Log,
4991 NoWait,
4993 SetError,
4995}
4996
4997impl fmt::Display for RaisErrorOption {
4998 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4999 match self {
5000 RaisErrorOption::Log => write!(f, "LOG"),
5001 RaisErrorOption::NoWait => write!(f, "NOWAIT"),
5002 RaisErrorOption::SetError => write!(f, "SETERROR"),
5003 }
5004 }
5005}
5006
5007impl fmt::Display for Statement {
5008 #[allow(clippy::cognitive_complexity)]
5033 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5034 match self {
5035 Statement::Flush {
5036 object_type,
5037 location,
5038 channel,
5039 read_lock,
5040 export,
5041 tables,
5042 } => {
5043 write!(f, "FLUSH")?;
5044 if let Some(location) = location {
5045 f.write_str(" ")?;
5046 location.fmt(f)?;
5047 }
5048 write!(f, " {object_type}")?;
5049
5050 if let Some(channel) = channel {
5051 write!(f, " FOR CHANNEL {channel}")?;
5052 }
5053
5054 write!(
5055 f,
5056 "{tables}{read}{export}",
5057 tables = if !tables.is_empty() {
5058 format!(" {}", display_comma_separated(tables))
5059 } else {
5060 String::new()
5061 },
5062 export = if *export { " FOR EXPORT" } else { "" },
5063 read = if *read_lock { " WITH READ LOCK" } else { "" }
5064 )
5065 }
5066 Statement::Kill { modifier, id } => {
5067 write!(f, "KILL ")?;
5068
5069 if let Some(m) = modifier {
5070 write!(f, "{m} ")?;
5071 }
5072
5073 write!(f, "{id}")
5074 }
5075 Statement::ExplainTable {
5076 describe_alias,
5077 hive_format,
5078 has_table_keyword,
5079 table_name,
5080 } => {
5081 write!(f, "{describe_alias} ")?;
5082
5083 if let Some(format) = hive_format {
5084 write!(f, "{format} ")?;
5085 }
5086 if *has_table_keyword {
5087 write!(f, "TABLE ")?;
5088 }
5089
5090 write!(f, "{table_name}")
5091 }
5092 Statement::Explain {
5093 describe_alias,
5094 verbose,
5095 analyze,
5096 query_plan,
5097 estimate,
5098 statement,
5099 format,
5100 options,
5101 } => {
5102 write!(f, "{describe_alias} ")?;
5103
5104 if *query_plan {
5105 write!(f, "QUERY PLAN ")?;
5106 }
5107 if *analyze {
5108 write!(f, "ANALYZE ")?;
5109 }
5110 if *estimate {
5111 write!(f, "ESTIMATE ")?;
5112 }
5113
5114 if *verbose {
5115 write!(f, "VERBOSE ")?;
5116 }
5117
5118 if let Some(format) = format {
5119 write!(f, "{format} ")?;
5120 }
5121
5122 if let Some(options) = options {
5123 write!(f, "({}) ", display_comma_separated(options))?;
5124 }
5125
5126 write!(f, "{statement}")
5127 }
5128 Statement::Query(s) => s.fmt(f),
5129 Statement::Declare { stmts } => {
5130 write!(f, "DECLARE ")?;
5131 write!(f, "{}", display_separated(stmts, "; "))
5132 }
5133 Statement::Fetch {
5134 name,
5135 direction,
5136 position,
5137 into,
5138 } => {
5139 write!(f, "FETCH {direction} {position} {name}")?;
5140
5141 if let Some(into) = into {
5142 write!(f, " INTO {into}")?;
5143 }
5144
5145 Ok(())
5146 }
5147 Statement::Directory {
5148 overwrite,
5149 local,
5150 path,
5151 file_format,
5152 source,
5153 } => {
5154 write!(
5155 f,
5156 "INSERT{overwrite}{local} DIRECTORY '{path}'",
5157 overwrite = if *overwrite { " OVERWRITE" } else { "" },
5158 local = if *local { " LOCAL" } else { "" },
5159 path = path
5160 )?;
5161 if let Some(ref ff) = file_format {
5162 write!(f, " STORED AS {ff}")?
5163 }
5164 write!(f, " {source}")
5165 }
5166 Statement::Msck(msck) => msck.fmt(f),
5167 Statement::Truncate(truncate) => truncate.fmt(f),
5168 Statement::Case(stmt) => {
5169 write!(f, "{stmt}")
5170 }
5171 Statement::If(stmt) => {
5172 write!(f, "{stmt}")
5173 }
5174 Statement::While(stmt) => {
5175 write!(f, "{stmt}")
5176 }
5177 Statement::Raise(stmt) => {
5178 write!(f, "{stmt}")
5179 }
5180 Statement::AttachDatabase {
5181 schema_name,
5182 database_file_name,
5183 database,
5184 } => {
5185 let keyword = if *database { "DATABASE " } else { "" };
5186 write!(f, "ATTACH {keyword}{database_file_name} AS {schema_name}")
5187 }
5188 Statement::AttachDuckDBDatabase {
5189 if_not_exists,
5190 database,
5191 database_path,
5192 database_alias,
5193 attach_options,
5194 } => {
5195 write!(
5196 f,
5197 "ATTACH{database}{if_not_exists} {database_path}",
5198 database = if *database { " DATABASE" } else { "" },
5199 if_not_exists = if *if_not_exists { " IF NOT EXISTS" } else { "" },
5200 )?;
5201 if let Some(alias) = database_alias {
5202 write!(f, " AS {alias}")?;
5203 }
5204 if !attach_options.is_empty() {
5205 write!(f, " ({})", display_comma_separated(attach_options))?;
5206 }
5207 Ok(())
5208 }
5209 Statement::DetachDuckDBDatabase {
5210 if_exists,
5211 database,
5212 database_alias,
5213 } => {
5214 write!(
5215 f,
5216 "DETACH{database}{if_exists} {database_alias}",
5217 database = if *database { " DATABASE" } else { "" },
5218 if_exists = if *if_exists { " IF EXISTS" } else { "" },
5219 )?;
5220 Ok(())
5221 }
5222 Statement::Analyze(analyze) => analyze.fmt(f),
5223 Statement::Insert(insert) => insert.fmt(f),
5224 Statement::Install {
5225 extension_name: name,
5226 } => write!(f, "INSTALL {name}"),
5227
5228 Statement::Load {
5229 extension_name: name,
5230 } => write!(f, "LOAD {name}"),
5231
5232 Statement::Call(function) => write!(f, "CALL {function}"),
5233
5234 Statement::Copy {
5235 source,
5236 to,
5237 target,
5238 options,
5239 legacy_options,
5240 values,
5241 } => {
5242 write!(f, "COPY")?;
5243 match source {
5244 CopySource::Query(query) => write!(f, " ({query})")?,
5245 CopySource::Table {
5246 table_name,
5247 columns,
5248 } => {
5249 write!(f, " {table_name}")?;
5250 if !columns.is_empty() {
5251 write!(f, " ({})", display_comma_separated(columns))?;
5252 }
5253 }
5254 }
5255 write!(f, " {} {}", if *to { "TO" } else { "FROM" }, target)?;
5256 if !options.is_empty() {
5257 write!(f, " ({})", display_comma_separated(options))?;
5258 }
5259 if !legacy_options.is_empty() {
5260 write!(f, " {}", display_separated(legacy_options, " "))?;
5261 }
5262 if !values.is_empty() {
5263 writeln!(f, ";")?;
5264 let mut delim = "";
5265 for v in values {
5266 write!(f, "{delim}")?;
5267 delim = "\t";
5268 if let Some(v) = v {
5269 write!(f, "{v}")?;
5270 } else {
5271 write!(f, "\\N")?;
5272 }
5273 }
5274 write!(f, "\n\\.")?;
5275 }
5276 Ok(())
5277 }
5278 Statement::Update(update) => update.fmt(f),
5279 Statement::Delete(delete) => delete.fmt(f),
5280 Statement::Open(open) => open.fmt(f),
5281 Statement::Close { cursor } => {
5282 write!(f, "CLOSE {cursor}")?;
5283
5284 Ok(())
5285 }
5286 Statement::CreateDatabase {
5287 db_name,
5288 if_not_exists,
5289 location,
5290 managed_location,
5291 or_replace,
5292 transient,
5293 clone,
5294 data_retention_time_in_days,
5295 max_data_extension_time_in_days,
5296 external_volume,
5297 catalog,
5298 replace_invalid_characters,
5299 default_ddl_collation,
5300 storage_serialization_policy,
5301 comment,
5302 default_charset,
5303 default_collation,
5304 catalog_sync,
5305 catalog_sync_namespace_mode,
5306 catalog_sync_namespace_flatten_delimiter,
5307 with_tags,
5308 with_contacts,
5309 } => {
5310 write!(
5311 f,
5312 "CREATE {or_replace}{transient}DATABASE {if_not_exists}{name}",
5313 or_replace = if *or_replace { "OR REPLACE " } else { "" },
5314 transient = if *transient { "TRANSIENT " } else { "" },
5315 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
5316 name = db_name,
5317 )?;
5318
5319 if let Some(l) = location {
5320 write!(f, " LOCATION '{l}'")?;
5321 }
5322 if let Some(ml) = managed_location {
5323 write!(f, " MANAGEDLOCATION '{ml}'")?;
5324 }
5325 if let Some(clone) = clone {
5326 write!(f, " CLONE {clone}")?;
5327 }
5328
5329 if let Some(value) = data_retention_time_in_days {
5330 write!(f, " DATA_RETENTION_TIME_IN_DAYS = {value}")?;
5331 }
5332
5333 if let Some(value) = max_data_extension_time_in_days {
5334 write!(f, " MAX_DATA_EXTENSION_TIME_IN_DAYS = {value}")?;
5335 }
5336
5337 if let Some(vol) = external_volume {
5338 write!(f, " EXTERNAL_VOLUME = '{vol}'")?;
5339 }
5340
5341 if let Some(cat) = catalog {
5342 write!(f, " CATALOG = '{cat}'")?;
5343 }
5344
5345 if let Some(true) = replace_invalid_characters {
5346 write!(f, " REPLACE_INVALID_CHARACTERS = TRUE")?;
5347 } else if let Some(false) = replace_invalid_characters {
5348 write!(f, " REPLACE_INVALID_CHARACTERS = FALSE")?;
5349 }
5350
5351 if let Some(collation) = default_ddl_collation {
5352 write!(f, " DEFAULT_DDL_COLLATION = '{collation}'")?;
5353 }
5354
5355 if let Some(policy) = storage_serialization_policy {
5356 write!(f, " STORAGE_SERIALIZATION_POLICY = {policy}")?;
5357 }
5358
5359 if let Some(comment) = comment {
5360 write!(f, " COMMENT = '{comment}'")?;
5361 }
5362
5363 if let Some(charset) = default_charset {
5364 write!(f, " DEFAULT CHARACTER SET {charset}")?;
5365 }
5366
5367 if let Some(collation) = default_collation {
5368 write!(f, " DEFAULT COLLATE {collation}")?;
5369 }
5370
5371 if let Some(sync) = catalog_sync {
5372 write!(f, " CATALOG_SYNC = '{sync}'")?;
5373 }
5374
5375 if let Some(mode) = catalog_sync_namespace_mode {
5376 write!(f, " CATALOG_SYNC_NAMESPACE_MODE = {mode}")?;
5377 }
5378
5379 if let Some(delim) = catalog_sync_namespace_flatten_delimiter {
5380 write!(f, " CATALOG_SYNC_NAMESPACE_FLATTEN_DELIMITER = '{delim}'")?;
5381 }
5382
5383 if let Some(tags) = with_tags {
5384 write!(f, " WITH TAG ({})", display_comma_separated(tags))?;
5385 }
5386
5387 if let Some(contacts) = with_contacts {
5388 write!(f, " WITH CONTACT ({})", display_comma_separated(contacts))?;
5389 }
5390 Ok(())
5391 }
5392 Statement::CreateFunction(create_function) => create_function.fmt(f),
5393 Statement::CreateDomain(create_domain) => create_domain.fmt(f),
5394 Statement::CreateTrigger(create_trigger) => create_trigger.fmt(f),
5395 Statement::DropTrigger(drop_trigger) => drop_trigger.fmt(f),
5396 Statement::CreateProcedure {
5397 name,
5398 or_alter,
5399 params,
5400 language,
5401 body,
5402 } => {
5403 write!(
5404 f,
5405 "CREATE {or_alter}PROCEDURE {name}",
5406 or_alter = if *or_alter { "OR ALTER " } else { "" },
5407 name = name
5408 )?;
5409
5410 if let Some(p) = params {
5411 if !p.is_empty() {
5412 write!(f, " ({})", display_comma_separated(p))?;
5413 }
5414 }
5415
5416 if let Some(language) = language {
5417 write!(f, " LANGUAGE {language}")?;
5418 }
5419
5420 write!(f, " AS {body}")
5421 }
5422 Statement::CreateMacro {
5423 or_replace,
5424 temporary,
5425 name,
5426 args,
5427 definition,
5428 } => {
5429 write!(
5430 f,
5431 "CREATE {or_replace}{temp}MACRO {name}",
5432 temp = if *temporary { "TEMPORARY " } else { "" },
5433 or_replace = if *or_replace { "OR REPLACE " } else { "" },
5434 )?;
5435 if let Some(args) = args {
5436 write!(f, "({})", display_comma_separated(args))?;
5437 }
5438 match definition {
5439 MacroDefinition::Expr(expr) => write!(f, " AS {expr}")?,
5440 MacroDefinition::Table(query) => write!(f, " AS TABLE {query}")?,
5441 }
5442 Ok(())
5443 }
5444 Statement::CreateView(create_view) => create_view.fmt(f),
5445 Statement::CreateTable(create_table) => create_table.fmt(f),
5446 Statement::LoadData {
5447 local,
5448 inpath,
5449 overwrite,
5450 table_name,
5451 partitioned,
5452 table_format,
5453 } => {
5454 write!(
5455 f,
5456 "LOAD DATA {local}INPATH '{inpath}' {overwrite}INTO TABLE {table_name}",
5457 local = if *local { "LOCAL " } else { "" },
5458 inpath = inpath,
5459 overwrite = if *overwrite { "OVERWRITE " } else { "" },
5460 table_name = table_name,
5461 )?;
5462 if let Some(ref parts) = &partitioned {
5463 if !parts.is_empty() {
5464 write!(f, " PARTITION ({})", display_comma_separated(parts))?;
5465 }
5466 }
5467 if let Some(HiveLoadDataFormat {
5468 serde,
5469 input_format,
5470 }) = &table_format
5471 {
5472 write!(f, " INPUTFORMAT {input_format} SERDE {serde}")?;
5473 }
5474 Ok(())
5475 }
5476 Statement::CreateVirtualTable {
5477 name,
5478 if_not_exists,
5479 module_name,
5480 module_args,
5481 } => {
5482 write!(
5483 f,
5484 "CREATE VIRTUAL TABLE {if_not_exists}{name} USING {module_name}",
5485 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
5486 name = name,
5487 module_name = module_name
5488 )?;
5489 if !module_args.is_empty() {
5490 write!(f, " ({})", display_comma_separated(module_args))?;
5491 }
5492 Ok(())
5493 }
5494 Statement::CreateIndex(create_index) => create_index.fmt(f),
5495 Statement::CreateExtension(create_extension) => write!(f, "{create_extension}"),
5496 Statement::CreateCollation(create_collation) => write!(f, "{create_collation}"),
5497 Statement::DropExtension(drop_extension) => write!(f, "{drop_extension}"),
5498 Statement::DropOperator(drop_operator) => write!(f, "{drop_operator}"),
5499 Statement::DropOperatorFamily(drop_operator_family) => {
5500 write!(f, "{drop_operator_family}")
5501 }
5502 Statement::DropOperatorClass(drop_operator_class) => {
5503 write!(f, "{drop_operator_class}")
5504 }
5505 Statement::CreateRole(create_role) => write!(f, "{create_role}"),
5506 Statement::CreateSecret {
5507 or_replace,
5508 temporary,
5509 if_not_exists,
5510 name,
5511 storage_specifier,
5512 secret_type,
5513 options,
5514 } => {
5515 write!(
5516 f,
5517 "CREATE {or_replace}",
5518 or_replace = if *or_replace { "OR REPLACE " } else { "" },
5519 )?;
5520 if let Some(t) = temporary {
5521 write!(f, "{}", if *t { "TEMPORARY " } else { "PERSISTENT " })?;
5522 }
5523 write!(
5524 f,
5525 "SECRET {if_not_exists}",
5526 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
5527 )?;
5528 if let Some(n) = name {
5529 write!(f, "{n} ")?;
5530 };
5531 if let Some(s) = storage_specifier {
5532 write!(f, "IN {s} ")?;
5533 }
5534 write!(f, "( TYPE {secret_type}",)?;
5535 if !options.is_empty() {
5536 write!(f, ", {o}", o = display_comma_separated(options))?;
5537 }
5538 write!(f, " )")?;
5539 Ok(())
5540 }
5541 Statement::CreateServer(stmt) => {
5542 write!(f, "{stmt}")
5543 }
5544 Statement::CreatePolicy(policy) => write!(f, "{policy}"),
5545 Statement::CreateConnector(create_connector) => create_connector.fmt(f),
5546 Statement::CreateOperator(create_operator) => create_operator.fmt(f),
5547 Statement::CreateOperatorFamily(create_operator_family) => {
5548 create_operator_family.fmt(f)
5549 }
5550 Statement::CreateOperatorClass(create_operator_class) => create_operator_class.fmt(f),
5551 Statement::AlterTable(alter_table) => write!(f, "{alter_table}"),
5552 Statement::AlterIndex { name, operation } => {
5553 write!(f, "ALTER INDEX {name} {operation}")
5554 }
5555 Statement::AlterView {
5556 name,
5557 columns,
5558 query,
5559 with_options,
5560 } => {
5561 write!(f, "ALTER VIEW {name}")?;
5562 if !with_options.is_empty() {
5563 write!(f, " WITH ({})", display_comma_separated(with_options))?;
5564 }
5565 if !columns.is_empty() {
5566 write!(f, " ({})", display_comma_separated(columns))?;
5567 }
5568 write!(f, " AS {query}")
5569 }
5570 Statement::AlterFunction(alter_function) => write!(f, "{alter_function}"),
5571 Statement::AlterType(AlterType { name, operation }) => {
5572 write!(f, "ALTER TYPE {name} {operation}")
5573 }
5574 Statement::AlterCollation(alter_collation) => write!(f, "{alter_collation}"),
5575 Statement::AlterOperator(alter_operator) => write!(f, "{alter_operator}"),
5576 Statement::AlterOperatorFamily(alter_operator_family) => {
5577 write!(f, "{alter_operator_family}")
5578 }
5579 Statement::AlterOperatorClass(alter_operator_class) => {
5580 write!(f, "{alter_operator_class}")
5581 }
5582 Statement::AlterRole { name, operation } => {
5583 write!(f, "ALTER ROLE {name} {operation}")
5584 }
5585 Statement::AlterPolicy(alter_policy) => write!(f, "{alter_policy}"),
5586 Statement::AlterConnector {
5587 name,
5588 properties,
5589 url,
5590 owner,
5591 } => {
5592 write!(f, "ALTER CONNECTOR {name}")?;
5593 if let Some(properties) = properties {
5594 write!(
5595 f,
5596 " SET DCPROPERTIES({})",
5597 display_comma_separated(properties)
5598 )?;
5599 }
5600 if let Some(url) = url {
5601 write!(f, " SET URL '{url}'")?;
5602 }
5603 if let Some(owner) = owner {
5604 write!(f, " SET OWNER {owner}")?;
5605 }
5606 Ok(())
5607 }
5608 Statement::AlterSession {
5609 set,
5610 session_params,
5611 } => {
5612 write!(
5613 f,
5614 "ALTER SESSION {set}",
5615 set = if *set { "SET" } else { "UNSET" }
5616 )?;
5617 if !session_params.options.is_empty() {
5618 if *set {
5619 write!(f, " {session_params}")?;
5620 } else {
5621 let options = session_params
5622 .options
5623 .iter()
5624 .map(|p| p.option_name.clone())
5625 .collect::<Vec<_>>();
5626 write!(f, " {}", display_separated(&options, ", "))?;
5627 }
5628 }
5629 Ok(())
5630 }
5631 Statement::Drop {
5632 object_type,
5633 if_exists,
5634 names,
5635 cascade,
5636 restrict,
5637 purge,
5638 temporary,
5639 table,
5640 } => {
5641 write!(
5642 f,
5643 "DROP {}{}{} {}{}{}{}",
5644 if *temporary { "TEMPORARY " } else { "" },
5645 object_type,
5646 if *if_exists { " IF EXISTS" } else { "" },
5647 display_comma_separated(names),
5648 if *cascade { " CASCADE" } else { "" },
5649 if *restrict { " RESTRICT" } else { "" },
5650 if *purge { " PURGE" } else { "" },
5651 )?;
5652 if let Some(table_name) = table.as_ref() {
5653 write!(f, " ON {table_name}")?;
5654 };
5655 Ok(())
5656 }
5657 Statement::DropFunction(drop_function) => write!(f, "{drop_function}"),
5658 Statement::DropDomain(DropDomain {
5659 if_exists,
5660 name,
5661 drop_behavior,
5662 }) => {
5663 write!(
5664 f,
5665 "DROP DOMAIN{} {name}",
5666 if *if_exists { " IF EXISTS" } else { "" },
5667 )?;
5668 if let Some(op) = drop_behavior {
5669 write!(f, " {op}")?;
5670 }
5671 Ok(())
5672 }
5673 Statement::DropProcedure {
5674 if_exists,
5675 proc_desc,
5676 drop_behavior,
5677 } => {
5678 write!(
5679 f,
5680 "DROP PROCEDURE{} {}",
5681 if *if_exists { " IF EXISTS" } else { "" },
5682 display_comma_separated(proc_desc),
5683 )?;
5684 if let Some(op) = drop_behavior {
5685 write!(f, " {op}")?;
5686 }
5687 Ok(())
5688 }
5689 Statement::DropSecret {
5690 if_exists,
5691 temporary,
5692 name,
5693 storage_specifier,
5694 } => {
5695 write!(f, "DROP ")?;
5696 if let Some(t) = temporary {
5697 write!(f, "{}", if *t { "TEMPORARY " } else { "PERSISTENT " })?;
5698 }
5699 write!(
5700 f,
5701 "SECRET {if_exists}{name}",
5702 if_exists = if *if_exists { "IF EXISTS " } else { "" },
5703 )?;
5704 if let Some(s) = storage_specifier {
5705 write!(f, " FROM {s}")?;
5706 }
5707 Ok(())
5708 }
5709 Statement::DropPolicy(policy) => write!(f, "{policy}"),
5710 Statement::DropConnector { if_exists, name } => {
5711 write!(
5712 f,
5713 "DROP CONNECTOR {if_exists}{name}",
5714 if_exists = if *if_exists { "IF EXISTS " } else { "" }
5715 )?;
5716 Ok(())
5717 }
5718 Statement::Discard { object_type } => {
5719 write!(f, "DISCARD {object_type}")?;
5720 Ok(())
5721 }
5722 Self::Set(set) => write!(f, "{set}"),
5723 Statement::ShowVariable { variable } => {
5724 write!(f, "SHOW")?;
5725 if !variable.is_empty() {
5726 write!(f, " {}", display_separated(variable, " "))?;
5727 }
5728 Ok(())
5729 }
5730 Statement::ShowStatus {
5731 filter,
5732 global,
5733 session,
5734 } => {
5735 write!(f, "SHOW")?;
5736 if *global {
5737 write!(f, " GLOBAL")?;
5738 }
5739 if *session {
5740 write!(f, " SESSION")?;
5741 }
5742 write!(f, " STATUS")?;
5743 if let Some(filter) = filter {
5744 write!(f, " {}", filter)?;
5745 }
5746 Ok(())
5747 }
5748 Statement::ShowVariables {
5749 filter,
5750 global,
5751 session,
5752 } => {
5753 write!(f, "SHOW")?;
5754 if *global {
5755 write!(f, " GLOBAL")?;
5756 }
5757 if *session {
5758 write!(f, " SESSION")?;
5759 }
5760 write!(f, " VARIABLES")?;
5761 if let Some(filter) = filter {
5762 write!(f, " {}", filter)?;
5763 }
5764 Ok(())
5765 }
5766 Statement::ShowCreate { obj_type, obj_name } => {
5767 write!(f, "SHOW CREATE {obj_type} {obj_name}",)?;
5768 Ok(())
5769 }
5770 Statement::ShowColumns {
5771 extended,
5772 full,
5773 show_options,
5774 } => {
5775 write!(
5776 f,
5777 "SHOW {extended}{full}COLUMNS{show_options}",
5778 extended = if *extended { "EXTENDED " } else { "" },
5779 full = if *full { "FULL " } else { "" },
5780 )?;
5781 Ok(())
5782 }
5783 Statement::ShowDatabases {
5784 terse,
5785 history,
5786 show_options,
5787 } => {
5788 write!(
5789 f,
5790 "SHOW {terse}DATABASES{history}{show_options}",
5791 terse = if *terse { "TERSE " } else { "" },
5792 history = if *history { " HISTORY" } else { "" },
5793 )?;
5794 Ok(())
5795 }
5796 Statement::ShowCatalogs {
5797 terse,
5798 history,
5799 show_options,
5800 } => {
5801 write!(
5802 f,
5803 "SHOW {terse}CATALOGS{history}{show_options}",
5804 terse = if *terse { "TERSE " } else { "" },
5805 history = if *history { " HISTORY" } else { "" },
5806 )?;
5807 Ok(())
5808 }
5809 Statement::ShowProcessList { full } => {
5810 write!(
5811 f,
5812 "SHOW {full}PROCESSLIST",
5813 full = if *full { "FULL " } else { "" },
5814 )?;
5815 Ok(())
5816 }
5817 Statement::ShowSchemas {
5818 terse,
5819 history,
5820 show_options,
5821 } => {
5822 write!(
5823 f,
5824 "SHOW {terse}SCHEMAS{history}{show_options}",
5825 terse = if *terse { "TERSE " } else { "" },
5826 history = if *history { " HISTORY" } else { "" },
5827 )?;
5828 Ok(())
5829 }
5830 Statement::ShowObjects(ShowObjects {
5831 terse,
5832 show_options,
5833 }) => {
5834 write!(
5835 f,
5836 "SHOW {terse}OBJECTS{show_options}",
5837 terse = if *terse { "TERSE " } else { "" },
5838 )?;
5839 Ok(())
5840 }
5841 Statement::ShowTables {
5842 terse,
5843 history,
5844 extended,
5845 full,
5846 external,
5847 show_options,
5848 } => {
5849 write!(
5850 f,
5851 "SHOW {terse}{extended}{full}{external}TABLES{history}{show_options}",
5852 terse = if *terse { "TERSE " } else { "" },
5853 extended = if *extended { "EXTENDED " } else { "" },
5854 full = if *full { "FULL " } else { "" },
5855 external = if *external { "EXTERNAL " } else { "" },
5856 history = if *history { " HISTORY" } else { "" },
5857 )?;
5858 Ok(())
5859 }
5860 Statement::ShowViews {
5861 terse,
5862 materialized,
5863 show_options,
5864 } => {
5865 write!(
5866 f,
5867 "SHOW {terse}{materialized}VIEWS{show_options}",
5868 terse = if *terse { "TERSE " } else { "" },
5869 materialized = if *materialized { "MATERIALIZED " } else { "" }
5870 )?;
5871 Ok(())
5872 }
5873 Statement::ShowFunctions { filter } => {
5874 write!(f, "SHOW FUNCTIONS")?;
5875 if let Some(filter) = filter {
5876 write!(f, " {filter}")?;
5877 }
5878 Ok(())
5879 }
5880 Statement::Use(use_expr) => use_expr.fmt(f),
5881 Statement::ShowCollation { filter } => {
5882 write!(f, "SHOW COLLATION")?;
5883 if let Some(filter) = filter {
5884 write!(f, " {filter}")?;
5885 }
5886 Ok(())
5887 }
5888 Statement::ShowCharset(show_stm) => show_stm.fmt(f),
5889 Statement::StartTransaction {
5890 modes,
5891 begin: syntax_begin,
5892 transaction,
5893 modifier,
5894 statements,
5895 exception,
5896 has_end_keyword,
5897 } => {
5898 if *syntax_begin {
5899 if let Some(modifier) = *modifier {
5900 write!(f, "BEGIN {modifier}")?;
5901 } else {
5902 write!(f, "BEGIN")?;
5903 }
5904 } else {
5905 write!(f, "START")?;
5906 }
5907 if let Some(transaction) = transaction {
5908 write!(f, " {transaction}")?;
5909 }
5910 if !modes.is_empty() {
5911 write!(f, " {}", display_comma_separated(modes))?;
5912 }
5913 if !statements.is_empty() {
5914 write!(f, " ")?;
5915 format_statement_list(f, statements)?;
5916 }
5917 if let Some(exception_when) = exception {
5918 write!(f, " EXCEPTION")?;
5919 for when in exception_when {
5920 write!(f, " {when}")?;
5921 }
5922 }
5923 if *has_end_keyword {
5924 write!(f, " END")?;
5925 }
5926 Ok(())
5927 }
5928 Statement::Commit {
5929 chain,
5930 end: end_syntax,
5931 modifier,
5932 } => {
5933 if *end_syntax {
5934 write!(f, "END")?;
5935 if let Some(modifier) = *modifier {
5936 write!(f, " {modifier}")?;
5937 }
5938 if *chain {
5939 write!(f, " AND CHAIN")?;
5940 }
5941 } else {
5942 write!(f, "COMMIT{}", if *chain { " AND CHAIN" } else { "" })?;
5943 }
5944 Ok(())
5945 }
5946 Statement::Rollback { chain, savepoint } => {
5947 write!(f, "ROLLBACK")?;
5948
5949 if *chain {
5950 write!(f, " AND CHAIN")?;
5951 }
5952
5953 if let Some(savepoint) = savepoint {
5954 write!(f, " TO SAVEPOINT {savepoint}")?;
5955 }
5956
5957 Ok(())
5958 }
5959 Statement::CreateSchema {
5960 schema_name,
5961 if_not_exists,
5962 with,
5963 options,
5964 default_collate_spec,
5965 clone,
5966 } => {
5967 write!(
5968 f,
5969 "CREATE SCHEMA {if_not_exists}{name}",
5970 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
5971 name = schema_name
5972 )?;
5973
5974 if let Some(collate) = default_collate_spec {
5975 write!(f, " DEFAULT COLLATE {collate}")?;
5976 }
5977
5978 if let Some(with) = with {
5979 write!(f, " WITH ({})", display_comma_separated(with))?;
5980 }
5981
5982 if let Some(options) = options {
5983 write!(f, " OPTIONS({})", display_comma_separated(options))?;
5984 }
5985
5986 if let Some(clone) = clone {
5987 write!(f, " CLONE {clone}")?;
5988 }
5989 Ok(())
5990 }
5991 Statement::Assert { condition, message } => {
5992 write!(f, "ASSERT {condition}")?;
5993 if let Some(m) = message {
5994 write!(f, " AS {m}")?;
5995 }
5996 Ok(())
5997 }
5998 Statement::Grant(grant) => write!(f, "{grant}"),
5999 Statement::Deny(s) => write!(f, "{s}"),
6000 Statement::Revoke(revoke) => write!(f, "{revoke}"),
6001 Statement::Deallocate { name, prepare } => write!(
6002 f,
6003 "DEALLOCATE {prepare}{name}",
6004 prepare = if *prepare { "PREPARE " } else { "" },
6005 name = name,
6006 ),
6007 Statement::Execute {
6008 name,
6009 parameters,
6010 has_parentheses,
6011 immediate,
6012 into,
6013 using,
6014 output,
6015 default,
6016 } => {
6017 let (open, close) = if *has_parentheses {
6018 (if name.is_some() { "(" } else { " (" }, ")")
6020 } else {
6021 (if parameters.is_empty() { "" } else { " " }, "")
6022 };
6023 write!(f, "EXECUTE")?;
6024 if *immediate {
6025 write!(f, " IMMEDIATE")?;
6026 }
6027 if let Some(name) = name {
6028 write!(f, " {name}")?;
6029 }
6030 write!(f, "{open}{}{close}", display_comma_separated(parameters),)?;
6031 if !into.is_empty() {
6032 write!(f, " INTO {}", display_comma_separated(into))?;
6033 }
6034 if !using.is_empty() {
6035 write!(f, " USING {}", display_comma_separated(using))?;
6036 };
6037 if *output {
6038 write!(f, " OUTPUT")?;
6039 }
6040 if *default {
6041 write!(f, " DEFAULT")?;
6042 }
6043 Ok(())
6044 }
6045 Statement::Prepare {
6046 name,
6047 data_types,
6048 statement,
6049 } => {
6050 write!(f, "PREPARE {name} ")?;
6051 if !data_types.is_empty() {
6052 write!(f, "({}) ", display_comma_separated(data_types))?;
6053 }
6054 write!(f, "AS {statement}")
6055 }
6056 Statement::Comment {
6057 object_type,
6058 object_name,
6059 comment,
6060 if_exists,
6061 } => {
6062 write!(f, "COMMENT ")?;
6063 if *if_exists {
6064 write!(f, "IF EXISTS ")?
6065 };
6066 write!(f, "ON {object_type} {object_name} IS ")?;
6067 if let Some(c) = comment {
6068 write!(f, "'{c}'")
6069 } else {
6070 write!(f, "NULL")
6071 }
6072 }
6073 Statement::Savepoint { name } => {
6074 write!(f, "SAVEPOINT ")?;
6075 write!(f, "{name}")
6076 }
6077 Statement::ReleaseSavepoint { name } => {
6078 write!(f, "RELEASE SAVEPOINT {name}")
6079 }
6080 Statement::Merge(merge) => merge.fmt(f),
6081 Statement::Cache {
6082 table_name,
6083 table_flag,
6084 has_as,
6085 options,
6086 query,
6087 } => {
6088 if let Some(table_flag) = table_flag {
6089 write!(f, "CACHE {table_flag} TABLE {table_name}")?;
6090 } else {
6091 write!(f, "CACHE TABLE {table_name}")?;
6092 }
6093
6094 if !options.is_empty() {
6095 write!(f, " OPTIONS({})", display_comma_separated(options))?;
6096 }
6097
6098 match (*has_as, query) {
6099 (true, Some(query)) => write!(f, " AS {query}"),
6100 (true, None) => f.write_str(" AS"),
6101 (false, Some(query)) => write!(f, " {query}"),
6102 (false, None) => Ok(()),
6103 }
6104 }
6105 Statement::UNCache {
6106 table_name,
6107 if_exists,
6108 } => {
6109 if *if_exists {
6110 write!(f, "UNCACHE TABLE IF EXISTS {table_name}")
6111 } else {
6112 write!(f, "UNCACHE TABLE {table_name}")
6113 }
6114 }
6115 Statement::CreateSequence {
6116 temporary,
6117 if_not_exists,
6118 name,
6119 data_type,
6120 sequence_options,
6121 owned_by,
6122 } => {
6123 let as_type: String = if let Some(dt) = data_type.as_ref() {
6124 [" AS ", &dt.to_string()].concat()
6127 } else {
6128 "".to_string()
6129 };
6130 write!(
6131 f,
6132 "CREATE {temporary}SEQUENCE {if_not_exists}{name}{as_type}",
6133 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
6134 temporary = if *temporary { "TEMPORARY " } else { "" },
6135 name = name,
6136 as_type = as_type
6137 )?;
6138 for sequence_option in sequence_options {
6139 write!(f, "{sequence_option}")?;
6140 }
6141 if let Some(ob) = owned_by.as_ref() {
6142 write!(f, " OWNED BY {ob}")?;
6143 }
6144 write!(f, "")
6145 }
6146 Statement::CreateStage {
6147 or_replace,
6148 temporary,
6149 if_not_exists,
6150 name,
6151 stage_params,
6152 directory_table_params,
6153 file_format,
6154 copy_options,
6155 comment,
6156 ..
6157 } => {
6158 write!(
6159 f,
6160 "CREATE {or_replace}{temp}STAGE {if_not_exists}{name}{stage_params}",
6161 temp = if *temporary { "TEMPORARY " } else { "" },
6162 or_replace = if *or_replace { "OR REPLACE " } else { "" },
6163 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
6164 )?;
6165 if !directory_table_params.options.is_empty() {
6166 write!(f, " DIRECTORY=({directory_table_params})")?;
6167 }
6168 if !file_format.options.is_empty() {
6169 write!(f, " FILE_FORMAT=({file_format})")?;
6170 }
6171 if !copy_options.options.is_empty() {
6172 write!(f, " COPY_OPTIONS=({copy_options})")?;
6173 }
6174 if let Some(comment) = comment {
6175 write!(f, " COMMENT='{}'", comment)?;
6176 }
6177 Ok(())
6178 }
6179 Statement::CopyIntoSnowflake {
6180 kind,
6181 into,
6182 into_columns,
6183 from_obj,
6184 from_obj_alias,
6185 stage_params,
6186 from_transformations,
6187 from_query,
6188 files,
6189 pattern,
6190 file_format,
6191 copy_options,
6192 validation_mode,
6193 partition,
6194 } => {
6195 write!(f, "COPY INTO {into}")?;
6196 if let Some(into_columns) = into_columns {
6197 write!(f, " ({})", display_comma_separated(into_columns))?;
6198 }
6199 if let Some(from_transformations) = from_transformations {
6200 if let Some(from_stage) = from_obj {
6202 write!(
6203 f,
6204 " FROM (SELECT {} FROM {}{}",
6205 display_separated(from_transformations, ", "),
6206 from_stage,
6207 stage_params
6208 )?;
6209 }
6210 if let Some(from_obj_alias) = from_obj_alias {
6211 write!(f, " AS {from_obj_alias}")?;
6212 }
6213 write!(f, ")")?;
6214 } else if let Some(from_obj) = from_obj {
6215 write!(f, " FROM {from_obj}{stage_params}")?;
6217 if let Some(from_obj_alias) = from_obj_alias {
6218 write!(f, " AS {from_obj_alias}")?;
6219 }
6220 } else if let Some(from_query) = from_query {
6221 write!(f, " FROM ({from_query})")?;
6223 }
6224
6225 if let Some(files) = files {
6226 write!(f, " FILES = ('{}')", display_separated(files, "', '"))?;
6227 }
6228 if let Some(pattern) = pattern {
6229 write!(f, " PATTERN = '{pattern}'")?;
6230 }
6231 if let Some(partition) = partition {
6232 write!(f, " PARTITION BY {partition}")?;
6233 }
6234 if !file_format.options.is_empty() {
6235 write!(f, " FILE_FORMAT=({file_format})")?;
6236 }
6237 if !copy_options.options.is_empty() {
6238 match kind {
6239 CopyIntoSnowflakeKind::Table => {
6240 write!(f, " COPY_OPTIONS=({copy_options})")?
6241 }
6242 CopyIntoSnowflakeKind::Location => write!(f, " {copy_options}")?,
6243 }
6244 }
6245 if let Some(validation_mode) = validation_mode {
6246 write!(f, " VALIDATION_MODE = {validation_mode}")?;
6247 }
6248 Ok(())
6249 }
6250 Statement::CreateType {
6251 name,
6252 representation,
6253 } => {
6254 write!(f, "CREATE TYPE {name}")?;
6255 if let Some(repr) = representation {
6256 write!(f, " {repr}")?;
6257 }
6258 Ok(())
6259 }
6260 Statement::Pragma { name, value, is_eq } => {
6261 write!(f, "PRAGMA {name}")?;
6262 if let Some(value) = value {
6263 if *is_eq {
6264 write!(f, " = {value}")?;
6265 } else {
6266 write!(f, "({value})")?;
6267 }
6268 }
6269 Ok(())
6270 }
6271 Statement::Lock(lock) => lock.fmt(f),
6272 Statement::LockTables { tables } => {
6273 write!(f, "LOCK TABLES {}", display_comma_separated(tables))
6274 }
6275 Statement::UnlockTables => {
6276 write!(f, "UNLOCK TABLES")
6277 }
6278 Statement::Unload {
6279 query,
6280 query_text,
6281 to,
6282 auth,
6283 with,
6284 options,
6285 } => {
6286 write!(f, "UNLOAD(")?;
6287 if let Some(query) = query {
6288 write!(f, "{query}")?;
6289 }
6290 if let Some(query_text) = query_text {
6291 write!(f, "'{query_text}'")?;
6292 }
6293 write!(f, ") TO {to}")?;
6294 if let Some(auth) = auth {
6295 write!(f, " IAM_ROLE {auth}")?;
6296 }
6297 if !with.is_empty() {
6298 write!(f, " WITH ({})", display_comma_separated(with))?;
6299 }
6300 if !options.is_empty() {
6301 write!(f, " {}", display_separated(options, " "))?;
6302 }
6303 Ok(())
6304 }
6305 Statement::OptimizeTable {
6306 name,
6307 has_table_keyword,
6308 on_cluster,
6309 partition,
6310 include_final,
6311 deduplicate,
6312 predicate,
6313 zorder,
6314 } => {
6315 write!(f, "OPTIMIZE")?;
6316 if *has_table_keyword {
6317 write!(f, " TABLE")?;
6318 }
6319 write!(f, " {name}")?;
6320 if let Some(on_cluster) = on_cluster {
6321 write!(f, " ON CLUSTER {on_cluster}")?;
6322 }
6323 if let Some(partition) = partition {
6324 write!(f, " {partition}")?;
6325 }
6326 if *include_final {
6327 write!(f, " FINAL")?;
6328 }
6329 if let Some(deduplicate) = deduplicate {
6330 write!(f, " {deduplicate}")?;
6331 }
6332 if let Some(predicate) = predicate {
6333 write!(f, " WHERE {predicate}")?;
6334 }
6335 if let Some(zorder) = zorder {
6336 write!(f, " ZORDER BY ({})", display_comma_separated(zorder))?;
6337 }
6338 Ok(())
6339 }
6340 Statement::LISTEN { channel } => {
6341 write!(f, "LISTEN {channel}")?;
6342 Ok(())
6343 }
6344 Statement::UNLISTEN { channel } => {
6345 write!(f, "UNLISTEN {channel}")?;
6346 Ok(())
6347 }
6348 Statement::NOTIFY { channel, payload } => {
6349 write!(f, "NOTIFY {channel}")?;
6350 if let Some(payload) = payload {
6351 write!(f, ", '{payload}'")?;
6352 }
6353 Ok(())
6354 }
6355 Statement::RenameTable(rename_tables) => {
6356 write!(f, "RENAME TABLE {}", display_comma_separated(rename_tables))
6357 }
6358 Statement::RaisError {
6359 message,
6360 severity,
6361 state,
6362 arguments,
6363 options,
6364 } => {
6365 write!(f, "RAISERROR({message}, {severity}, {state}")?;
6366 if !arguments.is_empty() {
6367 write!(f, ", {}", display_comma_separated(arguments))?;
6368 }
6369 write!(f, ")")?;
6370 if !options.is_empty() {
6371 write!(f, " WITH {}", display_comma_separated(options))?;
6372 }
6373 Ok(())
6374 }
6375 Statement::Throw(s) => write!(f, "{s}"),
6376 Statement::Print(s) => write!(f, "{s}"),
6377 Statement::WaitFor(s) => write!(f, "{s}"),
6378 Statement::Return(r) => write!(f, "{r}"),
6379 Statement::List(command) => write!(f, "LIST {command}"),
6380 Statement::Remove(command) => write!(f, "REMOVE {command}"),
6381 Statement::ExportData(e) => write!(f, "{e}"),
6382 Statement::CreateUser(s) => write!(f, "{s}"),
6383 Statement::AlterSchema(s) => write!(f, "{s}"),
6384 Statement::Vacuum(s) => write!(f, "{s}"),
6385 Statement::AlterUser(s) => write!(f, "{s}"),
6386 Statement::Reset(s) => write!(f, "{s}"),
6387 }
6388 }
6389}
6390
6391#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6398#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6399#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6400pub enum SequenceOptions {
6401 IncrementBy(Expr, bool),
6403 MinValue(Option<Expr>),
6405 MaxValue(Option<Expr>),
6407 StartWith(Expr, bool),
6409 Cache(Expr),
6411 Cycle(bool),
6413}
6414
6415impl fmt::Display for SequenceOptions {
6416 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6417 match self {
6418 SequenceOptions::IncrementBy(increment, by) => {
6419 write!(
6420 f,
6421 " INCREMENT{by} {increment}",
6422 by = if *by { " BY" } else { "" },
6423 increment = increment
6424 )
6425 }
6426 SequenceOptions::MinValue(Some(expr)) => {
6427 write!(f, " MINVALUE {expr}")
6428 }
6429 SequenceOptions::MinValue(None) => {
6430 write!(f, " NO MINVALUE")
6431 }
6432 SequenceOptions::MaxValue(Some(expr)) => {
6433 write!(f, " MAXVALUE {expr}")
6434 }
6435 SequenceOptions::MaxValue(None) => {
6436 write!(f, " NO MAXVALUE")
6437 }
6438 SequenceOptions::StartWith(start, with) => {
6439 write!(
6440 f,
6441 " START{with} {start}",
6442 with = if *with { " WITH" } else { "" },
6443 start = start
6444 )
6445 }
6446 SequenceOptions::Cache(cache) => {
6447 write!(f, " CACHE {}", *cache)
6448 }
6449 SequenceOptions::Cycle(no) => {
6450 write!(f, " {}CYCLE", if *no { "NO " } else { "" })
6451 }
6452 }
6453 }
6454}
6455
6456#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6458#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6459#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6460pub struct SetAssignment {
6461 pub scope: Option<ContextModifier>,
6463 pub name: ObjectName,
6465 pub value: Expr,
6467}
6468
6469impl fmt::Display for SetAssignment {
6470 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6471 write!(
6472 f,
6473 "{}{} = {}",
6474 self.scope.map(|s| format!("{s}")).unwrap_or_default(),
6475 self.name,
6476 self.value
6477 )
6478 }
6479}
6480
6481#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6485#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6486#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6487pub struct TruncateTableTarget {
6488 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6490 pub name: ObjectName,
6491 pub only: bool,
6497 pub has_asterisk: bool,
6503}
6504
6505impl fmt::Display for TruncateTableTarget {
6506 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6507 if self.only {
6508 write!(f, "ONLY ")?;
6509 };
6510 write!(f, "{}", self.name)?;
6511 if self.has_asterisk {
6512 write!(f, " *")?;
6513 };
6514 Ok(())
6515 }
6516}
6517
6518#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6522#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6523#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6524pub struct Lock {
6525 pub tables: Vec<LockTableTarget>,
6527 pub lock_mode: Option<LockTableMode>,
6529 pub nowait: bool,
6531}
6532
6533impl fmt::Display for Lock {
6534 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6535 write!(f, "LOCK TABLE {}", display_comma_separated(&self.tables))?;
6536 if let Some(lock_mode) = &self.lock_mode {
6537 write!(f, " IN {lock_mode} MODE")?;
6538 }
6539 if self.nowait {
6540 write!(f, " NOWAIT")?;
6541 }
6542 Ok(())
6543 }
6544}
6545
6546#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6550#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6551#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6552pub struct LockTableTarget {
6553 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
6555 pub name: ObjectName,
6556 pub only: bool,
6558 pub has_asterisk: bool,
6560}
6561
6562impl fmt::Display for LockTableTarget {
6563 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6564 if self.only {
6565 write!(f, "ONLY ")?;
6566 }
6567 write!(f, "{}", self.name)?;
6568 if self.has_asterisk {
6569 write!(f, " *")?;
6570 }
6571 Ok(())
6572 }
6573}
6574
6575#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6579#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6580#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6581pub enum LockTableMode {
6582 AccessShare,
6584 RowShare,
6586 RowExclusive,
6588 ShareUpdateExclusive,
6590 Share,
6592 ShareRowExclusive,
6594 Exclusive,
6596 AccessExclusive,
6598}
6599
6600impl fmt::Display for LockTableMode {
6601 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6602 let text = match self {
6603 Self::AccessShare => "ACCESS SHARE",
6604 Self::RowShare => "ROW SHARE",
6605 Self::RowExclusive => "ROW EXCLUSIVE",
6606 Self::ShareUpdateExclusive => "SHARE UPDATE EXCLUSIVE",
6607 Self::Share => "SHARE",
6608 Self::ShareRowExclusive => "SHARE ROW EXCLUSIVE",
6609 Self::Exclusive => "EXCLUSIVE",
6610 Self::AccessExclusive => "ACCESS EXCLUSIVE",
6611 };
6612 write!(f, "{text}")
6613 }
6614}
6615
6616#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6619#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6620#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6621pub enum TruncateIdentityOption {
6622 Restart,
6624 Continue,
6626}
6627
6628#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6631#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6632#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6633pub enum CascadeOption {
6634 Cascade,
6636 Restrict,
6638}
6639
6640impl Display for CascadeOption {
6641 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6642 match self {
6643 CascadeOption::Cascade => write!(f, "CASCADE"),
6644 CascadeOption::Restrict => write!(f, "RESTRICT"),
6645 }
6646 }
6647}
6648
6649#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6651#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6652#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6653pub enum BeginTransactionKind {
6654 Transaction,
6656 Work,
6658 Tran,
6661}
6662
6663impl Display for BeginTransactionKind {
6664 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6665 match self {
6666 BeginTransactionKind::Transaction => write!(f, "TRANSACTION"),
6667 BeginTransactionKind::Work => write!(f, "WORK"),
6668 BeginTransactionKind::Tran => write!(f, "TRAN"),
6669 }
6670 }
6671}
6672
6673#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6676#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6677#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6678pub enum MinMaxValue {
6679 Empty,
6681 None,
6683 Some(Expr),
6685}
6686
6687#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6688#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6689#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6690#[non_exhaustive]
6691pub enum OnInsert {
6693 DuplicateKeyUpdate(Vec<Assignment>),
6695 OnConflict(OnConflict),
6697}
6698
6699#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6700#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6701#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6702pub struct InsertAliases {
6704 pub row_alias: ObjectName,
6706 pub col_aliases: Option<Vec<Ident>>,
6708}
6709
6710#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6711#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6712#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6713pub struct TableAliasWithoutColumns {
6715 pub explicit: bool,
6717 pub alias: Ident,
6719}
6720
6721#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6722#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6723#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6724pub struct OnConflict {
6726 pub conflict_target: Option<ConflictTarget>,
6728 pub action: OnConflictAction,
6730}
6731#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6732#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6733#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6734pub enum ConflictTarget {
6736 Columns(Vec<Ident>),
6738 OnConstraint(ObjectName),
6740}
6741#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6742#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6743#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6744pub enum OnConflictAction {
6746 DoNothing,
6748 DoUpdate(DoUpdate),
6750}
6751
6752#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6753#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6754#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6755pub struct DoUpdate {
6757 pub assignments: Vec<Assignment>,
6759 pub selection: Option<Expr>,
6761}
6762
6763impl fmt::Display for OnInsert {
6764 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6765 match self {
6766 Self::DuplicateKeyUpdate(expr) => write!(
6767 f,
6768 " ON DUPLICATE KEY UPDATE {}",
6769 display_comma_separated(expr)
6770 ),
6771 Self::OnConflict(o) => write!(f, "{o}"),
6772 }
6773 }
6774}
6775impl fmt::Display for OnConflict {
6776 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6777 write!(f, " ON CONFLICT")?;
6778 if let Some(target) = &self.conflict_target {
6779 write!(f, "{target}")?;
6780 }
6781 write!(f, " {}", self.action)
6782 }
6783}
6784impl fmt::Display for ConflictTarget {
6785 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6786 match self {
6787 ConflictTarget::Columns(cols) => write!(f, "({})", display_comma_separated(cols)),
6788 ConflictTarget::OnConstraint(name) => write!(f, " ON CONSTRAINT {name}"),
6789 }
6790 }
6791}
6792impl fmt::Display for OnConflictAction {
6793 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6794 match self {
6795 Self::DoNothing => write!(f, "DO NOTHING"),
6796 Self::DoUpdate(do_update) => {
6797 write!(f, "DO UPDATE")?;
6798 if !do_update.assignments.is_empty() {
6799 write!(
6800 f,
6801 " SET {}",
6802 display_comma_separated(&do_update.assignments)
6803 )?;
6804 }
6805 if let Some(selection) = &do_update.selection {
6806 write!(f, " WHERE {selection}")?;
6807 }
6808 Ok(())
6809 }
6810 }
6811 }
6812}
6813
6814#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6816#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6817#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6818pub enum Privileges {
6819 All {
6821 with_privileges_keyword: bool,
6823 },
6824 Actions(Vec<Action>),
6826}
6827
6828impl fmt::Display for Privileges {
6829 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6830 match self {
6831 Privileges::All {
6832 with_privileges_keyword,
6833 } => {
6834 write!(
6835 f,
6836 "ALL{}",
6837 if *with_privileges_keyword {
6838 " PRIVILEGES"
6839 } else {
6840 ""
6841 }
6842 )
6843 }
6844 Privileges::Actions(actions) => {
6845 write!(f, "{}", display_comma_separated(actions))
6846 }
6847 }
6848 }
6849}
6850
6851#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6853#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6854#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6855pub enum FetchDirection {
6856 Count {
6858 limit: ValueWithSpan,
6860 },
6861 Next,
6863 Prior,
6865 First,
6867 Last,
6869 Absolute {
6871 limit: ValueWithSpan,
6873 },
6874 Relative {
6876 limit: ValueWithSpan,
6878 },
6879 All,
6881 Forward {
6885 limit: Option<ValueWithSpan>,
6887 },
6888 ForwardAll,
6890 Backward {
6894 limit: Option<ValueWithSpan>,
6896 },
6897 BackwardAll,
6899}
6900
6901impl fmt::Display for FetchDirection {
6902 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6903 match self {
6904 FetchDirection::Count { limit } => f.write_str(&limit.to_string())?,
6905 FetchDirection::Next => f.write_str("NEXT")?,
6906 FetchDirection::Prior => f.write_str("PRIOR")?,
6907 FetchDirection::First => f.write_str("FIRST")?,
6908 FetchDirection::Last => f.write_str("LAST")?,
6909 FetchDirection::Absolute { limit } => {
6910 f.write_str("ABSOLUTE ")?;
6911 f.write_str(&limit.to_string())?;
6912 }
6913 FetchDirection::Relative { limit } => {
6914 f.write_str("RELATIVE ")?;
6915 f.write_str(&limit.to_string())?;
6916 }
6917 FetchDirection::All => f.write_str("ALL")?,
6918 FetchDirection::Forward { limit } => {
6919 f.write_str("FORWARD")?;
6920
6921 if let Some(l) = limit {
6922 f.write_str(" ")?;
6923 f.write_str(&l.to_string())?;
6924 }
6925 }
6926 FetchDirection::ForwardAll => f.write_str("FORWARD ALL")?,
6927 FetchDirection::Backward { limit } => {
6928 f.write_str("BACKWARD")?;
6929
6930 if let Some(l) = limit {
6931 f.write_str(" ")?;
6932 f.write_str(&l.to_string())?;
6933 }
6934 }
6935 FetchDirection::BackwardAll => f.write_str("BACKWARD ALL")?,
6936 };
6937
6938 Ok(())
6939 }
6940}
6941
6942#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6946#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6947#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6948pub enum FetchPosition {
6949 From,
6951 In,
6953}
6954
6955impl fmt::Display for FetchPosition {
6956 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6957 match self {
6958 FetchPosition::From => f.write_str("FROM")?,
6959 FetchPosition::In => f.write_str("IN")?,
6960 };
6961
6962 Ok(())
6963 }
6964}
6965
6966#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
6968#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
6969#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
6970pub enum Action {
6971 AddSearchOptimization,
6973 Apply {
6975 apply_type: ActionApplyType,
6977 },
6978 ApplyBudget,
6980 AttachListing,
6982 AttachPolicy,
6984 Audit,
6986 BindServiceEndpoint,
6988 Connect,
6990 Create {
6992 obj_type: Option<ActionCreateObjectType>,
6994 },
6995 DatabaseRole {
6997 role: ObjectName,
6999 },
7000 Delete,
7002 Drop,
7004 EvolveSchema,
7006 Exec {
7008 obj_type: Option<ActionExecuteObjectType>,
7010 },
7011 Execute {
7013 obj_type: Option<ActionExecuteObjectType>,
7015 },
7016 Failover,
7018 ImportedPrivileges,
7020 ImportShare,
7022 Insert {
7024 columns: Option<Vec<Ident>>,
7026 },
7027 Manage {
7029 manage_type: ActionManageType,
7031 },
7032 ManageReleases,
7034 ManageVersions,
7036 Modify {
7038 modify_type: Option<ActionModifyType>,
7040 },
7041 Monitor {
7043 monitor_type: Option<ActionMonitorType>,
7045 },
7046 Operate,
7048 OverrideShareRestrictions,
7050 Ownership,
7052 PurchaseDataExchangeListing,
7054
7055 Read,
7057 ReadSession,
7059 References {
7061 columns: Option<Vec<Ident>>,
7063 },
7064 Replicate,
7066 ResolveAll,
7068 Role {
7070 role: ObjectName,
7072 },
7073 Select {
7075 columns: Option<Vec<Ident>>,
7077 },
7078 Temporary,
7080 Trigger,
7082 Truncate,
7084 Update {
7086 columns: Option<Vec<Ident>>,
7088 },
7089 Usage,
7091}
7092
7093impl fmt::Display for Action {
7094 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7095 match self {
7096 Action::AddSearchOptimization => f.write_str("ADD SEARCH OPTIMIZATION")?,
7097 Action::Apply { apply_type } => write!(f, "APPLY {apply_type}")?,
7098 Action::ApplyBudget => f.write_str("APPLYBUDGET")?,
7099 Action::AttachListing => f.write_str("ATTACH LISTING")?,
7100 Action::AttachPolicy => f.write_str("ATTACH POLICY")?,
7101 Action::Audit => f.write_str("AUDIT")?,
7102 Action::BindServiceEndpoint => f.write_str("BIND SERVICE ENDPOINT")?,
7103 Action::Connect => f.write_str("CONNECT")?,
7104 Action::Create { obj_type } => {
7105 f.write_str("CREATE")?;
7106 if let Some(obj_type) = obj_type {
7107 write!(f, " {obj_type}")?
7108 }
7109 }
7110 Action::DatabaseRole { role } => write!(f, "DATABASE ROLE {role}")?,
7111 Action::Delete => f.write_str("DELETE")?,
7112 Action::Drop => f.write_str("DROP")?,
7113 Action::EvolveSchema => f.write_str("EVOLVE SCHEMA")?,
7114 Action::Exec { obj_type } => {
7115 f.write_str("EXEC")?;
7116 if let Some(obj_type) = obj_type {
7117 write!(f, " {obj_type}")?
7118 }
7119 }
7120 Action::Execute { obj_type } => {
7121 f.write_str("EXECUTE")?;
7122 if let Some(obj_type) = obj_type {
7123 write!(f, " {obj_type}")?
7124 }
7125 }
7126 Action::Failover => f.write_str("FAILOVER")?,
7127 Action::ImportedPrivileges => f.write_str("IMPORTED PRIVILEGES")?,
7128 Action::ImportShare => f.write_str("IMPORT SHARE")?,
7129 Action::Insert { .. } => f.write_str("INSERT")?,
7130 Action::Manage { manage_type } => write!(f, "MANAGE {manage_type}")?,
7131 Action::ManageReleases => f.write_str("MANAGE RELEASES")?,
7132 Action::ManageVersions => f.write_str("MANAGE VERSIONS")?,
7133 Action::Modify { modify_type } => {
7134 write!(f, "MODIFY")?;
7135 if let Some(modify_type) = modify_type {
7136 write!(f, " {modify_type}")?;
7137 }
7138 }
7139 Action::Monitor { monitor_type } => {
7140 write!(f, "MONITOR")?;
7141 if let Some(monitor_type) = monitor_type {
7142 write!(f, " {monitor_type}")?
7143 }
7144 }
7145 Action::Operate => f.write_str("OPERATE")?,
7146 Action::OverrideShareRestrictions => f.write_str("OVERRIDE SHARE RESTRICTIONS")?,
7147 Action::Ownership => f.write_str("OWNERSHIP")?,
7148 Action::PurchaseDataExchangeListing => f.write_str("PURCHASE DATA EXCHANGE LISTING")?,
7149 Action::Read => f.write_str("READ")?,
7150 Action::ReadSession => f.write_str("READ SESSION")?,
7151 Action::References { .. } => f.write_str("REFERENCES")?,
7152 Action::Replicate => f.write_str("REPLICATE")?,
7153 Action::ResolveAll => f.write_str("RESOLVE ALL")?,
7154 Action::Role { role } => write!(f, "ROLE {role}")?,
7155 Action::Select { .. } => f.write_str("SELECT")?,
7156 Action::Temporary => f.write_str("TEMPORARY")?,
7157 Action::Trigger => f.write_str("TRIGGER")?,
7158 Action::Truncate => f.write_str("TRUNCATE")?,
7159 Action::Update { .. } => f.write_str("UPDATE")?,
7160 Action::Usage => f.write_str("USAGE")?,
7161 };
7162 match self {
7163 Action::Insert { columns }
7164 | Action::References { columns }
7165 | Action::Select { columns }
7166 | Action::Update { columns } => {
7167 if let Some(columns) = columns {
7168 write!(f, " ({})", display_comma_separated(columns))?;
7169 }
7170 }
7171 _ => (),
7172 };
7173 Ok(())
7174 }
7175}
7176
7177#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7178#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7179#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7180pub enum ActionCreateObjectType {
7183 Account,
7185 Application,
7187 ApplicationPackage,
7189 ComputePool,
7191 DataExchangeListing,
7193 Database,
7195 ExternalVolume,
7197 FailoverGroup,
7199 Integration,
7201 NetworkPolicy,
7203 OrganiationListing,
7205 ReplicationGroup,
7207 Role,
7209 Schema,
7211 Share,
7213 User,
7215 Warehouse,
7217}
7218
7219impl fmt::Display for ActionCreateObjectType {
7220 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7221 match self {
7222 ActionCreateObjectType::Account => write!(f, "ACCOUNT"),
7223 ActionCreateObjectType::Application => write!(f, "APPLICATION"),
7224 ActionCreateObjectType::ApplicationPackage => write!(f, "APPLICATION PACKAGE"),
7225 ActionCreateObjectType::ComputePool => write!(f, "COMPUTE POOL"),
7226 ActionCreateObjectType::DataExchangeListing => write!(f, "DATA EXCHANGE LISTING"),
7227 ActionCreateObjectType::Database => write!(f, "DATABASE"),
7228 ActionCreateObjectType::ExternalVolume => write!(f, "EXTERNAL VOLUME"),
7229 ActionCreateObjectType::FailoverGroup => write!(f, "FAILOVER GROUP"),
7230 ActionCreateObjectType::Integration => write!(f, "INTEGRATION"),
7231 ActionCreateObjectType::NetworkPolicy => write!(f, "NETWORK POLICY"),
7232 ActionCreateObjectType::OrganiationListing => write!(f, "ORGANIZATION LISTING"),
7233 ActionCreateObjectType::ReplicationGroup => write!(f, "REPLICATION GROUP"),
7234 ActionCreateObjectType::Role => write!(f, "ROLE"),
7235 ActionCreateObjectType::Schema => write!(f, "SCHEMA"),
7236 ActionCreateObjectType::Share => write!(f, "SHARE"),
7237 ActionCreateObjectType::User => write!(f, "USER"),
7238 ActionCreateObjectType::Warehouse => write!(f, "WAREHOUSE"),
7239 }
7240 }
7241}
7242
7243#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7244#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7245#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7246pub enum ActionApplyType {
7249 AggregationPolicy,
7251 AuthenticationPolicy,
7253 JoinPolicy,
7255 MaskingPolicy,
7257 PackagesPolicy,
7259 PasswordPolicy,
7261 ProjectionPolicy,
7263 RowAccessPolicy,
7265 SessionPolicy,
7267 Tag,
7269}
7270
7271impl fmt::Display for ActionApplyType {
7272 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7273 match self {
7274 ActionApplyType::AggregationPolicy => write!(f, "AGGREGATION POLICY"),
7275 ActionApplyType::AuthenticationPolicy => write!(f, "AUTHENTICATION POLICY"),
7276 ActionApplyType::JoinPolicy => write!(f, "JOIN POLICY"),
7277 ActionApplyType::MaskingPolicy => write!(f, "MASKING POLICY"),
7278 ActionApplyType::PackagesPolicy => write!(f, "PACKAGES POLICY"),
7279 ActionApplyType::PasswordPolicy => write!(f, "PASSWORD POLICY"),
7280 ActionApplyType::ProjectionPolicy => write!(f, "PROJECTION POLICY"),
7281 ActionApplyType::RowAccessPolicy => write!(f, "ROW ACCESS POLICY"),
7282 ActionApplyType::SessionPolicy => write!(f, "SESSION POLICY"),
7283 ActionApplyType::Tag => write!(f, "TAG"),
7284 }
7285 }
7286}
7287
7288#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7289#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7290#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7291pub enum ActionExecuteObjectType {
7294 Alert,
7296 DataMetricFunction,
7298 ManagedAlert,
7300 ManagedTask,
7302 Task,
7304}
7305
7306impl fmt::Display for ActionExecuteObjectType {
7307 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7308 match self {
7309 ActionExecuteObjectType::Alert => write!(f, "ALERT"),
7310 ActionExecuteObjectType::DataMetricFunction => write!(f, "DATA METRIC FUNCTION"),
7311 ActionExecuteObjectType::ManagedAlert => write!(f, "MANAGED ALERT"),
7312 ActionExecuteObjectType::ManagedTask => write!(f, "MANAGED TASK"),
7313 ActionExecuteObjectType::Task => write!(f, "TASK"),
7314 }
7315 }
7316}
7317
7318#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7319#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7320#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7321pub enum ActionManageType {
7324 AccountSupportCases,
7326 EventSharing,
7328 Grants,
7330 ListingAutoFulfillment,
7332 OrganizationSupportCases,
7334 UserSupportCases,
7336 Warehouses,
7338}
7339
7340impl fmt::Display for ActionManageType {
7341 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7342 match self {
7343 ActionManageType::AccountSupportCases => write!(f, "ACCOUNT SUPPORT CASES"),
7344 ActionManageType::EventSharing => write!(f, "EVENT SHARING"),
7345 ActionManageType::Grants => write!(f, "GRANTS"),
7346 ActionManageType::ListingAutoFulfillment => write!(f, "LISTING AUTO FULFILLMENT"),
7347 ActionManageType::OrganizationSupportCases => write!(f, "ORGANIZATION SUPPORT CASES"),
7348 ActionManageType::UserSupportCases => write!(f, "USER SUPPORT CASES"),
7349 ActionManageType::Warehouses => write!(f, "WAREHOUSES"),
7350 }
7351 }
7352}
7353
7354#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7355#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7356#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7357pub enum ActionModifyType {
7360 LogLevel,
7362 TraceLevel,
7364 SessionLogLevel,
7366 SessionTraceLevel,
7368}
7369
7370impl fmt::Display for ActionModifyType {
7371 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7372 match self {
7373 ActionModifyType::LogLevel => write!(f, "LOG LEVEL"),
7374 ActionModifyType::TraceLevel => write!(f, "TRACE LEVEL"),
7375 ActionModifyType::SessionLogLevel => write!(f, "SESSION LOG LEVEL"),
7376 ActionModifyType::SessionTraceLevel => write!(f, "SESSION TRACE LEVEL"),
7377 }
7378 }
7379}
7380
7381#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7382#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7383#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7384pub enum ActionMonitorType {
7387 Execution,
7389 Security,
7391 Usage,
7393}
7394
7395impl fmt::Display for ActionMonitorType {
7396 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7397 match self {
7398 ActionMonitorType::Execution => write!(f, "EXECUTION"),
7399 ActionMonitorType::Security => write!(f, "SECURITY"),
7400 ActionMonitorType::Usage => write!(f, "USAGE"),
7401 }
7402 }
7403}
7404
7405#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7407#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7408#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7409pub struct Grantee {
7410 pub grantee_type: GranteesType,
7412 pub name: Option<GranteeName>,
7414}
7415
7416impl fmt::Display for Grantee {
7417 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7418 match self.grantee_type {
7419 GranteesType::Role => {
7420 write!(f, "ROLE ")?;
7421 }
7422 GranteesType::Share => {
7423 write!(f, "SHARE ")?;
7424 }
7425 GranteesType::User => {
7426 write!(f, "USER ")?;
7427 }
7428 GranteesType::Group => {
7429 write!(f, "GROUP ")?;
7430 }
7431 GranteesType::Public => {
7432 write!(f, "PUBLIC ")?;
7433 }
7434 GranteesType::DatabaseRole => {
7435 write!(f, "DATABASE ROLE ")?;
7436 }
7437 GranteesType::Application => {
7438 write!(f, "APPLICATION ")?;
7439 }
7440 GranteesType::ApplicationRole => {
7441 write!(f, "APPLICATION ROLE ")?;
7442 }
7443 GranteesType::None => (),
7444 }
7445 if let Some(ref name) = self.name {
7446 name.fmt(f)?;
7447 }
7448 Ok(())
7449 }
7450}
7451
7452#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7453#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7454#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7455pub enum GranteesType {
7457 Role,
7459 Share,
7461 User,
7463 Group,
7465 Public,
7467 DatabaseRole,
7469 Application,
7471 ApplicationRole,
7473 None,
7475}
7476
7477#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7479#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7480#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7481pub enum GranteeName {
7482 ObjectName(ObjectName),
7484 UserHost {
7486 user: Ident,
7488 host: Ident,
7490 },
7491}
7492
7493impl fmt::Display for GranteeName {
7494 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7495 match self {
7496 GranteeName::ObjectName(name) => name.fmt(f),
7497 GranteeName::UserHost { user, host } => {
7498 write!(f, "{user}@{host}")
7499 }
7500 }
7501 }
7502}
7503
7504#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7506#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7507#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7508pub enum GrantObjects {
7509 AllSequencesInSchema {
7511 schemas: Vec<ObjectName>,
7513 },
7514 AllTablesInSchema {
7516 schemas: Vec<ObjectName>,
7518 },
7519 AllViewsInSchema {
7521 schemas: Vec<ObjectName>,
7523 },
7524 AllMaterializedViewsInSchema {
7526 schemas: Vec<ObjectName>,
7528 },
7529 AllExternalTablesInSchema {
7531 schemas: Vec<ObjectName>,
7533 },
7534 AllFunctionsInSchema {
7536 schemas: Vec<ObjectName>,
7538 },
7539 FutureSchemasInDatabase {
7541 databases: Vec<ObjectName>,
7543 },
7544 FutureTablesInSchema {
7546 schemas: Vec<ObjectName>,
7548 },
7549 FutureViewsInSchema {
7551 schemas: Vec<ObjectName>,
7553 },
7554 FutureExternalTablesInSchema {
7556 schemas: Vec<ObjectName>,
7558 },
7559 FutureMaterializedViewsInSchema {
7561 schemas: Vec<ObjectName>,
7563 },
7564 FutureSequencesInSchema {
7566 schemas: Vec<ObjectName>,
7568 },
7569 Databases(Vec<ObjectName>),
7571 Schemas(Vec<ObjectName>),
7573 Sequences(Vec<ObjectName>),
7575 Tables(Vec<ObjectName>),
7577 Views(Vec<ObjectName>),
7579 Warehouses(Vec<ObjectName>),
7581 Integrations(Vec<ObjectName>),
7583 ResourceMonitors(Vec<ObjectName>),
7585 Users(Vec<ObjectName>),
7587 ComputePools(Vec<ObjectName>),
7589 Connections(Vec<ObjectName>),
7591 FailoverGroup(Vec<ObjectName>),
7593 ReplicationGroup(Vec<ObjectName>),
7595 ExternalVolumes(Vec<ObjectName>),
7597 Procedure {
7603 name: ObjectName,
7605 arg_types: Vec<DataType>,
7607 },
7608
7609 Function {
7615 name: ObjectName,
7617 arg_types: Vec<DataType>,
7619 },
7620}
7621
7622impl fmt::Display for GrantObjects {
7623 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7624 match self {
7625 GrantObjects::Sequences(sequences) => {
7626 write!(f, "SEQUENCE {}", display_comma_separated(sequences))
7627 }
7628 GrantObjects::Databases(databases) => {
7629 write!(f, "DATABASE {}", display_comma_separated(databases))
7630 }
7631 GrantObjects::Schemas(schemas) => {
7632 write!(f, "SCHEMA {}", display_comma_separated(schemas))
7633 }
7634 GrantObjects::Tables(tables) => {
7635 write!(f, "{}", display_comma_separated(tables))
7636 }
7637 GrantObjects::Views(views) => {
7638 write!(f, "VIEW {}", display_comma_separated(views))
7639 }
7640 GrantObjects::Warehouses(warehouses) => {
7641 write!(f, "WAREHOUSE {}", display_comma_separated(warehouses))
7642 }
7643 GrantObjects::Integrations(integrations) => {
7644 write!(f, "INTEGRATION {}", display_comma_separated(integrations))
7645 }
7646 GrantObjects::AllSequencesInSchema { schemas } => {
7647 write!(
7648 f,
7649 "ALL SEQUENCES IN SCHEMA {}",
7650 display_comma_separated(schemas)
7651 )
7652 }
7653 GrantObjects::AllTablesInSchema { schemas } => {
7654 write!(
7655 f,
7656 "ALL TABLES IN SCHEMA {}",
7657 display_comma_separated(schemas)
7658 )
7659 }
7660 GrantObjects::AllExternalTablesInSchema { schemas } => {
7661 write!(
7662 f,
7663 "ALL EXTERNAL TABLES IN SCHEMA {}",
7664 display_comma_separated(schemas)
7665 )
7666 }
7667 GrantObjects::AllViewsInSchema { schemas } => {
7668 write!(
7669 f,
7670 "ALL VIEWS IN SCHEMA {}",
7671 display_comma_separated(schemas)
7672 )
7673 }
7674 GrantObjects::AllMaterializedViewsInSchema { schemas } => {
7675 write!(
7676 f,
7677 "ALL MATERIALIZED VIEWS IN SCHEMA {}",
7678 display_comma_separated(schemas)
7679 )
7680 }
7681 GrantObjects::AllFunctionsInSchema { schemas } => {
7682 write!(
7683 f,
7684 "ALL FUNCTIONS IN SCHEMA {}",
7685 display_comma_separated(schemas)
7686 )
7687 }
7688 GrantObjects::FutureSchemasInDatabase { databases } => {
7689 write!(
7690 f,
7691 "FUTURE SCHEMAS IN DATABASE {}",
7692 display_comma_separated(databases)
7693 )
7694 }
7695 GrantObjects::FutureTablesInSchema { schemas } => {
7696 write!(
7697 f,
7698 "FUTURE TABLES IN SCHEMA {}",
7699 display_comma_separated(schemas)
7700 )
7701 }
7702 GrantObjects::FutureExternalTablesInSchema { schemas } => {
7703 write!(
7704 f,
7705 "FUTURE EXTERNAL TABLES IN SCHEMA {}",
7706 display_comma_separated(schemas)
7707 )
7708 }
7709 GrantObjects::FutureViewsInSchema { schemas } => {
7710 write!(
7711 f,
7712 "FUTURE VIEWS IN SCHEMA {}",
7713 display_comma_separated(schemas)
7714 )
7715 }
7716 GrantObjects::FutureMaterializedViewsInSchema { schemas } => {
7717 write!(
7718 f,
7719 "FUTURE MATERIALIZED VIEWS IN SCHEMA {}",
7720 display_comma_separated(schemas)
7721 )
7722 }
7723 GrantObjects::FutureSequencesInSchema { schemas } => {
7724 write!(
7725 f,
7726 "FUTURE SEQUENCES IN SCHEMA {}",
7727 display_comma_separated(schemas)
7728 )
7729 }
7730 GrantObjects::ResourceMonitors(objects) => {
7731 write!(f, "RESOURCE MONITOR {}", display_comma_separated(objects))
7732 }
7733 GrantObjects::Users(objects) => {
7734 write!(f, "USER {}", display_comma_separated(objects))
7735 }
7736 GrantObjects::ComputePools(objects) => {
7737 write!(f, "COMPUTE POOL {}", display_comma_separated(objects))
7738 }
7739 GrantObjects::Connections(objects) => {
7740 write!(f, "CONNECTION {}", display_comma_separated(objects))
7741 }
7742 GrantObjects::FailoverGroup(objects) => {
7743 write!(f, "FAILOVER GROUP {}", display_comma_separated(objects))
7744 }
7745 GrantObjects::ReplicationGroup(objects) => {
7746 write!(f, "REPLICATION GROUP {}", display_comma_separated(objects))
7747 }
7748 GrantObjects::ExternalVolumes(objects) => {
7749 write!(f, "EXTERNAL VOLUME {}", display_comma_separated(objects))
7750 }
7751 GrantObjects::Procedure { name, arg_types } => {
7752 write!(f, "PROCEDURE {name}")?;
7753 if !arg_types.is_empty() {
7754 write!(f, "({})", display_comma_separated(arg_types))?;
7755 }
7756 Ok(())
7757 }
7758 GrantObjects::Function { name, arg_types } => {
7759 write!(f, "FUNCTION {name}")?;
7760 if !arg_types.is_empty() {
7761 write!(f, "({})", display_comma_separated(arg_types))?;
7762 }
7763 Ok(())
7764 }
7765 }
7766 }
7767}
7768
7769#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7773#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7774#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7775pub struct DenyStatement {
7776 pub privileges: Privileges,
7778 pub objects: GrantObjects,
7780 pub grantees: Vec<Grantee>,
7782 pub granted_by: Option<Ident>,
7784 pub cascade: Option<CascadeOption>,
7786}
7787
7788impl fmt::Display for DenyStatement {
7789 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7790 write!(f, "DENY {}", self.privileges)?;
7791 write!(f, " ON {}", self.objects)?;
7792 if !self.grantees.is_empty() {
7793 write!(f, " TO {}", display_comma_separated(&self.grantees))?;
7794 }
7795 if let Some(cascade) = &self.cascade {
7796 write!(f, " {cascade}")?;
7797 }
7798 if let Some(granted_by) = &self.granted_by {
7799 write!(f, " AS {granted_by}")?;
7800 }
7801 Ok(())
7802 }
7803}
7804
7805#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7807#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7808#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7809pub struct Assignment {
7810 pub target: AssignmentTarget,
7812 pub value: Expr,
7814}
7815
7816impl fmt::Display for Assignment {
7817 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7818 write!(f, "{} = {}", self.target, self.value)
7819 }
7820}
7821
7822#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7826#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7827#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7828pub enum AssignmentTarget {
7829 ColumnName(ObjectName),
7831 Tuple(Vec<ObjectName>),
7833}
7834
7835impl fmt::Display for AssignmentTarget {
7836 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7837 match self {
7838 AssignmentTarget::ColumnName(column) => write!(f, "{column}"),
7839 AssignmentTarget::Tuple(columns) => write!(f, "({})", display_comma_separated(columns)),
7840 }
7841 }
7842}
7843
7844#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7845#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7846#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7847pub enum FunctionArgExpr {
7849 Expr(Expr),
7851 QualifiedWildcard(ObjectName),
7853 Wildcard,
7855 WildcardWithOptions(WildcardAdditionalOptions),
7859}
7860
7861impl From<Expr> for FunctionArgExpr {
7862 fn from(wildcard_expr: Expr) -> Self {
7863 match wildcard_expr {
7864 Expr::QualifiedWildcard(prefix, _) => Self::QualifiedWildcard(prefix),
7865 Expr::Wildcard(_) => Self::Wildcard,
7866 expr => Self::Expr(expr),
7867 }
7868 }
7869}
7870
7871impl fmt::Display for FunctionArgExpr {
7872 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7873 match self {
7874 FunctionArgExpr::Expr(expr) => write!(f, "{expr}"),
7875 FunctionArgExpr::QualifiedWildcard(prefix) => write!(f, "{prefix}.*"),
7876 FunctionArgExpr::Wildcard => f.write_str("*"),
7877 FunctionArgExpr::WildcardWithOptions(opts) => write!(f, "*{opts}"),
7878 }
7879 }
7880}
7881
7882#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7883#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7884#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7885pub enum FunctionArgOperator {
7887 Equals,
7889 RightArrow,
7891 Assignment,
7893 Colon,
7895 Value,
7897}
7898
7899impl fmt::Display for FunctionArgOperator {
7900 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7901 match self {
7902 FunctionArgOperator::Equals => f.write_str("="),
7903 FunctionArgOperator::RightArrow => f.write_str("=>"),
7904 FunctionArgOperator::Assignment => f.write_str(":="),
7905 FunctionArgOperator::Colon => f.write_str(":"),
7906 FunctionArgOperator::Value => f.write_str("VALUE"),
7907 }
7908 }
7909}
7910
7911#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7912#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7913#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7914pub enum FunctionArg {
7916 Named {
7920 name: Ident,
7922 arg: FunctionArgExpr,
7924 operator: FunctionArgOperator,
7926 },
7927 ExprNamed {
7931 name: Expr,
7933 arg: FunctionArgExpr,
7935 operator: FunctionArgOperator,
7937 },
7938 Unnamed(FunctionArgExpr),
7940}
7941
7942impl fmt::Display for FunctionArg {
7943 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7944 match self {
7945 FunctionArg::Named {
7946 name,
7947 arg,
7948 operator,
7949 } => write!(f, "{name} {operator} {arg}"),
7950 FunctionArg::ExprNamed {
7951 name,
7952 arg,
7953 operator,
7954 } => write!(f, "{name} {operator} {arg}"),
7955 FunctionArg::Unnamed(unnamed_arg) => write!(f, "{unnamed_arg}"),
7956 }
7957 }
7958}
7959
7960#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7961#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7962#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7963pub enum CloseCursor {
7965 All,
7967 Specific {
7969 name: Ident,
7971 },
7972}
7973
7974impl fmt::Display for CloseCursor {
7975 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7976 match self {
7977 CloseCursor::All => write!(f, "ALL"),
7978 CloseCursor::Specific { name } => write!(f, "{name}"),
7979 }
7980 }
7981}
7982
7983#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
7985#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7986#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
7987pub struct DropDomain {
7988 pub if_exists: bool,
7990 pub name: ObjectName,
7992 pub drop_behavior: Option<DropBehavior>,
7994}
7995
7996#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8000#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8001#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8002pub struct TypedString {
8003 pub data_type: DataType,
8005 pub value: ValueWithSpan,
8008 pub uses_odbc_syntax: bool,
8019}
8020
8021impl fmt::Display for TypedString {
8022 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8023 let data_type = &self.data_type;
8024 let value = &self.value;
8025 match self.uses_odbc_syntax {
8026 false => {
8027 write!(f, "{data_type}")?;
8028 write!(f, " {value}")
8029 }
8030 true => {
8031 let prefix = match data_type {
8032 DataType::Date => "d",
8033 DataType::Time(..) => "t",
8034 DataType::Timestamp(..) => "ts",
8035 _ => "?",
8036 };
8037 write!(f, "{{{prefix} {value}}}")
8038 }
8039 }
8040 }
8041}
8042
8043#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8045#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8046#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8047pub struct Function {
8048 pub name: ObjectName,
8050 pub uses_odbc_syntax: bool,
8059 pub parameters: FunctionArguments,
8069 pub args: FunctionArguments,
8072 pub filter: Option<Box<Expr>>,
8074 pub null_treatment: Option<NullTreatment>,
8083 pub over: Option<WindowType>,
8085 pub within_group: Vec<OrderByExpr>,
8093}
8094
8095impl fmt::Display for Function {
8096 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8097 if self.uses_odbc_syntax {
8098 write!(f, "{{fn ")?;
8099 }
8100
8101 write!(f, "{}{}{}", self.name, self.parameters, self.args)?;
8102
8103 if !self.within_group.is_empty() {
8104 write!(
8105 f,
8106 " WITHIN GROUP (ORDER BY {})",
8107 display_comma_separated(&self.within_group)
8108 )?;
8109 }
8110
8111 if let Some(filter_cond) = &self.filter {
8112 write!(f, " FILTER (WHERE {filter_cond})")?;
8113 }
8114
8115 if let Some(null_treatment) = &self.null_treatment {
8116 write!(f, " {null_treatment}")?;
8117 }
8118
8119 if let Some(o) = &self.over {
8120 f.write_str(" OVER ")?;
8121 o.fmt(f)?;
8122 }
8123
8124 if self.uses_odbc_syntax {
8125 write!(f, "}}")?;
8126 }
8127
8128 Ok(())
8129 }
8130}
8131
8132#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8134#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8135#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8136pub enum FunctionArguments {
8137 None,
8140 Subquery(Box<Query>),
8143 List(FunctionArgumentList),
8146}
8147
8148impl fmt::Display for FunctionArguments {
8149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8150 match self {
8151 FunctionArguments::None => Ok(()),
8152 FunctionArguments::Subquery(query) => write!(f, "({query})"),
8153 FunctionArguments::List(args) => write!(f, "({args})"),
8154 }
8155 }
8156}
8157
8158#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8160#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8161#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8162pub struct FunctionArgumentList {
8163 pub duplicate_treatment: Option<DuplicateTreatment>,
8165 pub args: Vec<FunctionArg>,
8167 pub clauses: Vec<FunctionArgumentClause>,
8169}
8170
8171impl fmt::Display for FunctionArgumentList {
8172 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8173 if let Some(duplicate_treatment) = self.duplicate_treatment {
8174 write!(f, "{duplicate_treatment} ")?;
8175 }
8176 write!(f, "{}", display_comma_separated(&self.args))?;
8177 if !self.clauses.is_empty() {
8178 if !self.args.is_empty() {
8179 write!(f, " ")?;
8180 }
8181 write!(f, "{}", display_separated(&self.clauses, " "))?;
8182 }
8183 Ok(())
8184 }
8185}
8186
8187#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8188#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8189#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8190pub enum FunctionArgumentClause {
8192 IgnoreOrRespectNulls(NullTreatment),
8201 OrderBy(Vec<OrderByExpr>),
8205 Limit(Expr),
8207 OnOverflow(ListAggOnOverflow),
8211 Having(HavingBound),
8220 Separator(ValueWithSpan),
8224 JsonNullClause(JsonNullClause),
8230 JsonReturningClause(JsonReturningClause),
8234}
8235
8236impl fmt::Display for FunctionArgumentClause {
8237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8238 match self {
8239 FunctionArgumentClause::IgnoreOrRespectNulls(null_treatment) => {
8240 write!(f, "{null_treatment}")
8241 }
8242 FunctionArgumentClause::OrderBy(order_by) => {
8243 write!(f, "ORDER BY {}", display_comma_separated(order_by))
8244 }
8245 FunctionArgumentClause::Limit(limit) => write!(f, "LIMIT {limit}"),
8246 FunctionArgumentClause::OnOverflow(on_overflow) => write!(f, "{on_overflow}"),
8247 FunctionArgumentClause::Having(bound) => write!(f, "{bound}"),
8248 FunctionArgumentClause::Separator(sep) => write!(f, "SEPARATOR {sep}"),
8249 FunctionArgumentClause::JsonNullClause(null_clause) => write!(f, "{null_clause}"),
8250 FunctionArgumentClause::JsonReturningClause(returning_clause) => {
8251 write!(f, "{returning_clause}")
8252 }
8253 }
8254 }
8255}
8256
8257#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8259#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8260#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8261pub struct Method {
8262 pub expr: Box<Expr>,
8264 pub method_chain: Vec<Function>,
8267}
8268
8269impl fmt::Display for Method {
8270 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8271 write!(
8272 f,
8273 "{}.{}",
8274 self.expr,
8275 display_separated(&self.method_chain, ".")
8276 )
8277 }
8278}
8279
8280#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8281#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8282#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8283pub enum DuplicateTreatment {
8285 Distinct,
8287 All,
8289}
8290
8291impl fmt::Display for DuplicateTreatment {
8292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8293 match self {
8294 DuplicateTreatment::Distinct => write!(f, "DISTINCT"),
8295 DuplicateTreatment::All => write!(f, "ALL"),
8296 }
8297 }
8298}
8299
8300#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8301#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8302#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8303pub enum AnalyzeFormatKind {
8305 Keyword(AnalyzeFormat),
8307 Assignment(AnalyzeFormat),
8309}
8310
8311impl fmt::Display for AnalyzeFormatKind {
8312 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
8313 match self {
8314 AnalyzeFormatKind::Keyword(format) => write!(f, "FORMAT {format}"),
8315 AnalyzeFormatKind::Assignment(format) => write!(f, "FORMAT={format}"),
8316 }
8317 }
8318}
8319
8320#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8321#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8322#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8323pub enum AnalyzeFormat {
8325 TEXT,
8327 GRAPHVIZ,
8329 JSON,
8331 TRADITIONAL,
8333 TREE,
8335}
8336
8337impl fmt::Display for AnalyzeFormat {
8338 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
8339 f.write_str(match self {
8340 AnalyzeFormat::TEXT => "TEXT",
8341 AnalyzeFormat::GRAPHVIZ => "GRAPHVIZ",
8342 AnalyzeFormat::JSON => "JSON",
8343 AnalyzeFormat::TRADITIONAL => "TRADITIONAL",
8344 AnalyzeFormat::TREE => "TREE",
8345 })
8346 }
8347}
8348
8349#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8351#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8352#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8353pub enum FileFormat {
8354 TEXTFILE,
8356 SEQUENCEFILE,
8358 ORC,
8360 PARQUET,
8362 AVRO,
8364 RCFILE,
8366 JSONFILE,
8368}
8369
8370impl fmt::Display for FileFormat {
8371 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8372 use self::FileFormat::*;
8373 f.write_str(match self {
8374 TEXTFILE => "TEXTFILE",
8375 SEQUENCEFILE => "SEQUENCEFILE",
8376 ORC => "ORC",
8377 PARQUET => "PARQUET",
8378 AVRO => "AVRO",
8379 RCFILE => "RCFILE",
8380 JSONFILE => "JSONFILE",
8381 })
8382 }
8383}
8384
8385#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8387#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8388#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8389pub enum ListAggOnOverflow {
8390 Error,
8392
8393 Truncate {
8395 filler: Option<Box<Expr>>,
8397 with_count: bool,
8399 },
8400}
8401
8402impl fmt::Display for ListAggOnOverflow {
8403 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8404 write!(f, "ON OVERFLOW")?;
8405 match self {
8406 ListAggOnOverflow::Error => write!(f, " ERROR"),
8407 ListAggOnOverflow::Truncate { filler, with_count } => {
8408 write!(f, " TRUNCATE")?;
8409 if let Some(filler) = filler {
8410 write!(f, " {filler}")?;
8411 }
8412 if *with_count {
8413 write!(f, " WITH")?;
8414 } else {
8415 write!(f, " WITHOUT")?;
8416 }
8417 write!(f, " COUNT")
8418 }
8419 }
8420 }
8421}
8422
8423#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8425#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8426#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8427pub struct HavingBound(pub HavingBoundKind, pub Expr);
8428
8429impl fmt::Display for HavingBound {
8430 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8431 write!(f, "HAVING {} {}", self.0, self.1)
8432 }
8433}
8434
8435#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8436#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8437#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8438pub enum HavingBoundKind {
8440 Min,
8442 Max,
8444}
8445
8446impl fmt::Display for HavingBoundKind {
8447 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8448 match self {
8449 HavingBoundKind::Min => write!(f, "MIN"),
8450 HavingBoundKind::Max => write!(f, "MAX"),
8451 }
8452 }
8453}
8454
8455#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8456#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8457#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8458pub enum ObjectType {
8460 Collation,
8462 Table,
8464 View,
8466 MaterializedView,
8468 Index,
8470 Schema,
8472 Database,
8474 Role,
8476 Sequence,
8478 Stage,
8480 Type,
8482 User,
8484 Stream,
8486}
8487
8488impl fmt::Display for ObjectType {
8489 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8490 f.write_str(match self {
8491 ObjectType::Collation => "COLLATION",
8492 ObjectType::Table => "TABLE",
8493 ObjectType::View => "VIEW",
8494 ObjectType::MaterializedView => "MATERIALIZED VIEW",
8495 ObjectType::Index => "INDEX",
8496 ObjectType::Schema => "SCHEMA",
8497 ObjectType::Database => "DATABASE",
8498 ObjectType::Role => "ROLE",
8499 ObjectType::Sequence => "SEQUENCE",
8500 ObjectType::Stage => "STAGE",
8501 ObjectType::Type => "TYPE",
8502 ObjectType::User => "USER",
8503 ObjectType::Stream => "STREAM",
8504 })
8505 }
8506}
8507
8508#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8509#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8510#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8511pub enum KillType {
8513 Connection,
8515 Query,
8517 Mutation,
8519}
8520
8521impl fmt::Display for KillType {
8522 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8523 f.write_str(match self {
8524 KillType::Connection => "CONNECTION",
8526 KillType::Query => "QUERY",
8527 KillType::Mutation => "MUTATION",
8529 })
8530 }
8531}
8532
8533#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8534#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8535#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8536pub enum HiveDistributionStyle {
8538 PARTITIONED {
8540 columns: Vec<ColumnDef>,
8542 },
8543 SKEWED {
8545 columns: Vec<ColumnDef>,
8547 on: Vec<ColumnDef>,
8549 stored_as_directories: bool,
8551 },
8552 NONE,
8554}
8555
8556#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8557#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8558#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8559pub enum HiveRowFormat {
8561 SERDE {
8563 class: String,
8565 },
8566 DELIMITED {
8568 delimiters: Vec<HiveRowDelimiter>,
8570 },
8571}
8572
8573#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8574#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8575#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8576pub struct HiveLoadDataFormat {
8578 pub serde: Expr,
8580 pub input_format: Expr,
8582}
8583
8584#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8585#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8586#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8587pub struct HiveRowDelimiter {
8589 pub delimiter: HiveDelimiter,
8591 pub char: Ident,
8593}
8594
8595impl fmt::Display for HiveRowDelimiter {
8596 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8597 write!(f, "{} ", self.delimiter)?;
8598 write!(f, "{}", self.char)
8599 }
8600}
8601
8602#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8603#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8604#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8605pub enum HiveDelimiter {
8607 FieldsTerminatedBy,
8609 FieldsEscapedBy,
8611 CollectionItemsTerminatedBy,
8613 MapKeysTerminatedBy,
8615 LinesTerminatedBy,
8617 NullDefinedAs,
8619}
8620
8621impl fmt::Display for HiveDelimiter {
8622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8623 use HiveDelimiter::*;
8624 f.write_str(match self {
8625 FieldsTerminatedBy => "FIELDS TERMINATED BY",
8626 FieldsEscapedBy => "ESCAPED BY",
8627 CollectionItemsTerminatedBy => "COLLECTION ITEMS TERMINATED BY",
8628 MapKeysTerminatedBy => "MAP KEYS TERMINATED BY",
8629 LinesTerminatedBy => "LINES TERMINATED BY",
8630 NullDefinedAs => "NULL DEFINED AS",
8631 })
8632 }
8633}
8634
8635#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8636#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8637#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8638pub enum HiveDescribeFormat {
8640 Extended,
8642 Formatted,
8644}
8645
8646impl fmt::Display for HiveDescribeFormat {
8647 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8648 use HiveDescribeFormat::*;
8649 f.write_str(match self {
8650 Extended => "EXTENDED",
8651 Formatted => "FORMATTED",
8652 })
8653 }
8654}
8655
8656#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8657#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8658#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8659pub enum DescribeAlias {
8661 Describe,
8663 Explain,
8665 Desc,
8667}
8668
8669impl fmt::Display for DescribeAlias {
8670 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8671 use DescribeAlias::*;
8672 f.write_str(match self {
8673 Describe => "DESCRIBE",
8674 Explain => "EXPLAIN",
8675 Desc => "DESC",
8676 })
8677 }
8678}
8679
8680#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8681#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8682#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8683#[allow(clippy::large_enum_variant)]
8684pub enum HiveIOFormat {
8686 IOF {
8688 input_format: Expr,
8690 output_format: Expr,
8692 },
8693 FileFormat {
8695 format: FileFormat,
8697 },
8698 Using {
8704 format: Ident,
8706 },
8707}
8708
8709#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Default)]
8710#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8711#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8712pub struct HiveFormat {
8714 pub row_format: Option<HiveRowFormat>,
8716 pub serde_properties: Option<Vec<SqlOption>>,
8718 pub storage: Option<HiveIOFormat>,
8720 pub location: Option<String>,
8722}
8723
8724#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8725#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8726#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8727pub struct ClusteredIndex {
8729 pub name: Ident,
8731 pub asc: Option<bool>,
8733}
8734
8735impl fmt::Display for ClusteredIndex {
8736 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8737 write!(f, "{}", self.name)?;
8738 match self.asc {
8739 Some(true) => write!(f, " ASC"),
8740 Some(false) => write!(f, " DESC"),
8741 _ => Ok(()),
8742 }
8743 }
8744}
8745
8746#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8747#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8748#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8749pub enum TableOptionsClustered {
8751 ColumnstoreIndex,
8753 ColumnstoreIndexOrder(Vec<Ident>),
8755 Index(Vec<ClusteredIndex>),
8757}
8758
8759impl fmt::Display for TableOptionsClustered {
8760 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8761 match self {
8762 TableOptionsClustered::ColumnstoreIndex => {
8763 write!(f, "CLUSTERED COLUMNSTORE INDEX")
8764 }
8765 TableOptionsClustered::ColumnstoreIndexOrder(values) => {
8766 write!(
8767 f,
8768 "CLUSTERED COLUMNSTORE INDEX ORDER ({})",
8769 display_comma_separated(values)
8770 )
8771 }
8772 TableOptionsClustered::Index(values) => {
8773 write!(f, "CLUSTERED INDEX ({})", display_comma_separated(values))
8774 }
8775 }
8776 }
8777}
8778
8779#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
8781#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8782#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8783pub enum PartitionRangeDirection {
8784 Left,
8786 Right,
8788}
8789
8790#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8791#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8792#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8793pub enum SqlOption {
8795 Clustered(TableOptionsClustered),
8799 Ident(Ident),
8803 KeyValue {
8807 key: Ident,
8809 value: Expr,
8811 },
8812 Partition {
8819 column_name: Ident,
8821 range_direction: Option<PartitionRangeDirection>,
8823 for_values: Vec<Expr>,
8825 },
8826 Comment(CommentDef),
8828 TableSpace(TablespaceOption),
8831 NamedParenthesizedList(NamedParenthesizedList),
8838}
8839
8840impl fmt::Display for SqlOption {
8841 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8842 match self {
8843 SqlOption::Clustered(c) => write!(f, "{c}"),
8844 SqlOption::Ident(ident) => {
8845 write!(f, "{ident}")
8846 }
8847 SqlOption::KeyValue { key: name, value } => {
8848 write!(f, "{name} = {value}")
8849 }
8850 SqlOption::Partition {
8851 column_name,
8852 range_direction,
8853 for_values,
8854 } => {
8855 let direction = match range_direction {
8856 Some(PartitionRangeDirection::Left) => " LEFT",
8857 Some(PartitionRangeDirection::Right) => " RIGHT",
8858 None => "",
8859 };
8860
8861 write!(
8862 f,
8863 "PARTITION ({} RANGE{} FOR VALUES ({}))",
8864 column_name,
8865 direction,
8866 display_comma_separated(for_values)
8867 )
8868 }
8869 SqlOption::TableSpace(tablespace_option) => {
8870 write!(f, "TABLESPACE {}", tablespace_option.name)?;
8871 match tablespace_option.storage {
8872 Some(StorageType::Disk) => write!(f, " STORAGE DISK"),
8873 Some(StorageType::Memory) => write!(f, " STORAGE MEMORY"),
8874 None => Ok(()),
8875 }
8876 }
8877 SqlOption::Comment(comment) => match comment {
8878 CommentDef::WithEq(comment) => {
8879 write!(f, "COMMENT = '{comment}'")
8880 }
8881 CommentDef::WithoutEq(comment) => {
8882 write!(f, "COMMENT '{comment}'")
8883 }
8884 },
8885 SqlOption::NamedParenthesizedList(value) => {
8886 write!(f, "{} = ", value.key)?;
8887 if let Some(key) = &value.name {
8888 write!(f, "{key}")?;
8889 }
8890 if !value.values.is_empty() {
8891 write!(f, "({})", display_comma_separated(&value.values))?
8892 }
8893 Ok(())
8894 }
8895 }
8896 }
8897}
8898
8899#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
8900#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8901#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8902pub enum StorageType {
8904 Disk,
8906 Memory,
8908}
8909
8910#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
8911#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8912#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8913pub struct TablespaceOption {
8916 pub name: String,
8918 pub storage: Option<StorageType>,
8920}
8921
8922#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8923#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8924#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8925pub struct SecretOption {
8927 pub key: Ident,
8929 pub value: Ident,
8931}
8932
8933impl fmt::Display for SecretOption {
8934 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8935 write!(f, "{} {}", self.key, self.value)
8936 }
8937}
8938
8939#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8943#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8944#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8945pub struct CreateServerStatement {
8946 pub name: ObjectName,
8948 pub if_not_exists: bool,
8950 pub server_type: Option<Ident>,
8952 pub version: Option<Ident>,
8954 pub foreign_data_wrapper: ObjectName,
8956 pub options: Option<Vec<CreateServerOption>>,
8958}
8959
8960impl fmt::Display for CreateServerStatement {
8961 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8962 let CreateServerStatement {
8963 name,
8964 if_not_exists,
8965 server_type,
8966 version,
8967 foreign_data_wrapper,
8968 options,
8969 } = self;
8970
8971 write!(
8972 f,
8973 "CREATE SERVER {if_not_exists}{name} ",
8974 if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
8975 )?;
8976
8977 if let Some(st) = server_type {
8978 write!(f, "TYPE {st} ")?;
8979 }
8980
8981 if let Some(v) = version {
8982 write!(f, "VERSION {v} ")?;
8983 }
8984
8985 write!(f, "FOREIGN DATA WRAPPER {foreign_data_wrapper}")?;
8986
8987 if let Some(o) = options {
8988 write!(f, " OPTIONS ({o})", o = display_comma_separated(o))?;
8989 }
8990
8991 Ok(())
8992 }
8993}
8994
8995#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
8997#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
8998#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
8999pub struct CreateServerOption {
9000 pub key: Ident,
9002 pub value: Ident,
9004}
9005
9006impl fmt::Display for CreateServerOption {
9007 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9008 write!(f, "{} {}", self.key, self.value)
9009 }
9010}
9011
9012#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9013#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9014#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9015pub enum AttachDuckDBDatabaseOption {
9017 ReadOnly(Option<bool>),
9019 Type(Ident),
9021}
9022
9023impl fmt::Display for AttachDuckDBDatabaseOption {
9024 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9025 match self {
9026 AttachDuckDBDatabaseOption::ReadOnly(Some(true)) => write!(f, "READ_ONLY true"),
9027 AttachDuckDBDatabaseOption::ReadOnly(Some(false)) => write!(f, "READ_ONLY false"),
9028 AttachDuckDBDatabaseOption::ReadOnly(None) => write!(f, "READ_ONLY"),
9029 AttachDuckDBDatabaseOption::Type(t) => write!(f, "TYPE {t}"),
9030 }
9031 }
9032}
9033
9034#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9035#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9036#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9037pub enum TransactionMode {
9039 AccessMode(TransactionAccessMode),
9041 IsolationLevel(TransactionIsolationLevel),
9043}
9044
9045impl fmt::Display for TransactionMode {
9046 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9047 use TransactionMode::*;
9048 match self {
9049 AccessMode(access_mode) => write!(f, "{access_mode}"),
9050 IsolationLevel(iso_level) => write!(f, "ISOLATION LEVEL {iso_level}"),
9051 }
9052 }
9053}
9054
9055#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9056#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9057#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9058pub enum TransactionAccessMode {
9060 ReadOnly,
9062 ReadWrite,
9064}
9065
9066impl fmt::Display for TransactionAccessMode {
9067 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9068 use TransactionAccessMode::*;
9069 f.write_str(match self {
9070 ReadOnly => "READ ONLY",
9071 ReadWrite => "READ WRITE",
9072 })
9073 }
9074}
9075
9076#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9077#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9078#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9079pub enum TransactionIsolationLevel {
9081 ReadUncommitted,
9083 ReadCommitted,
9085 RepeatableRead,
9087 Serializable,
9089 Snapshot,
9091}
9092
9093impl fmt::Display for TransactionIsolationLevel {
9094 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9095 use TransactionIsolationLevel::*;
9096 f.write_str(match self {
9097 ReadUncommitted => "READ UNCOMMITTED",
9098 ReadCommitted => "READ COMMITTED",
9099 RepeatableRead => "REPEATABLE READ",
9100 Serializable => "SERIALIZABLE",
9101 Snapshot => "SNAPSHOT",
9102 })
9103 }
9104}
9105
9106#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9111#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9112#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9113pub enum TransactionModifier {
9114 Deferred,
9116 Immediate,
9118 Exclusive,
9120 Try,
9122 Catch,
9124}
9125
9126impl fmt::Display for TransactionModifier {
9127 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9128 use TransactionModifier::*;
9129 f.write_str(match self {
9130 Deferred => "DEFERRED",
9131 Immediate => "IMMEDIATE",
9132 Exclusive => "EXCLUSIVE",
9133 Try => "TRY",
9134 Catch => "CATCH",
9135 })
9136 }
9137}
9138
9139#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9140#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9141#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9142pub enum ShowStatementFilter {
9144 Like(String),
9146 ILike(String),
9148 Where(Expr),
9150 NoKeyword(String),
9152}
9153
9154impl fmt::Display for ShowStatementFilter {
9155 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9156 use ShowStatementFilter::*;
9157 match self {
9158 Like(pattern) => write!(f, "LIKE '{}'", value::escape_single_quote_string(pattern)),
9159 ILike(pattern) => write!(f, "ILIKE {}", value::escape_single_quote_string(pattern)),
9160 Where(expr) => write!(f, "WHERE {expr}"),
9161 NoKeyword(pattern) => write!(f, "'{}'", value::escape_single_quote_string(pattern)),
9162 }
9163 }
9164}
9165
9166#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9167#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9168#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9169pub enum ShowStatementInClause {
9171 IN,
9173 FROM,
9175}
9176
9177impl fmt::Display for ShowStatementInClause {
9178 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9179 use ShowStatementInClause::*;
9180 match self {
9181 FROM => write!(f, "FROM"),
9182 IN => write!(f, "IN"),
9183 }
9184 }
9185}
9186
9187#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9192#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9193#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9194pub enum SqliteOnConflict {
9195 Rollback,
9197 Abort,
9199 Fail,
9201 Ignore,
9203 Replace,
9205}
9206
9207impl fmt::Display for SqliteOnConflict {
9208 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9209 use SqliteOnConflict::*;
9210 match self {
9211 Rollback => write!(f, "OR ROLLBACK"),
9212 Abort => write!(f, "OR ABORT"),
9213 Fail => write!(f, "OR FAIL"),
9214 Ignore => write!(f, "OR IGNORE"),
9215 Replace => write!(f, "OR REPLACE"),
9216 }
9217 }
9218}
9219
9220#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9226#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9227#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9228pub enum MysqlInsertPriority {
9229 LowPriority,
9231 Delayed,
9233 HighPriority,
9235}
9236
9237impl fmt::Display for crate::ast::MysqlInsertPriority {
9238 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9239 use MysqlInsertPriority::*;
9240 match self {
9241 LowPriority => write!(f, "LOW_PRIORITY"),
9242 Delayed => write!(f, "DELAYED"),
9243 HighPriority => write!(f, "HIGH_PRIORITY"),
9244 }
9245 }
9246}
9247
9248#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9249#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9250#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9251pub enum CopySource {
9253 Table {
9255 table_name: ObjectName,
9257 columns: Vec<Ident>,
9260 },
9261 Query(Box<Query>),
9263}
9264
9265#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9266#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9267#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9268pub enum CopyTarget {
9270 Stdin,
9272 Stdout,
9274 File {
9276 filename: String,
9278 },
9279 Program {
9281 command: String,
9283 },
9284}
9285
9286impl fmt::Display for CopyTarget {
9287 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9288 use CopyTarget::*;
9289 match self {
9290 Stdin => write!(f, "STDIN"),
9291 Stdout => write!(f, "STDOUT"),
9292 File { filename } => write!(f, "'{}'", value::escape_single_quote_string(filename)),
9293 Program { command } => write!(
9294 f,
9295 "PROGRAM '{}'",
9296 value::escape_single_quote_string(command)
9297 ),
9298 }
9299 }
9300}
9301
9302#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9303#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9304#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9305pub enum OnCommit {
9307 DeleteRows,
9309 PreserveRows,
9311 Drop,
9313}
9314
9315#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9319#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9320#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9321pub enum CopyOption {
9322 Format(Ident),
9324 Freeze(bool),
9326 Delimiter(char),
9328 Null(String),
9330 Header(bool),
9332 Quote(char),
9334 Escape(char),
9336 ForceQuote(Vec<Ident>),
9338 ForceNotNull(Vec<Ident>),
9340 ForceNull(Vec<Ident>),
9342 Encoding(String),
9344}
9345
9346impl fmt::Display for CopyOption {
9347 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9348 use CopyOption::*;
9349 match self {
9350 Format(name) => write!(f, "FORMAT {name}"),
9351 Freeze(true) => write!(f, "FREEZE"),
9352 Freeze(false) => write!(f, "FREEZE FALSE"),
9353 Delimiter(char) => write!(f, "DELIMITER '{char}'"),
9354 Null(string) => write!(f, "NULL '{}'", value::escape_single_quote_string(string)),
9355 Header(true) => write!(f, "HEADER"),
9356 Header(false) => write!(f, "HEADER FALSE"),
9357 Quote(char) => write!(f, "QUOTE '{char}'"),
9358 Escape(char) => write!(f, "ESCAPE '{char}'"),
9359 ForceQuote(columns) => write!(f, "FORCE_QUOTE ({})", display_comma_separated(columns)),
9360 ForceNotNull(columns) => {
9361 write!(f, "FORCE_NOT_NULL ({})", display_comma_separated(columns))
9362 }
9363 ForceNull(columns) => write!(f, "FORCE_NULL ({})", display_comma_separated(columns)),
9364 Encoding(name) => write!(f, "ENCODING '{}'", value::escape_single_quote_string(name)),
9365 }
9366 }
9367}
9368
9369#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9374#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9375#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9376pub enum CopyLegacyOption {
9377 AcceptAnyDate,
9379 AcceptInvChars(Option<String>),
9381 AddQuotes,
9383 AllowOverwrite,
9385 Binary,
9387 BlankAsNull,
9389 Bzip2,
9391 CleanPath,
9393 CompUpdate {
9395 preset: bool,
9397 enabled: Option<bool>,
9399 },
9400 Csv(Vec<CopyLegacyCsvOption>),
9402 DateFormat(Option<String>),
9404 Delimiter(char),
9406 EmptyAsNull,
9408 Encrypted {
9410 auto: bool,
9412 },
9413 Escape,
9415 Extension(String),
9417 FixedWidth(String),
9419 Gzip,
9421 Header,
9423 IamRole(IamRoleKind),
9425 IgnoreHeader(u64),
9427 Json(Option<String>),
9429 Manifest {
9431 verbose: bool,
9433 },
9434 MaxFileSize(FileSize),
9436 Null(String),
9438 Parallel(Option<bool>),
9440 Parquet,
9442 PartitionBy(UnloadPartitionBy),
9444 Region(String),
9446 RemoveQuotes,
9448 RowGroupSize(FileSize),
9450 StatUpdate(Option<bool>),
9452 TimeFormat(Option<String>),
9454 TruncateColumns,
9456 Zstd,
9458 Credentials(String),
9461}
9462
9463impl fmt::Display for CopyLegacyOption {
9464 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9465 use CopyLegacyOption::*;
9466 match self {
9467 AcceptAnyDate => write!(f, "ACCEPTANYDATE"),
9468 AcceptInvChars(ch) => {
9469 write!(f, "ACCEPTINVCHARS")?;
9470 if let Some(ch) = ch {
9471 write!(f, " '{}'", value::escape_single_quote_string(ch))?;
9472 }
9473 Ok(())
9474 }
9475 AddQuotes => write!(f, "ADDQUOTES"),
9476 AllowOverwrite => write!(f, "ALLOWOVERWRITE"),
9477 Binary => write!(f, "BINARY"),
9478 BlankAsNull => write!(f, "BLANKSASNULL"),
9479 Bzip2 => write!(f, "BZIP2"),
9480 CleanPath => write!(f, "CLEANPATH"),
9481 CompUpdate { preset, enabled } => {
9482 write!(f, "COMPUPDATE")?;
9483 if *preset {
9484 write!(f, " PRESET")?;
9485 } else if let Some(enabled) = enabled {
9486 write!(
9487 f,
9488 "{}",
9489 match enabled {
9490 true => " TRUE",
9491 false => " FALSE",
9492 }
9493 )?;
9494 }
9495 Ok(())
9496 }
9497 Csv(opts) => {
9498 write!(f, "CSV")?;
9499 if !opts.is_empty() {
9500 write!(f, " {}", display_separated(opts, " "))?;
9501 }
9502 Ok(())
9503 }
9504 DateFormat(fmt) => {
9505 write!(f, "DATEFORMAT")?;
9506 if let Some(fmt) = fmt {
9507 write!(f, " '{}'", value::escape_single_quote_string(fmt))?;
9508 }
9509 Ok(())
9510 }
9511 Delimiter(char) => write!(f, "DELIMITER '{char}'"),
9512 EmptyAsNull => write!(f, "EMPTYASNULL"),
9513 Encrypted { auto } => write!(f, "ENCRYPTED{}", if *auto { " AUTO" } else { "" }),
9514 Escape => write!(f, "ESCAPE"),
9515 Extension(ext) => write!(f, "EXTENSION '{}'", value::escape_single_quote_string(ext)),
9516 FixedWidth(spec) => write!(
9517 f,
9518 "FIXEDWIDTH '{}'",
9519 value::escape_single_quote_string(spec)
9520 ),
9521 Gzip => write!(f, "GZIP"),
9522 Header => write!(f, "HEADER"),
9523 IamRole(role) => write!(f, "IAM_ROLE {role}"),
9524 IgnoreHeader(num_rows) => write!(f, "IGNOREHEADER {num_rows}"),
9525 Json(opt) => {
9526 write!(f, "JSON")?;
9527 if let Some(opt) = opt {
9528 write!(f, " AS '{}'", value::escape_single_quote_string(opt))?;
9529 }
9530 Ok(())
9531 }
9532 Manifest { verbose } => write!(f, "MANIFEST{}", if *verbose { " VERBOSE" } else { "" }),
9533 MaxFileSize(file_size) => write!(f, "MAXFILESIZE {file_size}"),
9534 Null(string) => write!(f, "NULL '{}'", value::escape_single_quote_string(string)),
9535 Parallel(enabled) => {
9536 write!(
9537 f,
9538 "PARALLEL{}",
9539 match enabled {
9540 Some(true) => " TRUE",
9541 Some(false) => " FALSE",
9542 _ => "",
9543 }
9544 )
9545 }
9546 Parquet => write!(f, "PARQUET"),
9547 PartitionBy(p) => write!(f, "{p}"),
9548 Region(region) => write!(f, "REGION '{}'", value::escape_single_quote_string(region)),
9549 RemoveQuotes => write!(f, "REMOVEQUOTES"),
9550 RowGroupSize(file_size) => write!(f, "ROWGROUPSIZE {file_size}"),
9551 StatUpdate(enabled) => {
9552 write!(
9553 f,
9554 "STATUPDATE{}",
9555 match enabled {
9556 Some(true) => " TRUE",
9557 Some(false) => " FALSE",
9558 _ => "",
9559 }
9560 )
9561 }
9562 TimeFormat(fmt) => {
9563 write!(f, "TIMEFORMAT")?;
9564 if let Some(fmt) = fmt {
9565 write!(f, " '{}'", value::escape_single_quote_string(fmt))?;
9566 }
9567 Ok(())
9568 }
9569 TruncateColumns => write!(f, "TRUNCATECOLUMNS"),
9570 Zstd => write!(f, "ZSTD"),
9571 Credentials(s) => write!(f, "CREDENTIALS '{}'", value::escape_single_quote_string(s)),
9572 }
9573 }
9574}
9575
9576#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9580#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9581#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9582pub struct FileSize {
9583 pub size: ValueWithSpan,
9585 pub unit: Option<FileSizeUnit>,
9587}
9588
9589impl fmt::Display for FileSize {
9590 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9591 write!(f, "{}", self.size)?;
9592 if let Some(unit) = &self.unit {
9593 write!(f, " {unit}")?;
9594 }
9595 Ok(())
9596 }
9597}
9598
9599#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9601#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9602#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9603pub enum FileSizeUnit {
9604 MB,
9606 GB,
9608}
9609
9610impl fmt::Display for FileSizeUnit {
9611 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9612 match self {
9613 FileSizeUnit::MB => write!(f, "MB"),
9614 FileSizeUnit::GB => write!(f, "GB"),
9615 }
9616 }
9617}
9618
9619#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9625#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9626#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9627pub struct UnloadPartitionBy {
9628 pub columns: Vec<Ident>,
9630 pub include: bool,
9632}
9633
9634impl fmt::Display for UnloadPartitionBy {
9635 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9636 write!(
9637 f,
9638 "PARTITION BY ({}){}",
9639 display_comma_separated(&self.columns),
9640 if self.include { " INCLUDE" } else { "" }
9641 )
9642 }
9643}
9644
9645#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9649#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9650#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9651pub enum IamRoleKind {
9652 Default,
9654 Arn(String),
9656}
9657
9658impl fmt::Display for IamRoleKind {
9659 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9660 match self {
9661 IamRoleKind::Default => write!(f, "DEFAULT"),
9662 IamRoleKind::Arn(arn) => write!(f, "'{arn}'"),
9663 }
9664 }
9665}
9666
9667#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9671#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9672#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9673pub enum CopyLegacyCsvOption {
9674 Header,
9676 Quote(char),
9678 Escape(char),
9680 ForceQuote(Vec<Ident>),
9682 ForceNotNull(Vec<Ident>),
9684}
9685
9686impl fmt::Display for CopyLegacyCsvOption {
9687 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9688 use CopyLegacyCsvOption::*;
9689 match self {
9690 Header => write!(f, "HEADER"),
9691 Quote(char) => write!(f, "QUOTE '{char}'"),
9692 Escape(char) => write!(f, "ESCAPE '{char}'"),
9693 ForceQuote(columns) => write!(f, "FORCE QUOTE {}", display_comma_separated(columns)),
9694 ForceNotNull(columns) => {
9695 write!(f, "FORCE NOT NULL {}", display_comma_separated(columns))
9696 }
9697 }
9698 }
9699}
9700
9701#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9703#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9704#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9705pub enum DiscardObject {
9706 ALL,
9708 PLANS,
9710 SEQUENCES,
9712 TEMP,
9714}
9715
9716impl fmt::Display for DiscardObject {
9717 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9718 match self {
9719 DiscardObject::ALL => f.write_str("ALL"),
9720 DiscardObject::PLANS => f.write_str("PLANS"),
9721 DiscardObject::SEQUENCES => f.write_str("SEQUENCES"),
9722 DiscardObject::TEMP => f.write_str("TEMP"),
9723 }
9724 }
9725}
9726
9727#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9729#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9730#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9731pub enum FlushType {
9732 BinaryLogs,
9734 EngineLogs,
9736 ErrorLogs,
9738 GeneralLogs,
9740 Hosts,
9742 Logs,
9744 Privileges,
9746 OptimizerCosts,
9748 RelayLogs,
9750 SlowLogs,
9752 Status,
9754 UserResources,
9756 Tables,
9758}
9759
9760impl fmt::Display for FlushType {
9761 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9762 match self {
9763 FlushType::BinaryLogs => f.write_str("BINARY LOGS"),
9764 FlushType::EngineLogs => f.write_str("ENGINE LOGS"),
9765 FlushType::ErrorLogs => f.write_str("ERROR LOGS"),
9766 FlushType::GeneralLogs => f.write_str("GENERAL LOGS"),
9767 FlushType::Hosts => f.write_str("HOSTS"),
9768 FlushType::Logs => f.write_str("LOGS"),
9769 FlushType::Privileges => f.write_str("PRIVILEGES"),
9770 FlushType::OptimizerCosts => f.write_str("OPTIMIZER_COSTS"),
9771 FlushType::RelayLogs => f.write_str("RELAY LOGS"),
9772 FlushType::SlowLogs => f.write_str("SLOW LOGS"),
9773 FlushType::Status => f.write_str("STATUS"),
9774 FlushType::UserResources => f.write_str("USER_RESOURCES"),
9775 FlushType::Tables => f.write_str("TABLES"),
9776 }
9777 }
9778}
9779
9780#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9782#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9783#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9784pub enum FlushLocation {
9785 NoWriteToBinlog,
9787 Local,
9789}
9790
9791impl fmt::Display for FlushLocation {
9792 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9793 match self {
9794 FlushLocation::NoWriteToBinlog => f.write_str("NO_WRITE_TO_BINLOG"),
9795 FlushLocation::Local => f.write_str("LOCAL"),
9796 }
9797 }
9798}
9799
9800#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9802#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9803#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9804pub enum ContextModifier {
9805 Local,
9807 Session,
9809 Global,
9811}
9812
9813impl fmt::Display for ContextModifier {
9814 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9815 match self {
9816 Self::Local => {
9817 write!(f, "LOCAL ")
9818 }
9819 Self::Session => {
9820 write!(f, "SESSION ")
9821 }
9822 Self::Global => {
9823 write!(f, "GLOBAL ")
9824 }
9825 }
9826 }
9827}
9828
9829#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9831#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9832pub enum DropFunctionOption {
9833 Restrict,
9835 Cascade,
9837}
9838
9839impl fmt::Display for DropFunctionOption {
9840 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9841 match self {
9842 DropFunctionOption::Restrict => write!(f, "RESTRICT "),
9843 DropFunctionOption::Cascade => write!(f, "CASCADE "),
9844 }
9845 }
9846}
9847
9848#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9850#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9851#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9852pub struct FunctionDesc {
9853 pub name: ObjectName,
9855 pub args: Option<Vec<OperateFunctionArg>>,
9857}
9858
9859impl fmt::Display for FunctionDesc {
9860 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9861 write!(f, "{}", self.name)?;
9862 if let Some(args) = &self.args {
9863 write!(f, "({})", display_comma_separated(args))?;
9864 }
9865 Ok(())
9866 }
9867}
9868
9869#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9871#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9872#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9873pub struct OperateFunctionArg {
9874 pub mode: Option<ArgMode>,
9876 pub name: Option<Ident>,
9878 pub data_type: DataType,
9880 pub default_expr: Option<Expr>,
9882}
9883
9884impl OperateFunctionArg {
9885 pub fn unnamed(data_type: DataType) -> Self {
9887 Self {
9888 mode: None,
9889 name: None,
9890 data_type,
9891 default_expr: None,
9892 }
9893 }
9894
9895 pub fn with_name(name: &str, data_type: DataType) -> Self {
9897 Self {
9898 mode: None,
9899 name: Some(name.into()),
9900 data_type,
9901 default_expr: None,
9902 }
9903 }
9904}
9905
9906impl fmt::Display for OperateFunctionArg {
9907 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9908 if let Some(mode) = &self.mode {
9909 write!(f, "{mode} ")?;
9910 }
9911 if let Some(name) = &self.name {
9912 write!(f, "{name} ")?;
9913 }
9914 write!(f, "{}", self.data_type)?;
9915 if let Some(default_expr) = &self.default_expr {
9916 write!(f, " = {default_expr}")?;
9917 }
9918 Ok(())
9919 }
9920}
9921
9922#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9924#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9925#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9926pub enum ArgMode {
9927 In,
9929 Out,
9931 InOut,
9933 Variadic,
9935}
9936
9937impl fmt::Display for ArgMode {
9938 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9939 match self {
9940 ArgMode::In => write!(f, "IN"),
9941 ArgMode::Out => write!(f, "OUT"),
9942 ArgMode::InOut => write!(f, "INOUT"),
9943 ArgMode::Variadic => write!(f, "VARIADIC"),
9944 }
9945 }
9946}
9947
9948#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9950#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9951#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9952pub enum FunctionBehavior {
9953 Immutable,
9955 Stable,
9957 Volatile,
9959}
9960
9961impl fmt::Display for FunctionBehavior {
9962 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9963 match self {
9964 FunctionBehavior::Immutable => write!(f, "IMMUTABLE"),
9965 FunctionBehavior::Stable => write!(f, "STABLE"),
9966 FunctionBehavior::Volatile => write!(f, "VOLATILE"),
9967 }
9968 }
9969}
9970
9971#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9975#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9976#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9977pub enum FunctionSecurity {
9978 Definer,
9980 Invoker,
9982}
9983
9984impl fmt::Display for FunctionSecurity {
9985 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9986 match self {
9987 FunctionSecurity::Definer => write!(f, "SECURITY DEFINER"),
9988 FunctionSecurity::Invoker => write!(f, "SECURITY INVOKER"),
9989 }
9990 }
9991}
9992
9993#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
9997#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9998#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
9999pub enum FunctionSetValue {
10000 Default,
10002 Values(Vec<Expr>),
10004 FromCurrent,
10006}
10007
10008#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10012#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10013#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10014pub struct FunctionDefinitionSetParam {
10015 pub name: ObjectName,
10017 pub value: FunctionSetValue,
10019}
10020
10021impl fmt::Display for FunctionDefinitionSetParam {
10022 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10023 write!(f, "SET {} ", self.name)?;
10024 match &self.value {
10025 FunctionSetValue::Default => write!(f, "= DEFAULT"),
10026 FunctionSetValue::Values(values) => {
10027 write!(f, "= {}", display_comma_separated(values))
10028 }
10029 FunctionSetValue::FromCurrent => write!(f, "FROM CURRENT"),
10030 }
10031 }
10032}
10033
10034#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10036#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10037#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10038pub enum FunctionCalledOnNull {
10039 CalledOnNullInput,
10041 ReturnsNullOnNullInput,
10043 Strict,
10045}
10046
10047impl fmt::Display for FunctionCalledOnNull {
10048 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10049 match self {
10050 FunctionCalledOnNull::CalledOnNullInput => write!(f, "CALLED ON NULL INPUT"),
10051 FunctionCalledOnNull::ReturnsNullOnNullInput => write!(f, "RETURNS NULL ON NULL INPUT"),
10052 FunctionCalledOnNull::Strict => write!(f, "STRICT"),
10053 }
10054 }
10055}
10056
10057#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10059#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10060#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10061pub enum FunctionParallel {
10062 Unsafe,
10064 Restricted,
10066 Safe,
10068}
10069
10070impl fmt::Display for FunctionParallel {
10071 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10072 match self {
10073 FunctionParallel::Unsafe => write!(f, "PARALLEL UNSAFE"),
10074 FunctionParallel::Restricted => write!(f, "PARALLEL RESTRICTED"),
10075 FunctionParallel::Safe => write!(f, "PARALLEL SAFE"),
10076 }
10077 }
10078}
10079
10080#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10084#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10085#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10086pub enum FunctionDeterminismSpecifier {
10087 Deterministic,
10089 NotDeterministic,
10091}
10092
10093impl fmt::Display for FunctionDeterminismSpecifier {
10094 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10095 match self {
10096 FunctionDeterminismSpecifier::Deterministic => {
10097 write!(f, "DETERMINISTIC")
10098 }
10099 FunctionDeterminismSpecifier::NotDeterministic => {
10100 write!(f, "NOT DETERMINISTIC")
10101 }
10102 }
10103 }
10104}
10105
10106#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10113#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10114#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10115pub enum CreateFunctionBody {
10116 AsBeforeOptions {
10129 body: Expr,
10131 link_symbol: Option<Expr>,
10140 },
10141 AsAfterOptions(Expr),
10153 AsBeginEnd(BeginEndStatements),
10169 Return(Expr),
10180
10181 AsReturnExpr(Expr),
10192
10193 AsReturnSelect(Select),
10204}
10205
10206#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10207#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10208#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10209pub enum CreateFunctionUsing {
10211 Jar(String),
10213 File(String),
10215 Archive(String),
10217}
10218
10219impl fmt::Display for CreateFunctionUsing {
10220 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10221 write!(f, "USING ")?;
10222 match self {
10223 CreateFunctionUsing::Jar(uri) => write!(f, "JAR '{uri}'"),
10224 CreateFunctionUsing::File(uri) => write!(f, "FILE '{uri}'"),
10225 CreateFunctionUsing::Archive(uri) => write!(f, "ARCHIVE '{uri}'"),
10226 }
10227 }
10228}
10229
10230#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10235#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10236#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10237pub struct MacroArg {
10238 pub name: Ident,
10240 pub default_expr: Option<Expr>,
10242}
10243
10244impl MacroArg {
10245 pub fn new(name: &str) -> Self {
10247 Self {
10248 name: name.into(),
10249 default_expr: None,
10250 }
10251 }
10252}
10253
10254impl fmt::Display for MacroArg {
10255 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10256 write!(f, "{}", self.name)?;
10257 if let Some(default_expr) = &self.default_expr {
10258 write!(f, " := {default_expr}")?;
10259 }
10260 Ok(())
10261 }
10262}
10263
10264#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10265#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10266#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10267pub enum MacroDefinition {
10269 Expr(Expr),
10271 Table(Box<Query>),
10273}
10274
10275impl fmt::Display for MacroDefinition {
10276 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10277 match self {
10278 MacroDefinition::Expr(expr) => write!(f, "{expr}")?,
10279 MacroDefinition::Table(query) => write!(f, "{query}")?,
10280 }
10281 Ok(())
10282 }
10283}
10284
10285#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10289#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10290#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10291pub enum SchemaName {
10292 Simple(ObjectName),
10294 UnnamedAuthorization(Ident),
10296 NamedAuthorization(ObjectName, Ident),
10298}
10299
10300impl fmt::Display for SchemaName {
10301 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10302 match self {
10303 SchemaName::Simple(name) => {
10304 write!(f, "{name}")
10305 }
10306 SchemaName::UnnamedAuthorization(authorization) => {
10307 write!(f, "AUTHORIZATION {authorization}")
10308 }
10309 SchemaName::NamedAuthorization(name, authorization) => {
10310 write!(f, "{name} AUTHORIZATION {authorization}")
10311 }
10312 }
10313 }
10314}
10315
10316#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10320#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10321#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10322pub enum SearchModifier {
10323 InNaturalLanguageMode,
10325 InNaturalLanguageModeWithQueryExpansion,
10327 InBooleanMode,
10329 WithQueryExpansion,
10331}
10332
10333impl fmt::Display for SearchModifier {
10334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10335 match self {
10336 Self::InNaturalLanguageMode => {
10337 write!(f, "IN NATURAL LANGUAGE MODE")?;
10338 }
10339 Self::InNaturalLanguageModeWithQueryExpansion => {
10340 write!(f, "IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION")?;
10341 }
10342 Self::InBooleanMode => {
10343 write!(f, "IN BOOLEAN MODE")?;
10344 }
10345 Self::WithQueryExpansion => {
10346 write!(f, "WITH QUERY EXPANSION")?;
10347 }
10348 }
10349
10350 Ok(())
10351 }
10352}
10353
10354#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10356#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10357#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10358pub struct LockTable {
10359 pub table: Ident,
10361 pub alias: Option<Ident>,
10363 pub lock_type: LockTableType,
10365}
10366
10367impl fmt::Display for LockTable {
10368 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10369 let Self {
10370 table: tbl_name,
10371 alias,
10372 lock_type,
10373 } = self;
10374
10375 write!(f, "{tbl_name} ")?;
10376 if let Some(alias) = alias {
10377 write!(f, "AS {alias} ")?;
10378 }
10379 write!(f, "{lock_type}")?;
10380 Ok(())
10381 }
10382}
10383
10384#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10385#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10386#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10387pub enum LockTableType {
10389 Read {
10391 local: bool,
10393 },
10394 Write {
10396 low_priority: bool,
10398 },
10399}
10400
10401impl fmt::Display for LockTableType {
10402 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10403 match self {
10404 Self::Read { local } => {
10405 write!(f, "READ")?;
10406 if *local {
10407 write!(f, " LOCAL")?;
10408 }
10409 }
10410 Self::Write { low_priority } => {
10411 if *low_priority {
10412 write!(f, "LOW_PRIORITY ")?;
10413 }
10414 write!(f, "WRITE")?;
10415 }
10416 }
10417
10418 Ok(())
10419 }
10420}
10421
10422#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10423#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10424#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10425pub struct HiveSetLocation {
10427 pub has_set: bool,
10429 pub location: Ident,
10431}
10432
10433impl fmt::Display for HiveSetLocation {
10434 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10435 if self.has_set {
10436 write!(f, "SET ")?;
10437 }
10438 write!(f, "LOCATION {}", self.location)
10439 }
10440}
10441
10442#[allow(clippy::large_enum_variant)]
10444#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10445#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10446#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10447pub enum MySQLColumnPosition {
10449 First,
10451 After(Ident),
10453}
10454
10455impl Display for MySQLColumnPosition {
10456 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10457 match self {
10458 MySQLColumnPosition::First => write!(f, "FIRST"),
10459 MySQLColumnPosition::After(ident) => {
10460 let column_name = &ident.value;
10461 write!(f, "AFTER {column_name}")
10462 }
10463 }
10464 }
10465}
10466
10467#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10469#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10470#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10471pub enum CreateViewAlgorithm {
10473 Undefined,
10475 Merge,
10477 TempTable,
10479}
10480
10481impl Display for CreateViewAlgorithm {
10482 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10483 match self {
10484 CreateViewAlgorithm::Undefined => write!(f, "UNDEFINED"),
10485 CreateViewAlgorithm::Merge => write!(f, "MERGE"),
10486 CreateViewAlgorithm::TempTable => write!(f, "TEMPTABLE"),
10487 }
10488 }
10489}
10490#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10492#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10493#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10494pub enum CreateViewSecurity {
10496 Definer,
10498 Invoker,
10500}
10501
10502impl Display for CreateViewSecurity {
10503 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10504 match self {
10505 CreateViewSecurity::Definer => write!(f, "DEFINER"),
10506 CreateViewSecurity::Invoker => write!(f, "INVOKER"),
10507 }
10508 }
10509}
10510
10511#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10515#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10516#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10517pub struct CreateViewParams {
10518 pub algorithm: Option<CreateViewAlgorithm>,
10520 pub definer: Option<GranteeName>,
10522 pub security: Option<CreateViewSecurity>,
10524}
10525
10526impl Display for CreateViewParams {
10527 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10528 let CreateViewParams {
10529 algorithm,
10530 definer,
10531 security,
10532 } = self;
10533 if let Some(algorithm) = algorithm {
10534 write!(f, "ALGORITHM = {algorithm} ")?;
10535 }
10536 if let Some(definers) = definer {
10537 write!(f, "DEFINER = {definers} ")?;
10538 }
10539 if let Some(security) = security {
10540 write!(f, "SQL SECURITY {security} ")?;
10541 }
10542 Ok(())
10543 }
10544}
10545
10546#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10547#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10548#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10549pub struct NamedParenthesizedList {
10557 pub key: Ident,
10559 pub name: Option<Ident>,
10561 pub values: Vec<Ident>,
10563}
10564
10565#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10570#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10571#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10572pub struct RowAccessPolicy {
10573 pub policy: ObjectName,
10575 pub on: Vec<Ident>,
10577}
10578
10579impl RowAccessPolicy {
10580 pub fn new(policy: ObjectName, on: Vec<Ident>) -> Self {
10582 Self { policy, on }
10583 }
10584}
10585
10586impl Display for RowAccessPolicy {
10587 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10588 write!(
10589 f,
10590 "WITH ROW ACCESS POLICY {} ON ({})",
10591 self.policy,
10592 display_comma_separated(self.on.as_slice())
10593 )
10594 }
10595}
10596
10597#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10601#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10602#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10603pub struct StorageLifecyclePolicy {
10604 pub policy: ObjectName,
10606 pub on: Vec<Ident>,
10608}
10609
10610impl Display for StorageLifecyclePolicy {
10611 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10612 write!(
10613 f,
10614 "WITH STORAGE LIFECYCLE POLICY {} ON ({})",
10615 self.policy,
10616 display_comma_separated(self.on.as_slice())
10617 )
10618 }
10619}
10620
10621#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10625#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10626#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10627pub struct Tag {
10628 pub key: ObjectName,
10630 pub value: String,
10632}
10633
10634impl Tag {
10635 pub fn new(key: ObjectName, value: String) -> Self {
10637 Self { key, value }
10638 }
10639}
10640
10641impl Display for Tag {
10642 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10643 write!(f, "{}='{}'", self.key, self.value)
10644 }
10645}
10646
10647#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10651#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10652#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10653pub struct ContactEntry {
10654 pub purpose: String,
10656 pub contact: String,
10658}
10659
10660impl Display for ContactEntry {
10661 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10662 write!(f, "{} = {}", self.purpose, self.contact)
10663 }
10664}
10665
10666#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10668#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10669#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10670pub enum CommentDef {
10671 WithEq(String),
10674 WithoutEq(String),
10676}
10677
10678impl Display for CommentDef {
10679 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10680 match self {
10681 CommentDef::WithEq(comment) | CommentDef::WithoutEq(comment) => write!(f, "{comment}"),
10682 }
10683 }
10684}
10685
10686#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10701#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10702#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10703pub enum WrappedCollection<T> {
10704 NoWrapping(T),
10706 Parentheses(T),
10708}
10709
10710impl<T> Display for WrappedCollection<Vec<T>>
10711where
10712 T: Display,
10713{
10714 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10715 match self {
10716 WrappedCollection::NoWrapping(inner) => {
10717 write!(f, "{}", display_comma_separated(inner.as_slice()))
10718 }
10719 WrappedCollection::Parentheses(inner) => {
10720 write!(f, "({})", display_comma_separated(inner.as_slice()))
10721 }
10722 }
10723 }
10724}
10725
10726#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10750#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10751#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10752pub struct UtilityOption {
10753 pub name: Ident,
10755 pub arg: Option<Expr>,
10757}
10758
10759impl Display for UtilityOption {
10760 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10761 if let Some(ref arg) = self.arg {
10762 write!(f, "{} {}", self.name, arg)
10763 } else {
10764 write!(f, "{}", self.name)
10765 }
10766 }
10767}
10768
10769#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10773#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10774#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10775pub struct ShowStatementOptions {
10776 pub show_in: Option<ShowStatementIn>,
10778 pub starts_with: Option<ValueWithSpan>,
10780 pub limit: Option<Expr>,
10782 pub limit_from: Option<ValueWithSpan>,
10784 pub filter_position: Option<ShowStatementFilterPosition>,
10786}
10787
10788impl Display for ShowStatementOptions {
10789 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10790 let (like_in_infix, like_in_suffix) = match &self.filter_position {
10791 Some(ShowStatementFilterPosition::Infix(filter)) => {
10792 (format!(" {filter}"), "".to_string())
10793 }
10794 Some(ShowStatementFilterPosition::Suffix(filter)) => {
10795 ("".to_string(), format!(" {filter}"))
10796 }
10797 None => ("".to_string(), "".to_string()),
10798 };
10799 write!(
10800 f,
10801 "{like_in_infix}{show_in}{starts_with}{limit}{from}{like_in_suffix}",
10802 show_in = match &self.show_in {
10803 Some(i) => format!(" {i}"),
10804 None => String::new(),
10805 },
10806 starts_with = match &self.starts_with {
10807 Some(s) => format!(" STARTS WITH {s}"),
10808 None => String::new(),
10809 },
10810 limit = match &self.limit {
10811 Some(l) => format!(" LIMIT {l}"),
10812 None => String::new(),
10813 },
10814 from = match &self.limit_from {
10815 Some(f) => format!(" FROM {f}"),
10816 None => String::new(),
10817 }
10818 )?;
10819 Ok(())
10820 }
10821}
10822
10823#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10824#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10825#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10826pub enum ShowStatementFilterPosition {
10828 Infix(ShowStatementFilter), Suffix(ShowStatementFilter), }
10833
10834#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10835#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10836#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10837pub enum ShowStatementInParentType {
10839 Account,
10841 Database,
10843 Schema,
10845 Table,
10847 View,
10849}
10850
10851impl fmt::Display for ShowStatementInParentType {
10852 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10853 match self {
10854 ShowStatementInParentType::Account => write!(f, "ACCOUNT"),
10855 ShowStatementInParentType::Database => write!(f, "DATABASE"),
10856 ShowStatementInParentType::Schema => write!(f, "SCHEMA"),
10857 ShowStatementInParentType::Table => write!(f, "TABLE"),
10858 ShowStatementInParentType::View => write!(f, "VIEW"),
10859 }
10860 }
10861}
10862
10863#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10864#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10865#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10866pub struct ShowStatementIn {
10868 pub clause: ShowStatementInClause,
10870 pub parent_type: Option<ShowStatementInParentType>,
10872 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
10874 pub parent_name: Option<ObjectName>,
10875}
10876
10877impl fmt::Display for ShowStatementIn {
10878 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10879 write!(f, "{}", self.clause)?;
10880 if let Some(parent_type) = &self.parent_type {
10881 write!(f, " {parent_type}")?;
10882 }
10883 if let Some(parent_name) = &self.parent_name {
10884 write!(f, " {parent_name}")?;
10885 }
10886 Ok(())
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 struct ShowCharset {
10895 pub is_shorthand: bool,
10898 pub filter: Option<ShowStatementFilter>,
10900}
10901
10902impl fmt::Display for ShowCharset {
10903 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10904 write!(f, "SHOW")?;
10905 if self.is_shorthand {
10906 write!(f, " CHARSET")?;
10907 } else {
10908 write!(f, " CHARACTER SET")?;
10909 }
10910 if let Some(filter) = &self.filter {
10911 write!(f, " {filter}")?;
10912 }
10913 Ok(())
10914 }
10915}
10916
10917#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10918#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10919#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10920pub struct ShowObjects {
10922 pub terse: bool,
10924 pub show_options: ShowStatementOptions,
10926}
10927
10928#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10938#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10939#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10940pub enum JsonNullClause {
10941 NullOnNull,
10943 AbsentOnNull,
10945}
10946
10947impl Display for JsonNullClause {
10948 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10949 match self {
10950 JsonNullClause::NullOnNull => write!(f, "NULL ON NULL"),
10951 JsonNullClause::AbsentOnNull => write!(f, "ABSENT ON NULL"),
10952 }
10953 }
10954}
10955
10956#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10963#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10964#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10965pub struct JsonReturningClause {
10966 pub data_type: DataType,
10968}
10969
10970impl Display for JsonReturningClause {
10971 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10972 write!(f, "RETURNING {}", self.data_type)
10973 }
10974}
10975
10976#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10978#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10979#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10980pub struct RenameTable {
10981 pub old_name: ObjectName,
10983 pub new_name: ObjectName,
10985}
10986
10987impl fmt::Display for RenameTable {
10988 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10989 write!(f, "{} TO {}", self.old_name, self.new_name)?;
10990 Ok(())
10991 }
10992}
10993
10994#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
10996#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
10997#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
10998pub enum TableObject {
10999 TableName(#[cfg_attr(feature = "visitor", visit(with = "visit_relation"))] ObjectName),
11005
11006 TableFunction(Function),
11013
11014 TableQuery(Box<Query>),
11023}
11024
11025impl fmt::Display for TableObject {
11026 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11027 match self {
11028 Self::TableName(table_name) => write!(f, "{table_name}"),
11029 Self::TableFunction(func) => write!(f, "FUNCTION {func}"),
11030 Self::TableQuery(table_query) => write!(f, "({table_query})"),
11031 }
11032 }
11033}
11034
11035#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11037#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11038#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11039pub struct SetSessionAuthorizationParam {
11040 pub scope: ContextModifier,
11042 pub kind: SetSessionAuthorizationParamKind,
11044}
11045
11046impl fmt::Display for SetSessionAuthorizationParam {
11047 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11048 write!(f, "{}", self.kind)
11049 }
11050}
11051
11052#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11054#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11055#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11056pub enum SetSessionAuthorizationParamKind {
11057 Default,
11059
11060 User(Ident),
11062}
11063
11064impl fmt::Display for SetSessionAuthorizationParamKind {
11065 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11066 match self {
11067 SetSessionAuthorizationParamKind::Default => write!(f, "DEFAULT"),
11068 SetSessionAuthorizationParamKind::User(name) => write!(f, "{}", name),
11069 }
11070 }
11071}
11072
11073#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11074#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11075#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11076pub enum SetSessionParamKind {
11078 Generic(SetSessionParamGeneric),
11080 IdentityInsert(SetSessionParamIdentityInsert),
11082 Offsets(SetSessionParamOffsets),
11084 Statistics(SetSessionParamStatistics),
11086}
11087
11088impl fmt::Display for SetSessionParamKind {
11089 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11090 match self {
11091 SetSessionParamKind::Generic(x) => write!(f, "{x}"),
11092 SetSessionParamKind::IdentityInsert(x) => write!(f, "{x}"),
11093 SetSessionParamKind::Offsets(x) => write!(f, "{x}"),
11094 SetSessionParamKind::Statistics(x) => write!(f, "{x}"),
11095 }
11096 }
11097}
11098
11099#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11100#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11101#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11102pub struct SetSessionParamGeneric {
11104 pub names: Vec<String>,
11106 pub value: String,
11108}
11109
11110impl fmt::Display for SetSessionParamGeneric {
11111 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11112 write!(f, "{} {}", display_comma_separated(&self.names), self.value)
11113 }
11114}
11115
11116#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11117#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11118#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11119pub struct SetSessionParamIdentityInsert {
11121 pub obj: ObjectName,
11123 pub value: SessionParamValue,
11125}
11126
11127impl fmt::Display for SetSessionParamIdentityInsert {
11128 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11129 write!(f, "IDENTITY_INSERT {} {}", self.obj, self.value)
11130 }
11131}
11132
11133#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11134#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11135#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11136pub struct SetSessionParamOffsets {
11138 pub keywords: Vec<String>,
11140 pub value: SessionParamValue,
11142}
11143
11144impl fmt::Display for SetSessionParamOffsets {
11145 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11146 write!(
11147 f,
11148 "OFFSETS {} {}",
11149 display_comma_separated(&self.keywords),
11150 self.value
11151 )
11152 }
11153}
11154
11155#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11156#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11157#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11158pub struct SetSessionParamStatistics {
11160 pub topic: SessionParamStatsTopic,
11162 pub value: SessionParamValue,
11164}
11165
11166impl fmt::Display for SetSessionParamStatistics {
11167 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11168 write!(f, "STATISTICS {} {}", self.topic, self.value)
11169 }
11170}
11171
11172#[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 enum SessionParamStatsTopic {
11177 IO,
11179 Profile,
11181 Time,
11183 Xml,
11185}
11186
11187impl fmt::Display for SessionParamStatsTopic {
11188 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11189 match self {
11190 SessionParamStatsTopic::IO => write!(f, "IO"),
11191 SessionParamStatsTopic::Profile => write!(f, "PROFILE"),
11192 SessionParamStatsTopic::Time => write!(f, "TIME"),
11193 SessionParamStatsTopic::Xml => write!(f, "XML"),
11194 }
11195 }
11196}
11197
11198#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11199#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11200#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11201pub enum SessionParamValue {
11203 On,
11205 Off,
11207}
11208
11209impl fmt::Display for SessionParamValue {
11210 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11211 match self {
11212 SessionParamValue::On => write!(f, "ON"),
11213 SessionParamValue::Off => write!(f, "OFF"),
11214 }
11215 }
11216}
11217
11218#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11225#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11226#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11227pub enum StorageSerializationPolicy {
11228 Compatible,
11230 Optimized,
11232}
11233
11234impl Display for StorageSerializationPolicy {
11235 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11236 match self {
11237 StorageSerializationPolicy::Compatible => write!(f, "COMPATIBLE"),
11238 StorageSerializationPolicy::Optimized => write!(f, "OPTIMIZED"),
11239 }
11240 }
11241}
11242
11243#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11250#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11251#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11252pub enum CatalogSyncNamespaceMode {
11253 Nest,
11255 Flatten,
11257}
11258
11259impl Display for CatalogSyncNamespaceMode {
11260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
11261 match self {
11262 CatalogSyncNamespaceMode::Nest => write!(f, "NEST"),
11263 CatalogSyncNamespaceMode::Flatten => write!(f, "FLATTEN"),
11264 }
11265 }
11266}
11267
11268#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11270#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11271#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11272pub enum CopyIntoSnowflakeKind {
11273 Table,
11276 Location,
11279}
11280
11281#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11282#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11283#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11284pub struct PrintStatement {
11286 pub message: Box<Expr>,
11288}
11289
11290impl fmt::Display for PrintStatement {
11291 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11292 write!(f, "PRINT {}", self.message)
11293 }
11294}
11295
11296#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11300#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11301#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11302pub enum WaitForType {
11303 Delay,
11305 Time,
11307}
11308
11309impl fmt::Display for WaitForType {
11310 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11311 match self {
11312 WaitForType::Delay => write!(f, "DELAY"),
11313 WaitForType::Time => write!(f, "TIME"),
11314 }
11315 }
11316}
11317
11318#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11322#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11323#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11324pub struct WaitForStatement {
11325 pub wait_type: WaitForType,
11327 pub expr: Expr,
11329}
11330
11331impl fmt::Display for WaitForStatement {
11332 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11333 write!(f, "WAITFOR {} {}", self.wait_type, self.expr)
11334 }
11335}
11336
11337#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11342#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11343#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11344pub struct ReturnStatement {
11345 pub value: Option<ReturnStatementValue>,
11347}
11348
11349impl fmt::Display for ReturnStatement {
11350 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11351 match &self.value {
11352 Some(ReturnStatementValue::Expr(expr)) => write!(f, "RETURN {expr}"),
11353 None => write!(f, "RETURN"),
11354 }
11355 }
11356}
11357
11358#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11360#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11361#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11362pub enum ReturnStatementValue {
11363 Expr(Expr),
11365}
11366
11367#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11369#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11370#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11371pub struct OpenStatement {
11372 pub cursor_name: Ident,
11374}
11375
11376impl fmt::Display for OpenStatement {
11377 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11378 write!(f, "OPEN {}", self.cursor_name)
11379 }
11380}
11381
11382#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11386#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11387#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11388pub enum NullInclusion {
11389 IncludeNulls,
11391 ExcludeNulls,
11393}
11394
11395impl fmt::Display for NullInclusion {
11396 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11397 match self {
11398 NullInclusion::IncludeNulls => write!(f, "INCLUDE NULLS"),
11399 NullInclusion::ExcludeNulls => write!(f, "EXCLUDE NULLS"),
11400 }
11401 }
11402}
11403
11404#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11412#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11413#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11414pub struct MemberOf {
11415 pub value: Box<Expr>,
11417 pub array: Box<Expr>,
11419}
11420
11421impl fmt::Display for MemberOf {
11422 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11423 write!(f, "{} MEMBER OF({})", self.value, self.array)
11424 }
11425}
11426
11427#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11428#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11429#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11430pub struct ExportData {
11432 pub options: Vec<SqlOption>,
11434 pub query: Box<Query>,
11436 pub connection: Option<ObjectName>,
11438}
11439
11440impl fmt::Display for ExportData {
11441 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11442 if let Some(connection) = &self.connection {
11443 write!(
11444 f,
11445 "EXPORT DATA WITH CONNECTION {connection} OPTIONS({}) AS {}",
11446 display_comma_separated(&self.options),
11447 self.query
11448 )
11449 } else {
11450 write!(
11451 f,
11452 "EXPORT DATA OPTIONS({}) AS {}",
11453 display_comma_separated(&self.options),
11454 self.query
11455 )
11456 }
11457 }
11458}
11459#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11468#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11469#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11470pub struct CreateUser {
11471 pub or_replace: bool,
11473 pub if_not_exists: bool,
11475 pub name: Ident,
11477 pub options: KeyValueOptions,
11479 pub with_tags: bool,
11481 pub tags: KeyValueOptions,
11483}
11484
11485impl fmt::Display for CreateUser {
11486 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11487 write!(f, "CREATE")?;
11488 if self.or_replace {
11489 write!(f, " OR REPLACE")?;
11490 }
11491 write!(f, " USER")?;
11492 if self.if_not_exists {
11493 write!(f, " IF NOT EXISTS")?;
11494 }
11495 write!(f, " {}", self.name)?;
11496 if !self.options.options.is_empty() {
11497 write!(f, " {}", self.options)?;
11498 }
11499 if !self.tags.options.is_empty() {
11500 if self.with_tags {
11501 write!(f, " WITH")?;
11502 }
11503 write!(f, " TAG ({})", self.tags)?;
11504 }
11505 Ok(())
11506 }
11507}
11508
11509#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11521#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11522#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11523pub struct AlterUser {
11524 pub if_exists: bool,
11526 pub name: Ident,
11528 pub rename_to: Option<Ident>,
11531 pub reset_password: bool,
11533 pub abort_all_queries: bool,
11535 pub add_role_delegation: Option<AlterUserAddRoleDelegation>,
11537 pub remove_role_delegation: Option<AlterUserRemoveRoleDelegation>,
11539 pub enroll_mfa: bool,
11541 pub set_default_mfa_method: Option<MfaMethodKind>,
11543 pub remove_mfa_method: Option<MfaMethodKind>,
11545 pub modify_mfa_method: Option<AlterUserModifyMfaMethod>,
11547 pub add_mfa_method_otp: Option<AlterUserAddMfaMethodOtp>,
11549 pub set_policy: Option<AlterUserSetPolicy>,
11551 pub unset_policy: Option<UserPolicyKind>,
11553 pub set_tag: KeyValueOptions,
11555 pub unset_tag: Vec<String>,
11557 pub set_props: KeyValueOptions,
11559 pub unset_props: Vec<String>,
11561 pub password: Option<AlterUserPassword>,
11563}
11564
11565#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11569#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11570#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11571pub struct AlterUserAddRoleDelegation {
11572 pub role: Ident,
11574 pub integration: Ident,
11576}
11577
11578#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11582#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11583#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11584pub struct AlterUserRemoveRoleDelegation {
11585 pub role: Option<Ident>,
11587 pub integration: Ident,
11589}
11590
11591#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11595#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11596#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11597pub struct AlterUserAddMfaMethodOtp {
11598 pub count: Option<ValueWithSpan>,
11600}
11601
11602#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11606#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11607#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11608pub struct AlterUserModifyMfaMethod {
11609 pub method: MfaMethodKind,
11611 pub comment: String,
11613}
11614
11615#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11617#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11618#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11619pub enum MfaMethodKind {
11620 PassKey,
11622 Totp,
11624 Duo,
11626}
11627
11628impl fmt::Display for MfaMethodKind {
11629 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11630 match self {
11631 MfaMethodKind::PassKey => write!(f, "PASSKEY"),
11632 MfaMethodKind::Totp => write!(f, "TOTP"),
11633 MfaMethodKind::Duo => write!(f, "DUO"),
11634 }
11635 }
11636}
11637
11638#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11642#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11643#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11644pub struct AlterUserSetPolicy {
11645 pub policy_kind: UserPolicyKind,
11647 pub policy: Ident,
11649}
11650
11651#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11653#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11654#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11655pub enum UserPolicyKind {
11656 Authentication,
11658 Password,
11660 Session,
11662}
11663
11664impl fmt::Display for UserPolicyKind {
11665 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11666 match self {
11667 UserPolicyKind::Authentication => write!(f, "AUTHENTICATION"),
11668 UserPolicyKind::Password => write!(f, "PASSWORD"),
11669 UserPolicyKind::Session => write!(f, "SESSION"),
11670 }
11671 }
11672}
11673
11674impl fmt::Display for AlterUser {
11675 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11676 write!(f, "ALTER")?;
11677 write!(f, " USER")?;
11678 if self.if_exists {
11679 write!(f, " IF EXISTS")?;
11680 }
11681 write!(f, " {}", self.name)?;
11682 if let Some(new_name) = &self.rename_to {
11683 write!(f, " RENAME TO {new_name}")?;
11684 }
11685 if self.reset_password {
11686 write!(f, " RESET PASSWORD")?;
11687 }
11688 if self.abort_all_queries {
11689 write!(f, " ABORT ALL QUERIES")?;
11690 }
11691 if let Some(role_delegation) = &self.add_role_delegation {
11692 let role = &role_delegation.role;
11693 let integration = &role_delegation.integration;
11694 write!(
11695 f,
11696 " ADD DELEGATED AUTHORIZATION OF ROLE {role} TO SECURITY INTEGRATION {integration}"
11697 )?;
11698 }
11699 if let Some(role_delegation) = &self.remove_role_delegation {
11700 write!(f, " REMOVE DELEGATED")?;
11701 match &role_delegation.role {
11702 Some(role) => write!(f, " AUTHORIZATION OF ROLE {role}")?,
11703 None => write!(f, " AUTHORIZATIONS")?,
11704 }
11705 let integration = &role_delegation.integration;
11706 write!(f, " FROM SECURITY INTEGRATION {integration}")?;
11707 }
11708 if self.enroll_mfa {
11709 write!(f, " ENROLL MFA")?;
11710 }
11711 if let Some(method) = &self.set_default_mfa_method {
11712 write!(f, " SET DEFAULT_MFA_METHOD {method}")?
11713 }
11714 if let Some(method) = &self.remove_mfa_method {
11715 write!(f, " REMOVE MFA METHOD {method}")?;
11716 }
11717 if let Some(modify) = &self.modify_mfa_method {
11718 let method = &modify.method;
11719 let comment = &modify.comment;
11720 write!(
11721 f,
11722 " MODIFY MFA METHOD {method} SET COMMENT '{}'",
11723 value::escape_single_quote_string(comment)
11724 )?;
11725 }
11726 if let Some(add_mfa_method_otp) = &self.add_mfa_method_otp {
11727 write!(f, " ADD MFA METHOD OTP")?;
11728 if let Some(count) = &add_mfa_method_otp.count {
11729 write!(f, " COUNT = {count}")?;
11730 }
11731 }
11732 if let Some(policy) = &self.set_policy {
11733 let policy_kind = &policy.policy_kind;
11734 let name = &policy.policy;
11735 write!(f, " SET {policy_kind} POLICY {name}")?;
11736 }
11737 if let Some(policy_kind) = &self.unset_policy {
11738 write!(f, " UNSET {policy_kind} POLICY")?;
11739 }
11740 if !self.set_tag.options.is_empty() {
11741 write!(f, " SET TAG {}", self.set_tag)?;
11742 }
11743 if !self.unset_tag.is_empty() {
11744 write!(f, " UNSET TAG {}", display_comma_separated(&self.unset_tag))?;
11745 }
11746 let has_props = !self.set_props.options.is_empty();
11747 if has_props {
11748 write!(f, " SET")?;
11749 write!(f, " {}", self.set_props)?;
11750 }
11751 if !self.unset_props.is_empty() {
11752 write!(f, " UNSET {}", display_comma_separated(&self.unset_props))?;
11753 }
11754 if let Some(password) = &self.password {
11755 write!(f, " {}", password)?;
11756 }
11757 Ok(())
11758 }
11759}
11760
11761#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11765#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11766#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11767pub struct AlterUserPassword {
11768 pub encrypted: bool,
11770 pub password: Option<String>,
11772}
11773
11774impl Display for AlterUserPassword {
11775 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11776 if self.encrypted {
11777 write!(f, "ENCRYPTED ")?;
11778 }
11779 write!(f, "PASSWORD")?;
11780 match &self.password {
11781 None => write!(f, " NULL")?,
11782 Some(password) => write!(f, " '{}'", value::escape_single_quote_string(password))?,
11783 }
11784 Ok(())
11785 }
11786}
11787
11788#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11793#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11794#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11795pub enum CreateTableLikeKind {
11796 Parenthesized(CreateTableLike),
11801 Plain(CreateTableLike),
11807}
11808
11809#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11810#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11811#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11812pub enum CreateTableLikeDefaults {
11814 Including,
11816 Excluding,
11818}
11819
11820impl fmt::Display for CreateTableLikeDefaults {
11821 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11822 match self {
11823 CreateTableLikeDefaults::Including => write!(f, "INCLUDING DEFAULTS"),
11824 CreateTableLikeDefaults::Excluding => write!(f, "EXCLUDING DEFAULTS"),
11825 }
11826 }
11827}
11828
11829#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11830#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11831#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11832pub struct CreateTableLike {
11834 pub name: ObjectName,
11836 pub defaults: Option<CreateTableLikeDefaults>,
11838}
11839
11840impl fmt::Display for CreateTableLike {
11841 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11842 write!(f, "LIKE {}", self.name)?;
11843 if let Some(defaults) = &self.defaults {
11844 write!(f, " {defaults}")?;
11845 }
11846 Ok(())
11847 }
11848}
11849
11850#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11854#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11855#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11856pub enum RefreshModeKind {
11857 Auto,
11859 Full,
11861 Incremental,
11863}
11864
11865impl fmt::Display for RefreshModeKind {
11866 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11867 match self {
11868 RefreshModeKind::Auto => write!(f, "AUTO"),
11869 RefreshModeKind::Full => write!(f, "FULL"),
11870 RefreshModeKind::Incremental => write!(f, "INCREMENTAL"),
11871 }
11872 }
11873}
11874
11875#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11879#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11880#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11881pub enum InitializeKind {
11882 OnCreate,
11884 OnSchedule,
11886}
11887
11888impl fmt::Display for InitializeKind {
11889 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11890 match self {
11891 InitializeKind::OnCreate => write!(f, "ON_CREATE"),
11892 InitializeKind::OnSchedule => write!(f, "ON_SCHEDULE"),
11893 }
11894 }
11895}
11896
11897#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11904#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11905#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11906pub struct VacuumStatement {
11907 pub full: bool,
11909 pub sort_only: bool,
11911 pub delete_only: bool,
11913 pub reindex: bool,
11915 pub recluster: bool,
11917 pub table_name: Option<ObjectName>,
11919 pub threshold: Option<ValueWithSpan>,
11921 pub boost: bool,
11923}
11924
11925impl fmt::Display for VacuumStatement {
11926 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
11927 write!(
11928 f,
11929 "VACUUM{}{}{}{}{}",
11930 if self.full { " FULL" } else { "" },
11931 if self.sort_only { " SORT ONLY" } else { "" },
11932 if self.delete_only { " DELETE ONLY" } else { "" },
11933 if self.reindex { " REINDEX" } else { "" },
11934 if self.recluster { " RECLUSTER" } else { "" },
11935 )?;
11936 if let Some(table_name) = &self.table_name {
11937 write!(f, " {table_name}")?;
11938 }
11939 if let Some(threshold) = &self.threshold {
11940 write!(f, " TO {threshold} PERCENT")?;
11941 }
11942 if self.boost {
11943 write!(f, " BOOST")?;
11944 }
11945 Ok(())
11946 }
11947}
11948
11949#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11951#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11952#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11953pub enum Reset {
11954 ALL,
11956
11957 ConfigurationParameter(ObjectName),
11959}
11960
11961#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11966#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11967#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11968pub struct ResetStatement {
11969 pub reset: Reset,
11971}
11972
11973#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
11979#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11980#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
11981pub struct OptimizerHint {
11982 pub prefix: String,
11989 pub text: String,
11991 pub style: OptimizerHintStyle,
11996}
11997
11998#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
12000#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
12001#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
12002pub enum OptimizerHintStyle {
12003 SingleLine {
12006 prefix: String,
12008 },
12009 MultiLine,
12012}
12013
12014impl fmt::Display for OptimizerHint {
12015 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
12016 match &self.style {
12017 OptimizerHintStyle::SingleLine { prefix } => {
12018 f.write_str(prefix)?;
12019 f.write_str(&self.prefix)?;
12020 f.write_str("+")?;
12021 f.write_str(&self.text)
12022 }
12023 OptimizerHintStyle::MultiLine => {
12024 f.write_str("/*")?;
12025 f.write_str(&self.prefix)?;
12026 f.write_str("+")?;
12027 f.write_str(&self.text)?;
12028 f.write_str("*/")
12029 }
12030 }
12031 }
12032}
12033
12034impl fmt::Display for ResetStatement {
12035 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
12036 match &self.reset {
12037 Reset::ALL => write!(f, "RESET ALL"),
12038 Reset::ConfigurationParameter(param) => write!(f, "RESET {}", param),
12039 }
12040 }
12041}
12042
12043impl From<Set> for Statement {
12044 fn from(s: Set) -> Self {
12045 Self::Set(s)
12046 }
12047}
12048
12049impl From<Query> for Statement {
12050 fn from(q: Query) -> Self {
12051 Box::new(q).into()
12052 }
12053}
12054
12055impl From<Box<Query>> for Statement {
12056 fn from(q: Box<Query>) -> Self {
12057 Self::Query(q)
12058 }
12059}
12060
12061impl From<Insert> for Statement {
12062 fn from(i: Insert) -> Self {
12063 Self::Insert(i)
12064 }
12065}
12066
12067impl From<Update> for Statement {
12068 fn from(u: Update) -> Self {
12069 Self::Update(u)
12070 }
12071}
12072
12073impl From<CreateView> for Statement {
12074 fn from(cv: CreateView) -> Self {
12075 Self::CreateView(cv)
12076 }
12077}
12078
12079impl From<CreateRole> for Statement {
12080 fn from(cr: CreateRole) -> Self {
12081 Self::CreateRole(cr)
12082 }
12083}
12084
12085impl From<AlterTable> for Statement {
12086 fn from(at: AlterTable) -> Self {
12087 Self::AlterTable(at)
12088 }
12089}
12090
12091impl From<DropFunction> for Statement {
12092 fn from(df: DropFunction) -> Self {
12093 Self::DropFunction(df)
12094 }
12095}
12096
12097impl From<CreateExtension> for Statement {
12098 fn from(ce: CreateExtension) -> Self {
12099 Self::CreateExtension(ce)
12100 }
12101}
12102
12103impl From<CreateCollation> for Statement {
12104 fn from(c: CreateCollation) -> Self {
12105 Self::CreateCollation(c)
12106 }
12107}
12108
12109impl From<DropExtension> for Statement {
12110 fn from(de: DropExtension) -> Self {
12111 Self::DropExtension(de)
12112 }
12113}
12114
12115impl From<CaseStatement> for Statement {
12116 fn from(c: CaseStatement) -> Self {
12117 Self::Case(c)
12118 }
12119}
12120
12121impl From<IfStatement> for Statement {
12122 fn from(i: IfStatement) -> Self {
12123 Self::If(i)
12124 }
12125}
12126
12127impl From<WhileStatement> for Statement {
12128 fn from(w: WhileStatement) -> Self {
12129 Self::While(w)
12130 }
12131}
12132
12133impl From<RaiseStatement> for Statement {
12134 fn from(r: RaiseStatement) -> Self {
12135 Self::Raise(r)
12136 }
12137}
12138
12139impl From<ThrowStatement> for Statement {
12140 fn from(t: ThrowStatement) -> Self {
12141 Self::Throw(t)
12142 }
12143}
12144
12145impl From<Function> for Statement {
12146 fn from(f: Function) -> Self {
12147 Self::Call(f)
12148 }
12149}
12150
12151impl From<OpenStatement> for Statement {
12152 fn from(o: OpenStatement) -> Self {
12153 Self::Open(o)
12154 }
12155}
12156
12157impl From<Delete> for Statement {
12158 fn from(d: Delete) -> Self {
12159 Self::Delete(d)
12160 }
12161}
12162
12163impl From<CreateTable> for Statement {
12164 fn from(c: CreateTable) -> Self {
12165 Self::CreateTable(c)
12166 }
12167}
12168
12169impl From<CreateIndex> for Statement {
12170 fn from(c: CreateIndex) -> Self {
12171 Self::CreateIndex(c)
12172 }
12173}
12174
12175impl From<CreateServerStatement> for Statement {
12176 fn from(c: CreateServerStatement) -> Self {
12177 Self::CreateServer(c)
12178 }
12179}
12180
12181impl From<CreateConnector> for Statement {
12182 fn from(c: CreateConnector) -> Self {
12183 Self::CreateConnector(c)
12184 }
12185}
12186
12187impl From<CreateOperator> for Statement {
12188 fn from(c: CreateOperator) -> Self {
12189 Self::CreateOperator(c)
12190 }
12191}
12192
12193impl From<CreateOperatorFamily> for Statement {
12194 fn from(c: CreateOperatorFamily) -> Self {
12195 Self::CreateOperatorFamily(c)
12196 }
12197}
12198
12199impl From<CreateOperatorClass> for Statement {
12200 fn from(c: CreateOperatorClass) -> Self {
12201 Self::CreateOperatorClass(c)
12202 }
12203}
12204
12205impl From<AlterSchema> for Statement {
12206 fn from(a: AlterSchema) -> Self {
12207 Self::AlterSchema(a)
12208 }
12209}
12210
12211impl From<AlterFunction> for Statement {
12212 fn from(a: AlterFunction) -> Self {
12213 Self::AlterFunction(a)
12214 }
12215}
12216
12217impl From<AlterType> for Statement {
12218 fn from(a: AlterType) -> Self {
12219 Self::AlterType(a)
12220 }
12221}
12222
12223impl From<AlterCollation> for Statement {
12224 fn from(a: AlterCollation) -> Self {
12225 Self::AlterCollation(a)
12226 }
12227}
12228
12229impl From<AlterOperator> for Statement {
12230 fn from(a: AlterOperator) -> Self {
12231 Self::AlterOperator(a)
12232 }
12233}
12234
12235impl From<AlterOperatorFamily> for Statement {
12236 fn from(a: AlterOperatorFamily) -> Self {
12237 Self::AlterOperatorFamily(a)
12238 }
12239}
12240
12241impl From<AlterOperatorClass> for Statement {
12242 fn from(a: AlterOperatorClass) -> Self {
12243 Self::AlterOperatorClass(a)
12244 }
12245}
12246
12247impl From<Merge> for Statement {
12248 fn from(m: Merge) -> Self {
12249 Self::Merge(m)
12250 }
12251}
12252
12253impl From<AlterUser> for Statement {
12254 fn from(a: AlterUser) -> Self {
12255 Self::AlterUser(a)
12256 }
12257}
12258
12259impl From<DropDomain> for Statement {
12260 fn from(d: DropDomain) -> Self {
12261 Self::DropDomain(d)
12262 }
12263}
12264
12265impl From<ShowCharset> for Statement {
12266 fn from(s: ShowCharset) -> Self {
12267 Self::ShowCharset(s)
12268 }
12269}
12270
12271impl From<ShowObjects> for Statement {
12272 fn from(s: ShowObjects) -> Self {
12273 Self::ShowObjects(s)
12274 }
12275}
12276
12277impl From<Use> for Statement {
12278 fn from(u: Use) -> Self {
12279 Self::Use(u)
12280 }
12281}
12282
12283impl From<CreateFunction> for Statement {
12284 fn from(c: CreateFunction) -> Self {
12285 Self::CreateFunction(c)
12286 }
12287}
12288
12289impl From<CreateTrigger> for Statement {
12290 fn from(c: CreateTrigger) -> Self {
12291 Self::CreateTrigger(c)
12292 }
12293}
12294
12295impl From<DropTrigger> for Statement {
12296 fn from(d: DropTrigger) -> Self {
12297 Self::DropTrigger(d)
12298 }
12299}
12300
12301impl From<DropOperator> for Statement {
12302 fn from(d: DropOperator) -> Self {
12303 Self::DropOperator(d)
12304 }
12305}
12306
12307impl From<DropOperatorFamily> for Statement {
12308 fn from(d: DropOperatorFamily) -> Self {
12309 Self::DropOperatorFamily(d)
12310 }
12311}
12312
12313impl From<DropOperatorClass> for Statement {
12314 fn from(d: DropOperatorClass) -> Self {
12315 Self::DropOperatorClass(d)
12316 }
12317}
12318
12319impl From<DenyStatement> for Statement {
12320 fn from(d: DenyStatement) -> Self {
12321 Self::Deny(d)
12322 }
12323}
12324
12325impl From<CreateDomain> for Statement {
12326 fn from(c: CreateDomain) -> Self {
12327 Self::CreateDomain(c)
12328 }
12329}
12330
12331impl From<RenameTable> for Statement {
12332 fn from(r: RenameTable) -> Self {
12333 vec![r].into()
12334 }
12335}
12336
12337impl From<Vec<RenameTable>> for Statement {
12338 fn from(r: Vec<RenameTable>) -> Self {
12339 Self::RenameTable(r)
12340 }
12341}
12342
12343impl From<PrintStatement> for Statement {
12344 fn from(p: PrintStatement) -> Self {
12345 Self::Print(p)
12346 }
12347}
12348
12349impl From<ReturnStatement> for Statement {
12350 fn from(r: ReturnStatement) -> Self {
12351 Self::Return(r)
12352 }
12353}
12354
12355impl From<ExportData> for Statement {
12356 fn from(e: ExportData) -> Self {
12357 Self::ExportData(e)
12358 }
12359}
12360
12361impl From<CreateUser> for Statement {
12362 fn from(c: CreateUser) -> Self {
12363 Self::CreateUser(c)
12364 }
12365}
12366
12367impl From<VacuumStatement> for Statement {
12368 fn from(v: VacuumStatement) -> Self {
12369 Self::Vacuum(v)
12370 }
12371}
12372
12373impl From<ResetStatement> for Statement {
12374 fn from(r: ResetStatement) -> Self {
12375 Self::Reset(r)
12376 }
12377}
12378
12379#[cfg(test)]
12380mod tests {
12381 use crate::tokenizer::Location;
12382
12383 use super::*;
12384
12385 #[test]
12386 fn test_window_frame_default() {
12387 let window_frame = WindowFrame::default();
12388 assert_eq!(WindowFrameBound::Preceding(None), window_frame.start_bound);
12389 }
12390
12391 #[test]
12392 fn test_grouping_sets_display() {
12393 let grouping_sets = Expr::GroupingSets(vec![
12395 vec![Expr::Identifier(Ident::new("a"))],
12396 vec![Expr::Identifier(Ident::new("b"))],
12397 ]);
12398 assert_eq!("GROUPING SETS ((a), (b))", format!("{grouping_sets}"));
12399
12400 let grouping_sets = Expr::GroupingSets(vec![vec![
12402 Expr::Identifier(Ident::new("a")),
12403 Expr::Identifier(Ident::new("b")),
12404 ]]);
12405 assert_eq!("GROUPING SETS ((a, b))", format!("{grouping_sets}"));
12406
12407 let grouping_sets = Expr::GroupingSets(vec![
12409 vec![
12410 Expr::Identifier(Ident::new("a")),
12411 Expr::Identifier(Ident::new("b")),
12412 ],
12413 vec![
12414 Expr::Identifier(Ident::new("c")),
12415 Expr::Identifier(Ident::new("d")),
12416 ],
12417 ]);
12418 assert_eq!("GROUPING SETS ((a, b), (c, d))", format!("{grouping_sets}"));
12419 }
12420
12421 #[test]
12422 fn test_rollup_display() {
12423 let rollup = Expr::Rollup(vec![vec![Expr::Identifier(Ident::new("a"))]]);
12424 assert_eq!("ROLLUP (a)", format!("{rollup}"));
12425
12426 let rollup = Expr::Rollup(vec![vec![
12427 Expr::Identifier(Ident::new("a")),
12428 Expr::Identifier(Ident::new("b")),
12429 ]]);
12430 assert_eq!("ROLLUP ((a, b))", format!("{rollup}"));
12431
12432 let rollup = Expr::Rollup(vec![
12433 vec![Expr::Identifier(Ident::new("a"))],
12434 vec![Expr::Identifier(Ident::new("b"))],
12435 ]);
12436 assert_eq!("ROLLUP (a, b)", format!("{rollup}"));
12437
12438 let rollup = Expr::Rollup(vec![
12439 vec![Expr::Identifier(Ident::new("a"))],
12440 vec![
12441 Expr::Identifier(Ident::new("b")),
12442 Expr::Identifier(Ident::new("c")),
12443 ],
12444 vec![Expr::Identifier(Ident::new("d"))],
12445 ]);
12446 assert_eq!("ROLLUP (a, (b, c), d)", format!("{rollup}"));
12447 }
12448
12449 #[test]
12450 fn test_cube_display() {
12451 let cube = Expr::Cube(vec![vec![Expr::Identifier(Ident::new("a"))]]);
12452 assert_eq!("CUBE (a)", format!("{cube}"));
12453
12454 let cube = Expr::Cube(vec![vec![
12455 Expr::Identifier(Ident::new("a")),
12456 Expr::Identifier(Ident::new("b")),
12457 ]]);
12458 assert_eq!("CUBE ((a, b))", format!("{cube}"));
12459
12460 let cube = Expr::Cube(vec![
12461 vec![Expr::Identifier(Ident::new("a"))],
12462 vec![Expr::Identifier(Ident::new("b"))],
12463 ]);
12464 assert_eq!("CUBE (a, b)", format!("{cube}"));
12465
12466 let cube = Expr::Cube(vec![
12467 vec![Expr::Identifier(Ident::new("a"))],
12468 vec![
12469 Expr::Identifier(Ident::new("b")),
12470 Expr::Identifier(Ident::new("c")),
12471 ],
12472 vec![Expr::Identifier(Ident::new("d"))],
12473 ]);
12474 assert_eq!("CUBE (a, (b, c), d)", format!("{cube}"));
12475 }
12476
12477 #[test]
12478 fn test_interval_display() {
12479 let interval = Expr::Interval(Interval {
12480 value: Box::new(Expr::Value(
12481 Value::SingleQuotedString(String::from("123:45.67")).with_empty_span(),
12482 )),
12483 leading_field: Some(DateTimeField::Minute),
12484 leading_precision: Some(10),
12485 last_field: Some(DateTimeField::Second),
12486 fractional_seconds_precision: Some(9),
12487 });
12488 assert_eq!(
12489 "INTERVAL '123:45.67' MINUTE (10) TO SECOND (9)",
12490 format!("{interval}"),
12491 );
12492
12493 let interval = Expr::Interval(Interval {
12494 value: Box::new(Expr::Value(
12495 Value::SingleQuotedString(String::from("5")).with_empty_span(),
12496 )),
12497 leading_field: Some(DateTimeField::Second),
12498 leading_precision: Some(1),
12499 last_field: None,
12500 fractional_seconds_precision: Some(3),
12501 });
12502 assert_eq!("INTERVAL '5' SECOND (1, 3)", format!("{interval}"));
12503 }
12504
12505 #[test]
12506 fn test_one_or_many_with_parens_deref() {
12507 use core::ops::Index;
12508
12509 let one = OneOrManyWithParens::One("a");
12510
12511 assert_eq!(one.deref(), &["a"]);
12512 assert_eq!(<OneOrManyWithParens<_> as Deref>::deref(&one), &["a"]);
12513
12514 assert_eq!(one[0], "a");
12515 assert_eq!(one.index(0), &"a");
12516 assert_eq!(
12517 <<OneOrManyWithParens<_> as Deref>::Target as Index<usize>>::index(&one, 0),
12518 &"a"
12519 );
12520
12521 assert_eq!(one.len(), 1);
12522 assert_eq!(<OneOrManyWithParens<_> as Deref>::Target::len(&one), 1);
12523
12524 let many1 = OneOrManyWithParens::Many(vec!["b"]);
12525
12526 assert_eq!(many1.deref(), &["b"]);
12527 assert_eq!(<OneOrManyWithParens<_> as Deref>::deref(&many1), &["b"]);
12528
12529 assert_eq!(many1[0], "b");
12530 assert_eq!(many1.index(0), &"b");
12531 assert_eq!(
12532 <<OneOrManyWithParens<_> as Deref>::Target as Index<usize>>::index(&many1, 0),
12533 &"b"
12534 );
12535
12536 assert_eq!(many1.len(), 1);
12537 assert_eq!(<OneOrManyWithParens<_> as Deref>::Target::len(&many1), 1);
12538
12539 let many2 = OneOrManyWithParens::Many(vec!["c", "d"]);
12540
12541 assert_eq!(many2.deref(), &["c", "d"]);
12542 assert_eq!(
12543 <OneOrManyWithParens<_> as Deref>::deref(&many2),
12544 &["c", "d"]
12545 );
12546
12547 assert_eq!(many2[0], "c");
12548 assert_eq!(many2.index(0), &"c");
12549 assert_eq!(
12550 <<OneOrManyWithParens<_> as Deref>::Target as Index<usize>>::index(&many2, 0),
12551 &"c"
12552 );
12553
12554 assert_eq!(many2[1], "d");
12555 assert_eq!(many2.index(1), &"d");
12556 assert_eq!(
12557 <<OneOrManyWithParens<_> as Deref>::Target as Index<usize>>::index(&many2, 1),
12558 &"d"
12559 );
12560
12561 assert_eq!(many2.len(), 2);
12562 assert_eq!(<OneOrManyWithParens<_> as Deref>::Target::len(&many2), 2);
12563 }
12564
12565 #[test]
12566 fn test_one_or_many_with_parens_as_ref() {
12567 let one = OneOrManyWithParens::One("a");
12568
12569 assert_eq!(one.as_ref(), &["a"]);
12570 assert_eq!(<OneOrManyWithParens<_> as AsRef<_>>::as_ref(&one), &["a"]);
12571
12572 let many1 = OneOrManyWithParens::Many(vec!["b"]);
12573
12574 assert_eq!(many1.as_ref(), &["b"]);
12575 assert_eq!(<OneOrManyWithParens<_> as AsRef<_>>::as_ref(&many1), &["b"]);
12576
12577 let many2 = OneOrManyWithParens::Many(vec!["c", "d"]);
12578
12579 assert_eq!(many2.as_ref(), &["c", "d"]);
12580 assert_eq!(
12581 <OneOrManyWithParens<_> as AsRef<_>>::as_ref(&many2),
12582 &["c", "d"]
12583 );
12584 }
12585
12586 #[test]
12587 fn test_one_or_many_with_parens_ref_into_iter() {
12588 let one = OneOrManyWithParens::One("a");
12589
12590 assert_eq!(Vec::from_iter(&one), vec![&"a"]);
12591
12592 let many1 = OneOrManyWithParens::Many(vec!["b"]);
12593
12594 assert_eq!(Vec::from_iter(&many1), vec![&"b"]);
12595
12596 let many2 = OneOrManyWithParens::Many(vec!["c", "d"]);
12597
12598 assert_eq!(Vec::from_iter(&many2), vec![&"c", &"d"]);
12599 }
12600
12601 #[test]
12602 fn test_one_or_many_with_parens_value_into_iter() {
12603 use core::iter::once;
12604
12605 fn test_steps<I>(ours: OneOrManyWithParens<usize>, inner: I, n: usize)
12607 where
12608 I: IntoIterator<Item = usize, IntoIter: DoubleEndedIterator + Clone> + Clone,
12609 {
12610 fn checks<I>(ours: OneOrManyWithParensIntoIter<usize>, inner: I)
12611 where
12612 I: Iterator<Item = usize> + Clone + DoubleEndedIterator,
12613 {
12614 assert_eq!(ours.size_hint(), inner.size_hint());
12615 assert_eq!(ours.clone().count(), inner.clone().count());
12616
12617 assert_eq!(
12618 ours.clone().fold(1, |a, v| a + v),
12619 inner.clone().fold(1, |a, v| a + v)
12620 );
12621
12622 assert_eq!(Vec::from_iter(ours.clone()), Vec::from_iter(inner.clone()));
12623 assert_eq!(
12624 Vec::from_iter(ours.clone().rev()),
12625 Vec::from_iter(inner.clone().rev())
12626 );
12627 }
12628
12629 let mut ours_next = ours.clone().into_iter();
12630 let mut inner_next = inner.clone().into_iter();
12631
12632 for _ in 0..n {
12633 checks(ours_next.clone(), inner_next.clone());
12634
12635 assert_eq!(ours_next.next(), inner_next.next());
12636 }
12637
12638 let mut ours_next_back = ours.clone().into_iter();
12639 let mut inner_next_back = inner.clone().into_iter();
12640
12641 for _ in 0..n {
12642 checks(ours_next_back.clone(), inner_next_back.clone());
12643
12644 assert_eq!(ours_next_back.next_back(), inner_next_back.next_back());
12645 }
12646
12647 let mut ours_mixed = ours.clone().into_iter();
12648 let mut inner_mixed = inner.clone().into_iter();
12649
12650 for i in 0..n {
12651 checks(ours_mixed.clone(), inner_mixed.clone());
12652
12653 if i % 2 == 0 {
12654 assert_eq!(ours_mixed.next_back(), inner_mixed.next_back());
12655 } else {
12656 assert_eq!(ours_mixed.next(), inner_mixed.next());
12657 }
12658 }
12659
12660 let mut ours_mixed2 = ours.into_iter();
12661 let mut inner_mixed2 = inner.into_iter();
12662
12663 for i in 0..n {
12664 checks(ours_mixed2.clone(), inner_mixed2.clone());
12665
12666 if i % 2 == 0 {
12667 assert_eq!(ours_mixed2.next(), inner_mixed2.next());
12668 } else {
12669 assert_eq!(ours_mixed2.next_back(), inner_mixed2.next_back());
12670 }
12671 }
12672 }
12673
12674 test_steps(OneOrManyWithParens::One(1), once(1), 3);
12675 test_steps(OneOrManyWithParens::Many(vec![2]), vec![2], 3);
12676 test_steps(OneOrManyWithParens::Many(vec![3, 4]), vec![3, 4], 4);
12677 }
12678
12679 #[test]
12682 fn test_ident_ord() {
12683 let mut a = Ident::with_span(Span::new(Location::new(1, 1), Location::new(1, 1)), "a");
12684 let mut b = Ident::with_span(Span::new(Location::new(2, 2), Location::new(2, 2)), "b");
12685
12686 assert!(a < b);
12687 std::mem::swap(&mut a.span, &mut b.span);
12688 assert!(a < b);
12689 }
12690}