1#[cfg(not(feature = "std"))]
19use alloc::{boxed::Box, vec::Vec};
20
21use helpers::attached_token::AttachedToken;
22#[cfg(feature = "serde")]
23use serde::{Deserialize, Serialize};
24
25#[cfg(feature = "visitor")]
26use sqlparser_derive::{Visit, VisitMut};
27
28use crate::{
29 ast::*,
30 display_utils::{indented_list, SpaceOrNewline},
31 tokenizer::{Token, TokenWithSpan},
32};
33
34#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
37#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
38#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
39#[cfg_attr(feature = "visitor", visit(with = "visit_query"))]
40pub struct Query {
41 pub with: Option<With>,
43 pub body: Box<SetExpr>,
45 pub order_by: Option<OrderBy>,
47 pub limit_clause: Option<LimitClause>,
49 pub fetch: Option<Fetch>,
51 pub locks: Vec<LockClause>,
53 pub for_clause: Option<ForClause>,
57 pub settings: Option<Vec<Setting>>,
61 pub format_clause: Option<FormatClause>,
66
67 pub pipe_operators: Vec<PipeOperator>,
69}
70
71impl fmt::Display for Query {
72 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
73 if let Some(ref with) = self.with {
74 with.fmt(f)?;
75 SpaceOrNewline.fmt(f)?;
76 }
77 self.body.fmt(f)?;
78 if let Some(ref order_by) = self.order_by {
79 f.write_str(" ")?;
80 order_by.fmt(f)?;
81 }
82
83 if let Some(ref limit_clause) = self.limit_clause {
84 limit_clause.fmt(f)?;
85 }
86 if let Some(ref settings) = self.settings {
87 f.write_str(" SETTINGS ")?;
88 display_comma_separated(settings).fmt(f)?;
89 }
90 if let Some(ref fetch) = self.fetch {
91 f.write_str(" ")?;
92 fetch.fmt(f)?;
93 }
94 if !self.locks.is_empty() {
95 f.write_str(" ")?;
96 display_separated(&self.locks, " ").fmt(f)?;
97 }
98 if let Some(ref for_clause) = self.for_clause {
99 f.write_str(" ")?;
100 for_clause.fmt(f)?;
101 }
102 if let Some(ref format) = self.format_clause {
103 f.write_str(" ")?;
104 format.fmt(f)?;
105 }
106 for pipe_operator in &self.pipe_operators {
107 f.write_str(" |> ")?;
108 pipe_operator.fmt(f)?;
109 }
110 Ok(())
111 }
112}
113
114#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
120#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
121#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
122pub struct ProjectionSelect {
123 pub projection: Vec<SelectItem>,
125 pub order_by: Option<OrderBy>,
127 pub group_by: Option<GroupByExpr>,
129}
130
131impl fmt::Display for ProjectionSelect {
132 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
133 write!(f, "SELECT {}", display_comma_separated(&self.projection))?;
134 if let Some(ref group_by) = self.group_by {
135 write!(f, " {group_by}")?;
136 }
137 if let Some(ref order_by) = self.order_by {
138 write!(f, " {order_by}")?;
139 }
140 Ok(())
141 }
142}
143
144#[allow(clippy::large_enum_variant)]
147#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
148#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
149#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
150pub enum SetExpr {
151 Select(Box<Select>),
153 Query(Box<Query>),
156 SetOperation {
159 left: Box<SetExpr>,
161 op: SetOperator,
163 set_quantifier: SetQuantifier,
165 right: Box<SetExpr>,
167 },
168 Values(Values),
170 Insert(Statement),
172 Update(Statement),
174 Delete(Statement),
176 Merge(Statement),
178 Table(Box<Table>),
180}
181
182impl SetExpr {
183 pub fn as_select(&self) -> Option<&Select> {
185 if let Self::Select(select) = self {
186 Some(&**select)
187 } else {
188 None
189 }
190 }
191}
192
193impl fmt::Display for SetExpr {
194 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
195 match self {
196 SetExpr::Select(s) => s.fmt(f),
197 SetExpr::Query(q) => {
198 f.write_str("(")?;
199 q.fmt(f)?;
200 f.write_str(")")
201 }
202 SetExpr::Values(v) => v.fmt(f),
203 SetExpr::Insert(v) => v.fmt(f),
204 SetExpr::Update(v) => v.fmt(f),
205 SetExpr::Delete(v) => v.fmt(f),
206 SetExpr::Merge(v) => v.fmt(f),
207 SetExpr::Table(t) => t.fmt(f),
208 SetExpr::SetOperation {
209 left,
210 right,
211 op,
212 set_quantifier,
213 } => {
214 left.fmt(f)?;
215 SpaceOrNewline.fmt(f)?;
216 op.fmt(f)?;
217 match set_quantifier {
218 SetQuantifier::All
219 | SetQuantifier::Distinct
220 | SetQuantifier::ByName
221 | SetQuantifier::AllByName
222 | SetQuantifier::DistinctByName => {
223 f.write_str(" ")?;
224 set_quantifier.fmt(f)?;
225 }
226 SetQuantifier::None => {}
227 }
228 SpaceOrNewline.fmt(f)?;
229 right.fmt(f)?;
230 Ok(())
231 }
232 }
233 }
234}
235
236#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
237#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
238#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
239pub enum SetOperator {
241 Union,
243 Except,
245 Intersect,
247 Minus,
249}
250
251impl fmt::Display for SetOperator {
252 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
253 f.write_str(match self {
254 SetOperator::Union => "UNION",
255 SetOperator::Except => "EXCEPT",
256 SetOperator::Intersect => "INTERSECT",
257 SetOperator::Minus => "MINUS",
258 })
259 }
260}
261
262#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
266#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
267#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
268pub enum SetQuantifier {
269 All,
271 Distinct,
273 ByName,
275 AllByName,
277 DistinctByName,
279 None,
281}
282
283impl fmt::Display for SetQuantifier {
284 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
285 match self {
286 SetQuantifier::All => write!(f, "ALL"),
287 SetQuantifier::Distinct => write!(f, "DISTINCT"),
288 SetQuantifier::ByName => write!(f, "BY NAME"),
289 SetQuantifier::AllByName => write!(f, "ALL BY NAME"),
290 SetQuantifier::DistinctByName => write!(f, "DISTINCT BY NAME"),
291 SetQuantifier::None => Ok(()),
292 }
293 }
294}
295
296#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
297#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
298#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
300pub struct Table {
302 pub table_name: Option<String>,
304 pub schema_name: Option<String>,
306}
307
308impl fmt::Display for Table {
309 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
310 if let Some(ref table_name) = self.table_name {
311 if let Some(ref schema_name) = self.schema_name {
312 write!(f, "TABLE {}.{}", schema_name, table_name,)?;
313 } else {
314 write!(f, "TABLE {}", table_name)?;
315 }
316 } else {
317 write!(f, "TABLE")?;
318 }
319 Ok(())
320 }
321}
322
323#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
325#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
326#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
327pub enum SelectFlavor {
328 Standard,
330 FromFirst,
332 FromFirstNoSelect,
334}
335
336#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Default)]
354#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
355#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
356pub struct SelectModifiers {
357 pub high_priority: bool,
361 pub straight_join: bool,
365 pub sql_small_result: bool,
369 pub sql_big_result: bool,
373 pub sql_buffer_result: bool,
377 pub sql_no_cache: bool,
381 pub sql_calc_found_rows: bool,
386}
387
388impl fmt::Display for SelectModifiers {
389 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
390 if self.high_priority {
391 f.write_str(" HIGH_PRIORITY")?;
392 }
393 if self.straight_join {
394 f.write_str(" STRAIGHT_JOIN")?;
395 }
396 if self.sql_small_result {
397 f.write_str(" SQL_SMALL_RESULT")?;
398 }
399 if self.sql_big_result {
400 f.write_str(" SQL_BIG_RESULT")?;
401 }
402 if self.sql_buffer_result {
403 f.write_str(" SQL_BUFFER_RESULT")?;
404 }
405 if self.sql_no_cache {
406 f.write_str(" SQL_NO_CACHE")?;
407 }
408 if self.sql_calc_found_rows {
409 f.write_str(" SQL_CALC_FOUND_ROWS")?;
410 }
411 Ok(())
412 }
413}
414
415impl SelectModifiers {
416 pub fn is_any_set(&self) -> bool {
418 let Self {
420 high_priority,
421 straight_join,
422 sql_small_result,
423 sql_big_result,
424 sql_buffer_result,
425 sql_no_cache,
426 sql_calc_found_rows,
427 } = self;
428 *high_priority
429 || *straight_join
430 || *sql_small_result
431 || *sql_big_result
432 || *sql_buffer_result
433 || *sql_no_cache
434 || *sql_calc_found_rows
435 }
436}
437
438#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
442#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
443#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
444#[cfg_attr(feature = "visitor", visit(with = "visit_select"))]
445pub struct Select {
446 pub select_token: AttachedToken,
448 pub optimizer_hints: Vec<OptimizerHint>,
453 pub distinct: Option<Distinct>,
455 pub select_modifiers: Option<SelectModifiers>,
459 pub top: Option<Top>,
461 pub top_before_distinct: bool,
463 pub projection: Vec<SelectItem>,
465 pub exclude: Option<ExcludeSelectItem>,
470 pub into: Option<SelectInto>,
472 pub from: Vec<TableWithJoins>,
474 pub lateral_views: Vec<LateralView>,
476 pub prewhere: Option<Expr>,
481 pub selection: Option<Expr>,
483 pub connect_by: Vec<ConnectByKind>,
485 pub group_by: GroupByExpr,
487 pub cluster_by: Vec<Expr>,
489 pub distribute_by: Vec<Expr>,
491 pub sort_by: Vec<OrderByExpr>,
493 pub having: Option<Expr>,
495 pub named_window: Vec<NamedWindowDefinition>,
497 pub qualify: Option<Expr>,
499 pub window_before_qualify: bool,
504 pub value_table_mode: Option<ValueTableMode>,
506 pub flavor: SelectFlavor,
508}
509
510impl fmt::Display for Select {
511 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
512 match self.flavor {
513 SelectFlavor::Standard => {
514 write!(f, "SELECT")?;
515 }
516 SelectFlavor::FromFirst => {
517 write!(f, "FROM {} SELECT", display_comma_separated(&self.from))?;
518 }
519 SelectFlavor::FromFirstNoSelect => {
520 write!(f, "FROM {}", display_comma_separated(&self.from))?;
521 }
522 }
523
524 for hint in &self.optimizer_hints {
525 f.write_str(" ")?;
526 hint.fmt(f)?;
527 }
528
529 if let Some(value_table_mode) = self.value_table_mode {
530 f.write_str(" ")?;
531 value_table_mode.fmt(f)?;
532 }
533
534 if let Some(ref top) = self.top {
535 if self.top_before_distinct {
536 f.write_str(" ")?;
537 top.fmt(f)?;
538 }
539 }
540 if let Some(ref distinct) = self.distinct {
541 f.write_str(" ")?;
542 distinct.fmt(f)?;
543 }
544 if let Some(ref top) = self.top {
545 if !self.top_before_distinct {
546 f.write_str(" ")?;
547 top.fmt(f)?;
548 }
549 }
550
551 if let Some(ref select_modifiers) = self.select_modifiers {
552 select_modifiers.fmt(f)?;
553 }
554
555 if !self.projection.is_empty() {
556 indented_list(f, &self.projection)?;
557 }
558
559 if let Some(exclude) = &self.exclude {
560 write!(f, " {exclude}")?;
561 }
562
563 if let Some(ref into) = self.into {
564 f.write_str(" ")?;
565 into.fmt(f)?;
566 }
567
568 if self.flavor == SelectFlavor::Standard && !self.from.is_empty() {
569 SpaceOrNewline.fmt(f)?;
570 f.write_str("FROM")?;
571 indented_list(f, &self.from)?;
572 }
573 if !self.lateral_views.is_empty() {
574 for lv in &self.lateral_views {
575 lv.fmt(f)?;
576 }
577 }
578 if let Some(ref prewhere) = self.prewhere {
579 f.write_str(" PREWHERE ")?;
580 prewhere.fmt(f)?;
581 }
582 if let Some(ref selection) = self.selection {
583 SpaceOrNewline.fmt(f)?;
584 f.write_str("WHERE")?;
585 SpaceOrNewline.fmt(f)?;
586 Indent(selection).fmt(f)?;
587 }
588 for clause in &self.connect_by {
589 SpaceOrNewline.fmt(f)?;
590 clause.fmt(f)?;
591 }
592 match &self.group_by {
593 GroupByExpr::All(_) => {
594 SpaceOrNewline.fmt(f)?;
595 self.group_by.fmt(f)?;
596 }
597 GroupByExpr::Expressions(exprs, _) => {
598 if !exprs.is_empty() {
599 SpaceOrNewline.fmt(f)?;
600 self.group_by.fmt(f)?;
601 }
602 }
603 }
604 if !self.cluster_by.is_empty() {
605 SpaceOrNewline.fmt(f)?;
606 f.write_str("CLUSTER BY")?;
607 SpaceOrNewline.fmt(f)?;
608 Indent(display_comma_separated(&self.cluster_by)).fmt(f)?;
609 }
610 if !self.distribute_by.is_empty() {
611 SpaceOrNewline.fmt(f)?;
612 f.write_str("DISTRIBUTE BY")?;
613 SpaceOrNewline.fmt(f)?;
614 display_comma_separated(&self.distribute_by).fmt(f)?;
615 }
616 if !self.sort_by.is_empty() {
617 SpaceOrNewline.fmt(f)?;
618 f.write_str("SORT BY")?;
619 SpaceOrNewline.fmt(f)?;
620 Indent(display_comma_separated(&self.sort_by)).fmt(f)?;
621 }
622 if let Some(ref having) = self.having {
623 SpaceOrNewline.fmt(f)?;
624 f.write_str("HAVING")?;
625 SpaceOrNewline.fmt(f)?;
626 Indent(having).fmt(f)?;
627 }
628 if self.window_before_qualify {
629 if !self.named_window.is_empty() {
630 SpaceOrNewline.fmt(f)?;
631 f.write_str("WINDOW")?;
632 SpaceOrNewline.fmt(f)?;
633 display_comma_separated(&self.named_window).fmt(f)?;
634 }
635 if let Some(ref qualify) = self.qualify {
636 SpaceOrNewline.fmt(f)?;
637 f.write_str("QUALIFY")?;
638 SpaceOrNewline.fmt(f)?;
639 qualify.fmt(f)?;
640 }
641 } else {
642 if let Some(ref qualify) = self.qualify {
643 SpaceOrNewline.fmt(f)?;
644 f.write_str("QUALIFY")?;
645 SpaceOrNewline.fmt(f)?;
646 qualify.fmt(f)?;
647 }
648 if !self.named_window.is_empty() {
649 SpaceOrNewline.fmt(f)?;
650 f.write_str("WINDOW")?;
651 SpaceOrNewline.fmt(f)?;
652 display_comma_separated(&self.named_window).fmt(f)?;
653 }
654 }
655 Ok(())
656 }
657}
658
659#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
661#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
662#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
663pub struct LateralView {
664 pub lateral_view: Expr,
666 pub lateral_view_name: ObjectName,
668 pub lateral_col_alias: Vec<Ident>,
670 pub outer: bool,
672}
673
674impl fmt::Display for LateralView {
675 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
676 write!(
677 f,
678 " LATERAL VIEW{outer} {} {}",
679 self.lateral_view,
680 self.lateral_view_name,
681 outer = if self.outer { " OUTER" } else { "" }
682 )?;
683 if !self.lateral_col_alias.is_empty() {
684 write!(
685 f,
686 " AS {}",
687 display_comma_separated(&self.lateral_col_alias)
688 )?;
689 }
690 Ok(())
691 }
692}
693
694#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
700#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
701#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
702pub enum NamedWindowExpr {
703 NamedWindow(Ident),
713 WindowSpec(WindowSpec),
720}
721
722impl fmt::Display for NamedWindowExpr {
723 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
724 match self {
725 NamedWindowExpr::NamedWindow(named_window) => {
726 write!(f, "{named_window}")?;
727 }
728 NamedWindowExpr::WindowSpec(window_spec) => {
729 write!(f, "({window_spec})")?;
730 }
731 };
732 Ok(())
733 }
734}
735
736#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
737#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
738#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
739pub struct NamedWindowDefinition(pub Ident, pub NamedWindowExpr);
741
742impl fmt::Display for NamedWindowDefinition {
743 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
744 write!(f, "{} AS {}", self.0, self.1)
745 }
746}
747
748#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
749#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
750#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
751pub struct With {
753 pub with_token: AttachedToken,
755 pub recursive: bool,
757 pub cte_tables: Vec<Cte>,
759}
760
761impl fmt::Display for With {
762 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
763 f.write_str("WITH ")?;
764 if self.recursive {
765 f.write_str("RECURSIVE ")?;
766 }
767 display_comma_separated(&self.cte_tables).fmt(f)?;
768 Ok(())
769 }
770}
771
772#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
773#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
774#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
775pub enum CteAsMaterialized {
777 Materialized,
779 NotMaterialized,
781}
782
783impl fmt::Display for CteAsMaterialized {
784 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
785 match *self {
786 CteAsMaterialized::Materialized => {
787 write!(f, "MATERIALIZED")?;
788 }
789 CteAsMaterialized::NotMaterialized => {
790 write!(f, "NOT MATERIALIZED")?;
791 }
792 };
793 Ok(())
794 }
795}
796
797#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
802#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
803#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
804pub struct Cte {
805 pub alias: TableAlias,
807 pub query: Box<Query>,
809 pub from: Option<Ident>,
811 pub materialized: Option<CteAsMaterialized>,
813 pub closing_paren_token: AttachedToken,
815}
816
817impl fmt::Display for Cte {
818 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
819 match self.materialized.as_ref() {
820 None => {
821 self.alias.fmt(f)?;
822 f.write_str(" AS (")?;
823 NewLine.fmt(f)?;
824 Indent(&self.query).fmt(f)?;
825 NewLine.fmt(f)?;
826 f.write_str(")")?;
827 }
828 Some(materialized) => {
829 self.alias.fmt(f)?;
830 f.write_str(" AS ")?;
831 materialized.fmt(f)?;
832 f.write_str(" (")?;
833 NewLine.fmt(f)?;
834 Indent(&self.query).fmt(f)?;
835 NewLine.fmt(f)?;
836 f.write_str(")")?;
837 }
838 };
839 if let Some(ref fr) = self.from {
840 write!(f, " FROM {fr}")?;
841 }
842 Ok(())
843 }
844}
845
846#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
849#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
850#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
851pub enum SelectItemQualifiedWildcardKind {
852 ObjectName(ObjectName),
855 Expr(Expr),
858}
859
860#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
862#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
863#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
864pub enum SelectItem {
865 UnnamedExpr(Expr),
867 ExprWithAlias {
869 expr: Expr,
871 alias: Ident,
873 },
874 ExprWithAliases {
878 expr: Expr,
880 aliases: Vec<Ident>,
882 },
883 QualifiedWildcard(SelectItemQualifiedWildcardKind, WildcardAdditionalOptions),
886 Wildcard(WildcardAdditionalOptions),
888}
889
890impl fmt::Display for SelectItemQualifiedWildcardKind {
891 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
892 match &self {
893 SelectItemQualifiedWildcardKind::ObjectName(object_name) => {
894 write!(f, "{object_name}.*")
895 }
896 SelectItemQualifiedWildcardKind::Expr(expr) => write!(f, "{expr}.*"),
897 }
898 }
899}
900
901#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
908#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
909#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
910pub struct IdentWithAlias {
911 pub ident: Ident,
913 pub alias: Ident,
915}
916
917impl fmt::Display for IdentWithAlias {
918 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
919 write!(f, "{} AS {}", self.ident, self.alias)
920 }
921}
922
923#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
925#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
926#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
927pub struct WildcardAdditionalOptions {
928 pub wildcard_token: AttachedToken,
930 pub opt_ilike: Option<IlikeSelectItem>,
933 pub opt_exclude: Option<ExcludeSelectItem>,
935 pub opt_except: Option<ExceptSelectItem>,
938 pub opt_replace: Option<ReplaceSelectItem>,
943 pub opt_rename: Option<RenameSelectItem>,
945 pub opt_alias: Option<Ident>,
948}
949
950impl Default for WildcardAdditionalOptions {
951 fn default() -> Self {
952 Self {
953 wildcard_token: TokenWithSpan::wrap(Token::Mul).into(),
954 opt_ilike: None,
955 opt_exclude: None,
956 opt_except: None,
957 opt_replace: None,
958 opt_rename: None,
959 opt_alias: None,
960 }
961 }
962}
963
964impl fmt::Display for WildcardAdditionalOptions {
965 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
966 if let Some(ilike) = &self.opt_ilike {
967 write!(f, " {ilike}")?;
968 }
969 if let Some(exclude) = &self.opt_exclude {
970 write!(f, " {exclude}")?;
971 }
972 if let Some(except) = &self.opt_except {
973 write!(f, " {except}")?;
974 }
975 if let Some(replace) = &self.opt_replace {
976 write!(f, " {replace}")?;
977 }
978 if let Some(rename) = &self.opt_rename {
979 write!(f, " {rename}")?;
980 }
981 if let Some(alias) = &self.opt_alias {
982 write!(f, " AS {alias}")?;
983 }
984 Ok(())
985 }
986}
987
988#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
995#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
996#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
997pub struct IlikeSelectItem {
998 pub pattern: String,
1000}
1001
1002impl fmt::Display for IlikeSelectItem {
1003 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1004 write!(
1005 f,
1006 "ILIKE '{}'",
1007 value::escape_single_quote_string(&self.pattern)
1008 )?;
1009 Ok(())
1010 }
1011}
1012#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1020#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1021#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1022pub enum ExcludeSelectItem {
1023 Single(ObjectName),
1030 Multiple(Vec<ObjectName>),
1036}
1037
1038impl fmt::Display for ExcludeSelectItem {
1039 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1040 write!(f, "EXCLUDE")?;
1041 match self {
1042 Self::Single(column) => {
1043 write!(f, " {column}")?;
1044 }
1045 Self::Multiple(columns) => {
1046 write!(f, " ({})", display_comma_separated(columns))?;
1047 }
1048 }
1049 Ok(())
1050 }
1051}
1052
1053#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1061#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1062#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1063pub enum RenameSelectItem {
1064 Single(IdentWithAlias),
1071 Multiple(Vec<IdentWithAlias>),
1077}
1078
1079impl fmt::Display for RenameSelectItem {
1080 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1081 write!(f, "RENAME")?;
1082 match self {
1083 Self::Single(column) => {
1084 write!(f, " {column}")?;
1085 }
1086 Self::Multiple(columns) => {
1087 write!(f, " ({})", display_comma_separated(columns))?;
1088 }
1089 }
1090 Ok(())
1091 }
1092}
1093
1094#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1101#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1102#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1103pub struct ExceptSelectItem {
1104 pub first_element: Ident,
1106 pub additional_elements: Vec<Ident>,
1108}
1109
1110impl fmt::Display for ExceptSelectItem {
1111 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1112 write!(f, "EXCEPT ")?;
1113 if self.additional_elements.is_empty() {
1114 write!(f, "({})", self.first_element)?;
1115 } else {
1116 write!(
1117 f,
1118 "({}, {})",
1119 self.first_element,
1120 display_comma_separated(&self.additional_elements)
1121 )?;
1122 }
1123 Ok(())
1124 }
1125}
1126
1127#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1135#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1136#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1137pub struct ReplaceSelectItem {
1138 pub items: Vec<Box<ReplaceSelectElement>>,
1140}
1141
1142impl fmt::Display for ReplaceSelectItem {
1143 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1144 write!(f, "REPLACE")?;
1145 write!(f, " ({})", display_comma_separated(&self.items))?;
1146 Ok(())
1147 }
1148}
1149
1150#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1155#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1156#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1157pub struct ReplaceSelectElement {
1158 pub expr: Expr,
1160 pub column_name: Ident,
1162 pub as_keyword: bool,
1164}
1165
1166impl fmt::Display for ReplaceSelectElement {
1167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1168 if self.as_keyword {
1169 write!(f, "{} AS {}", self.expr, self.column_name)
1170 } else {
1171 write!(f, "{} {}", self.expr, self.column_name)
1172 }
1173 }
1174}
1175
1176impl fmt::Display for SelectItem {
1177 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1178 use core::fmt::Write;
1179 match &self {
1180 SelectItem::UnnamedExpr(expr) => expr.fmt(f),
1181 SelectItem::ExprWithAlias { expr, alias } => {
1182 expr.fmt(f)?;
1183 f.write_str(" AS ")?;
1184 alias.fmt(f)
1185 }
1186 SelectItem::ExprWithAliases { expr, aliases } => {
1187 expr.fmt(f)?;
1188 f.write_str(" AS (")?;
1189 display_comma_separated(aliases).fmt(f)?;
1190 f.write_str(")")
1191 }
1192 SelectItem::QualifiedWildcard(kind, additional_options) => {
1193 kind.fmt(f)?;
1194 additional_options.fmt(f)
1195 }
1196 SelectItem::Wildcard(additional_options) => {
1197 f.write_char('*')?;
1198 additional_options.fmt(f)
1199 }
1200 }
1201 }
1202}
1203
1204#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1205#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1206#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1207pub struct TableWithJoins {
1209 pub relation: TableFactor,
1211 pub joins: Vec<Join>,
1213}
1214
1215impl fmt::Display for TableWithJoins {
1216 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1217 self.relation.fmt(f)?;
1218 for join in &self.joins {
1219 SpaceOrNewline.fmt(f)?;
1220 join.fmt(f)?;
1221 }
1222 Ok(())
1223 }
1224}
1225
1226#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1231#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1232#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1233pub enum ConnectByKind {
1234 ConnectBy {
1236 connect_token: AttachedToken,
1238
1239 nocycle: bool,
1243
1244 relationships: Vec<Expr>,
1246 },
1247
1248 StartWith {
1253 start_token: AttachedToken,
1255
1256 condition: Box<Expr>,
1258 },
1259}
1260
1261impl fmt::Display for ConnectByKind {
1262 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1263 match self {
1264 ConnectByKind::ConnectBy {
1265 connect_token: _,
1266 nocycle,
1267 relationships,
1268 } => {
1269 write!(
1270 f,
1271 "CONNECT BY {nocycle}{relationships}",
1272 nocycle = if *nocycle { "NOCYCLE " } else { "" },
1273 relationships = display_comma_separated(relationships)
1274 )
1275 }
1276 ConnectByKind::StartWith {
1277 start_token: _,
1278 condition,
1279 } => {
1280 write!(f, "START WITH {condition}")
1281 }
1282 }
1283 }
1284}
1285
1286#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1287#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1288#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1289pub struct Setting {
1291 pub key: Ident,
1293 pub value: Expr,
1295}
1296
1297impl fmt::Display for Setting {
1298 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1299 write!(f, "{} = {}", self.key, self.value)
1300 }
1301}
1302
1303#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1310#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1311#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1312pub struct ExprWithAlias {
1313 pub expr: Expr,
1315 pub alias: Option<Ident>,
1317}
1318
1319impl fmt::Display for ExprWithAlias {
1320 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1321 let ExprWithAlias { expr, alias } = self;
1322 write!(f, "{expr}")?;
1323 if let Some(alias) = alias {
1324 write!(f, " AS {alias}")?;
1325 }
1326 Ok(())
1327 }
1328}
1329
1330#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1337#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1338#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1339pub struct ExprWithAliasAndOrderBy {
1340 pub expr: ExprWithAlias,
1342 pub order_by: OrderByOptions,
1344}
1345
1346impl fmt::Display for ExprWithAliasAndOrderBy {
1347 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1348 write!(f, "{}{}", self.expr, self.order_by)
1349 }
1350}
1351
1352#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1354#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1355#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1356pub struct TableFunctionArgs {
1357 pub args: Vec<FunctionArg>,
1359 pub settings: Option<Vec<Setting>>,
1364}
1365
1366#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1367#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1368#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1369pub enum TableIndexHintType {
1371 Use,
1373 Ignore,
1375 Force,
1377}
1378
1379impl fmt::Display for TableIndexHintType {
1380 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1381 f.write_str(match self {
1382 TableIndexHintType::Use => "USE",
1383 TableIndexHintType::Ignore => "IGNORE",
1384 TableIndexHintType::Force => "FORCE",
1385 })
1386 }
1387}
1388
1389#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1390#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1391#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1392pub enum TableIndexType {
1394 Index,
1396 Key,
1398}
1399
1400impl fmt::Display for TableIndexType {
1401 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1402 f.write_str(match self {
1403 TableIndexType::Index => "INDEX",
1404 TableIndexType::Key => "KEY",
1405 })
1406 }
1407}
1408
1409#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1410#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1411#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1412pub enum TableIndexHintForClause {
1414 Join,
1416 OrderBy,
1418 GroupBy,
1420}
1421
1422impl fmt::Display for TableIndexHintForClause {
1423 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1424 f.write_str(match self {
1425 TableIndexHintForClause::Join => "JOIN",
1426 TableIndexHintForClause::OrderBy => "ORDER BY",
1427 TableIndexHintForClause::GroupBy => "GROUP BY",
1428 })
1429 }
1430}
1431
1432#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1433#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1434#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1435pub struct TableIndexHints {
1437 pub hint_type: TableIndexHintType,
1439 pub index_type: TableIndexType,
1441 pub for_clause: Option<TableIndexHintForClause>,
1443 pub index_names: Vec<Ident>,
1445}
1446
1447impl fmt::Display for TableIndexHints {
1448 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1449 write!(f, "{} {} ", self.hint_type, self.index_type)?;
1450 if let Some(for_clause) = &self.for_clause {
1451 write!(f, "FOR {for_clause} ")?;
1452 }
1453 write!(f, "({})", display_comma_separated(&self.index_names))
1454 }
1455}
1456
1457#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1459#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1460#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1461#[cfg_attr(feature = "visitor", visit(with = "visit_table_factor"))]
1462pub enum TableFactor {
1463 Table {
1465 #[cfg_attr(feature = "visitor", visit(with = "visit_relation"))]
1466 name: ObjectName,
1468 alias: Option<TableAlias>,
1470 args: Option<TableFunctionArgs>,
1478 with_hints: Vec<Expr>,
1480 version: Option<TableVersion>,
1483 with_ordinality: bool,
1487 partitions: Vec<Ident>,
1489 json_path: Option<JsonPath>,
1491 sample: Option<TableSampleKind>,
1494 index_hints: Vec<TableIndexHints>,
1497 },
1498 Derived {
1500 lateral: bool,
1502 subquery: Box<Query>,
1504 alias: Option<TableAlias>,
1506 sample: Option<TableSampleKind>,
1508 },
1509 TableFunction {
1511 expr: Expr,
1513 alias: Option<TableAlias>,
1515 },
1516 Function {
1518 lateral: bool,
1520 name: ObjectName,
1522 args: Vec<FunctionArg>,
1524 with_ordinality: bool,
1526 alias: Option<TableAlias>,
1528 },
1529 UNNEST {
1540 alias: Option<TableAlias>,
1542 array_exprs: Vec<Expr>,
1544 with_offset: bool,
1546 with_offset_alias: Option<Ident>,
1548 with_ordinality: bool,
1550 },
1551 JsonTable {
1567 json_expr: Expr,
1569 json_path: ValueWithSpan,
1572 columns: Vec<JsonTableColumn>,
1575 alias: Option<TableAlias>,
1577 },
1578 OpenJsonTable {
1588 json_expr: Expr,
1590 json_path: Option<ValueWithSpan>,
1593 columns: Vec<OpenJsonTableColumn>,
1596 alias: Option<TableAlias>,
1598 },
1599 NestedJoin {
1606 table_with_joins: Box<TableWithJoins>,
1608 alias: Option<TableAlias>,
1610 },
1611 Pivot {
1618 table: Box<TableFactor>,
1620 aggregate_functions: Vec<ExprWithAlias>, value_column: Vec<Expr>,
1624 value_source: PivotValueSource,
1626 default_on_null: Option<Expr>,
1628 alias: Option<TableAlias>,
1630 },
1631 Unpivot {
1643 table: Box<TableFactor>,
1645 value: Expr,
1647 name: Ident,
1649 columns: Vec<ExprWithAlias>,
1651 null_inclusion: Option<NullInclusion>,
1653 alias: Option<TableAlias>,
1655 },
1656 MatchRecognize {
1660 table: Box<TableFactor>,
1662 partition_by: Vec<Expr>,
1664 order_by: Vec<OrderByExpr>,
1666 measures: Vec<Measure>,
1668 rows_per_match: Option<RowsPerMatch>,
1670 after_match_skip: Option<AfterMatchSkip>,
1672 pattern: MatchRecognizePattern,
1674 symbols: Vec<SymbolDefinition>,
1676 alias: Option<TableAlias>,
1678 },
1679 XmlTable {
1699 namespaces: Vec<XmlNamespaceDefinition>,
1701 row_expression: Expr,
1703 passing: XmlPassingClause,
1705 columns: Vec<XmlTableColumn>,
1707 alias: Option<TableAlias>,
1709 },
1710 SemanticView {
1722 name: ObjectName,
1724 dimensions: Vec<Expr>,
1726 metrics: Vec<Expr>,
1728 facts: Vec<Expr>,
1730 where_clause: Option<Expr>,
1732 alias: Option<TableAlias>,
1734 },
1735}
1736
1737#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1739#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1740#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1741pub enum TableSampleKind {
1742 BeforeTableAlias(Box<TableSample>),
1744 AfterTableAlias(Box<TableSample>),
1746}
1747
1748#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1749#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1750#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1751pub struct TableSample {
1753 pub modifier: TableSampleModifier,
1755 pub name: Option<TableSampleMethod>,
1757 pub quantity: Option<TableSampleQuantity>,
1759 pub seed: Option<TableSampleSeed>,
1761 pub bucket: Option<TableSampleBucket>,
1763 pub offset: Option<Expr>,
1765}
1766
1767#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1768#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1769#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1770pub enum TableSampleModifier {
1772 Sample,
1774 TableSample,
1776}
1777
1778impl fmt::Display for TableSampleModifier {
1779 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1780 match self {
1781 TableSampleModifier::Sample => write!(f, "SAMPLE")?,
1782 TableSampleModifier::TableSample => write!(f, "TABLESAMPLE")?,
1783 }
1784 Ok(())
1785 }
1786}
1787
1788#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1789#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1790#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1791pub struct TableSampleQuantity {
1793 pub parenthesized: bool,
1795 pub value: Expr,
1797 pub unit: Option<TableSampleUnit>,
1799}
1800
1801impl fmt::Display for TableSampleQuantity {
1802 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1803 if self.parenthesized {
1804 write!(f, "(")?;
1805 }
1806 write!(f, "{}", self.value)?;
1807 if let Some(unit) = &self.unit {
1808 write!(f, " {unit}")?;
1809 }
1810 if self.parenthesized {
1811 write!(f, ")")?;
1812 }
1813 Ok(())
1814 }
1815}
1816
1817#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1819#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1820#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1821pub enum TableSampleMethod {
1823 Row,
1825 Bernoulli,
1827 System,
1829 Block,
1831}
1832
1833impl fmt::Display for TableSampleMethod {
1834 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1835 match self {
1836 TableSampleMethod::Bernoulli => write!(f, "BERNOULLI"),
1837 TableSampleMethod::Row => write!(f, "ROW"),
1838 TableSampleMethod::System => write!(f, "SYSTEM"),
1839 TableSampleMethod::Block => write!(f, "BLOCK"),
1840 }
1841 }
1842}
1843
1844#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1845#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1846#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1847pub struct TableSampleSeed {
1849 pub modifier: TableSampleSeedModifier,
1851 pub value: ValueWithSpan,
1853}
1854
1855impl fmt::Display for TableSampleSeed {
1856 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1857 write!(f, "{} ({})", self.modifier, self.value)?;
1858 Ok(())
1859 }
1860}
1861
1862#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1863#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1864#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1865pub enum TableSampleSeedModifier {
1867 Repeatable,
1869 Seed,
1871}
1872
1873impl fmt::Display for TableSampleSeedModifier {
1874 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1875 match self {
1876 TableSampleSeedModifier::Repeatable => write!(f, "REPEATABLE"),
1877 TableSampleSeedModifier::Seed => write!(f, "SEED"),
1878 }
1879 }
1880}
1881
1882#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
1883#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1884#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1885pub enum TableSampleUnit {
1887 Rows,
1889 Percent,
1891}
1892
1893impl fmt::Display for TableSampleUnit {
1894 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1895 match self {
1896 TableSampleUnit::Percent => write!(f, "PERCENT"),
1897 TableSampleUnit::Rows => write!(f, "ROWS"),
1898 }
1899 }
1900}
1901
1902#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1903#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1904#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1905pub struct TableSampleBucket {
1907 pub bucket: ValueWithSpan,
1909 pub total: ValueWithSpan,
1911 pub on: Option<Expr>,
1913}
1914
1915impl fmt::Display for TableSampleBucket {
1916 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1917 write!(f, "BUCKET {} OUT OF {}", self.bucket, self.total)?;
1918 if let Some(on) = &self.on {
1919 write!(f, " ON {on}")?;
1920 }
1921 Ok(())
1922 }
1923}
1924impl fmt::Display for TableSample {
1925 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1926 write!(f, "{}", self.modifier)?;
1927 if let Some(name) = &self.name {
1928 write!(f, " {name}")?;
1929 }
1930 if let Some(quantity) = &self.quantity {
1931 write!(f, " {quantity}")?;
1932 }
1933 if let Some(seed) = &self.seed {
1934 write!(f, " {seed}")?;
1935 }
1936 if let Some(bucket) = &self.bucket {
1937 write!(f, " ({bucket})")?;
1938 }
1939 if let Some(offset) = &self.offset {
1940 write!(f, " OFFSET {offset}")?;
1941 }
1942 Ok(())
1943 }
1944}
1945
1946#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1948#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1949#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1950pub enum PivotValueSource {
1951 List(Vec<ExprWithAlias>),
1955 Any(Vec<OrderByExpr>),
1959 Subquery(Box<Query>),
1963}
1964
1965impl fmt::Display for PivotValueSource {
1966 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1967 match self {
1968 PivotValueSource::List(values) => write!(f, "{}", display_comma_separated(values)),
1969 PivotValueSource::Any(order_by) => {
1970 write!(f, "ANY")?;
1971 if !order_by.is_empty() {
1972 write!(f, " ORDER BY {}", display_comma_separated(order_by))?;
1973 }
1974 Ok(())
1975 }
1976 PivotValueSource::Subquery(query) => write!(f, "{query}"),
1977 }
1978 }
1979}
1980
1981#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
1985#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1986#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
1987pub struct Measure {
1989 pub expr: Expr,
1991 pub alias: Ident,
1993}
1994
1995impl fmt::Display for Measure {
1996 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1997 write!(f, "{} AS {}", self.expr, self.alias)
1998 }
1999}
2000
2001#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2005#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2006#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2007pub enum RowsPerMatch {
2008 OneRow,
2010 AllRows(Option<EmptyMatchesMode>),
2012}
2013
2014impl fmt::Display for RowsPerMatch {
2015 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2016 match self {
2017 RowsPerMatch::OneRow => write!(f, "ONE ROW PER MATCH"),
2018 RowsPerMatch::AllRows(mode) => {
2019 write!(f, "ALL ROWS PER MATCH")?;
2020 if let Some(mode) = mode {
2021 write!(f, " {mode}")?;
2022 }
2023 Ok(())
2024 }
2025 }
2026 }
2027}
2028
2029#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2033#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2034#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2035pub enum AfterMatchSkip {
2036 PastLastRow,
2038 ToNextRow,
2040 ToFirst(Ident),
2042 ToLast(Ident),
2044}
2045
2046impl fmt::Display for AfterMatchSkip {
2047 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2048 write!(f, "AFTER MATCH SKIP ")?;
2049 match self {
2050 AfterMatchSkip::PastLastRow => write!(f, "PAST LAST ROW"),
2051 AfterMatchSkip::ToNextRow => write!(f, " TO NEXT ROW"),
2052 AfterMatchSkip::ToFirst(symbol) => write!(f, "TO FIRST {symbol}"),
2053 AfterMatchSkip::ToLast(symbol) => write!(f, "TO LAST {symbol}"),
2054 }
2055 }
2056}
2057
2058#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2059#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2060#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2061pub enum EmptyMatchesMode {
2063 Show,
2065 Omit,
2067 WithUnmatched,
2069}
2070
2071impl fmt::Display for EmptyMatchesMode {
2072 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2073 match self {
2074 EmptyMatchesMode::Show => write!(f, "SHOW EMPTY MATCHES"),
2075 EmptyMatchesMode::Omit => write!(f, "OMIT EMPTY MATCHES"),
2076 EmptyMatchesMode::WithUnmatched => write!(f, "WITH UNMATCHED ROWS"),
2077 }
2078 }
2079}
2080
2081#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2085#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2086#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2087pub struct SymbolDefinition {
2089 pub symbol: Ident,
2091 pub definition: Expr,
2093}
2094
2095impl fmt::Display for SymbolDefinition {
2096 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2097 write!(f, "{} AS {}", self.symbol, self.definition)
2098 }
2099}
2100
2101#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2103#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2104#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2105pub enum MatchRecognizeSymbol {
2106 Named(Ident),
2108 Start,
2110 End,
2112}
2113
2114impl fmt::Display for MatchRecognizeSymbol {
2115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2116 match self {
2117 MatchRecognizeSymbol::Named(symbol) => write!(f, "{symbol}"),
2118 MatchRecognizeSymbol::Start => write!(f, "^"),
2119 MatchRecognizeSymbol::End => write!(f, "$"),
2120 }
2121 }
2122}
2123
2124#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2128#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2129#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2130pub enum MatchRecognizePattern {
2131 Symbol(MatchRecognizeSymbol),
2133 Exclude(MatchRecognizeSymbol),
2135 Permute(Vec<MatchRecognizeSymbol>),
2137 Concat(Vec<MatchRecognizePattern>),
2139 Group(Box<MatchRecognizePattern>),
2141 Alternation(Vec<MatchRecognizePattern>),
2143 Repetition(Box<MatchRecognizePattern>, RepetitionQuantifier),
2145}
2146
2147impl fmt::Display for MatchRecognizePattern {
2148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2149 use MatchRecognizePattern::*;
2150 match self {
2151 Symbol(symbol) => write!(f, "{symbol}"),
2152 Exclude(symbol) => write!(f, "{{- {symbol} -}}"),
2153 Permute(symbols) => write!(f, "PERMUTE({})", display_comma_separated(symbols)),
2154 Concat(patterns) => write!(f, "{}", display_separated(patterns, " ")),
2155 Group(pattern) => write!(f, "( {pattern} )"),
2156 Alternation(patterns) => write!(f, "{}", display_separated(patterns, " | ")),
2157 Repetition(pattern, op) => write!(f, "{pattern}{op}"),
2158 }
2159 }
2160}
2161
2162#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2165#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2166#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2167pub enum RepetitionQuantifier {
2168 ZeroOrMore,
2170 OneOrMore,
2172 AtMostOne,
2174 Exactly(u32),
2176 AtLeast(u32),
2178 AtMost(u32),
2180 Range(u32, u32),
2182}
2183
2184impl fmt::Display for RepetitionQuantifier {
2185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2186 use RepetitionQuantifier::*;
2187 match self {
2188 ZeroOrMore => write!(f, "*"),
2189 OneOrMore => write!(f, "+"),
2190 AtMostOne => write!(f, "?"),
2191 Exactly(n) => write!(f, "{{{n}}}"),
2192 AtLeast(n) => write!(f, "{{{n},}}"),
2193 AtMost(n) => write!(f, "{{,{n}}}"),
2194 Range(n, m) => write!(f, "{{{n},{m}}}"),
2195 }
2196 }
2197}
2198
2199impl fmt::Display for TableFactor {
2200 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2201 match self {
2202 TableFactor::Table {
2203 name,
2204 alias,
2205 args,
2206 with_hints,
2207 version,
2208 partitions,
2209 with_ordinality,
2210 json_path,
2211 sample,
2212 index_hints,
2213 } => {
2214 name.fmt(f)?;
2215 if let Some(json_path) = json_path {
2216 json_path.fmt(f)?;
2217 }
2218 if !partitions.is_empty() {
2219 write!(f, "PARTITION ({})", display_comma_separated(partitions))?;
2220 }
2221 if let Some(args) = args {
2222 write!(f, "(")?;
2223 write!(f, "{}", display_comma_separated(&args.args))?;
2224 if let Some(ref settings) = args.settings {
2225 if !args.args.is_empty() {
2226 write!(f, ", ")?;
2227 }
2228 write!(f, "SETTINGS {}", display_comma_separated(settings))?;
2229 }
2230 write!(f, ")")?;
2231 }
2232 if *with_ordinality {
2233 write!(f, " WITH ORDINALITY")?;
2234 }
2235 if let Some(TableSampleKind::BeforeTableAlias(sample)) = sample {
2236 write!(f, " {sample}")?;
2237 }
2238 if let Some(alias) = alias {
2239 write!(f, " {alias}")?;
2240 }
2241 if !index_hints.is_empty() {
2242 write!(f, " {}", display_separated(index_hints, " "))?;
2243 }
2244 if !with_hints.is_empty() {
2245 write!(f, " WITH ({})", display_comma_separated(with_hints))?;
2246 }
2247 if let Some(version) = version {
2248 write!(f, " {version}")?;
2249 }
2250 if let Some(TableSampleKind::AfterTableAlias(sample)) = sample {
2251 write!(f, " {sample}")?;
2252 }
2253 Ok(())
2254 }
2255 TableFactor::Derived {
2256 lateral,
2257 subquery,
2258 alias,
2259 sample,
2260 } => {
2261 if *lateral {
2262 write!(f, "LATERAL ")?;
2263 }
2264 f.write_str("(")?;
2265 NewLine.fmt(f)?;
2266 Indent(subquery).fmt(f)?;
2267 NewLine.fmt(f)?;
2268 f.write_str(")")?;
2269 if let Some(alias) = alias {
2270 write!(f, " {alias}")?;
2271 }
2272 if let Some(TableSampleKind::AfterTableAlias(sample)) = sample {
2273 write!(f, " {sample}")?;
2274 }
2275 Ok(())
2276 }
2277 TableFactor::Function {
2278 lateral,
2279 name,
2280 args,
2281 with_ordinality,
2282 alias,
2283 } => {
2284 if *lateral {
2285 write!(f, "LATERAL ")?;
2286 }
2287 write!(f, "{name}")?;
2288 write!(f, "({})", display_comma_separated(args))?;
2289 if *with_ordinality {
2290 write!(f, " WITH ORDINALITY")?;
2291 }
2292 if let Some(alias) = alias {
2293 write!(f, " {alias}")?;
2294 }
2295 Ok(())
2296 }
2297 TableFactor::TableFunction { expr, alias } => {
2298 write!(f, "TABLE({expr})")?;
2299 if let Some(alias) = alias {
2300 write!(f, " {alias}")?;
2301 }
2302 Ok(())
2303 }
2304 TableFactor::UNNEST {
2305 alias,
2306 array_exprs,
2307 with_offset,
2308 with_offset_alias,
2309 with_ordinality,
2310 } => {
2311 write!(f, "UNNEST({})", display_comma_separated(array_exprs))?;
2312
2313 if *with_ordinality {
2314 write!(f, " WITH ORDINALITY")?;
2315 }
2316
2317 if let Some(alias) = alias {
2318 write!(f, " {alias}")?;
2319 }
2320 if *with_offset {
2321 write!(f, " WITH OFFSET")?;
2322 }
2323 if let Some(alias) = with_offset_alias {
2324 write!(f, " {alias}")?;
2325 }
2326 Ok(())
2327 }
2328 TableFactor::JsonTable {
2329 json_expr,
2330 json_path,
2331 columns,
2332 alias,
2333 } => {
2334 write!(
2335 f,
2336 "JSON_TABLE({json_expr}, {json_path} COLUMNS({columns}))",
2337 columns = display_comma_separated(columns)
2338 )?;
2339 if let Some(alias) = alias {
2340 write!(f, " {alias}")?;
2341 }
2342 Ok(())
2343 }
2344 TableFactor::OpenJsonTable {
2345 json_expr,
2346 json_path,
2347 columns,
2348 alias,
2349 } => {
2350 write!(f, "OPENJSON({json_expr}")?;
2351 if let Some(json_path) = json_path {
2352 write!(f, ", {json_path}")?;
2353 }
2354 write!(f, ")")?;
2355 if !columns.is_empty() {
2356 write!(f, " WITH ({})", display_comma_separated(columns))?;
2357 }
2358 if let Some(alias) = alias {
2359 write!(f, " {alias}")?;
2360 }
2361 Ok(())
2362 }
2363 TableFactor::NestedJoin {
2364 table_with_joins,
2365 alias,
2366 } => {
2367 write!(f, "({table_with_joins})")?;
2368 if let Some(alias) = alias {
2369 write!(f, " {alias}")?;
2370 }
2371 Ok(())
2372 }
2373 TableFactor::Pivot {
2374 table,
2375 aggregate_functions,
2376 value_column,
2377 value_source,
2378 default_on_null,
2379 alias,
2380 } => {
2381 write!(
2382 f,
2383 "{table} PIVOT({} FOR ",
2384 display_comma_separated(aggregate_functions),
2385 )?;
2386 if value_column.len() == 1 {
2387 write!(f, "{}", value_column[0])?;
2388 } else {
2389 write!(f, "({})", display_comma_separated(value_column))?;
2390 }
2391 write!(f, " IN ({value_source})")?;
2392 if let Some(expr) = default_on_null {
2393 write!(f, " DEFAULT ON NULL ({expr})")?;
2394 }
2395 write!(f, ")")?;
2396 if let Some(alias) = alias {
2397 write!(f, " {alias}")?;
2398 }
2399 Ok(())
2400 }
2401 TableFactor::Unpivot {
2402 table,
2403 null_inclusion,
2404 value,
2405 name,
2406 columns,
2407 alias,
2408 } => {
2409 write!(f, "{table} UNPIVOT")?;
2410 if let Some(null_inclusion) = null_inclusion {
2411 write!(f, " {null_inclusion} ")?;
2412 }
2413 write!(
2414 f,
2415 "({} FOR {} IN ({}))",
2416 value,
2417 name,
2418 display_comma_separated(columns)
2419 )?;
2420 if let Some(alias) = alias {
2421 write!(f, " {alias}")?;
2422 }
2423 Ok(())
2424 }
2425 TableFactor::MatchRecognize {
2426 table,
2427 partition_by,
2428 order_by,
2429 measures,
2430 rows_per_match,
2431 after_match_skip,
2432 pattern,
2433 symbols,
2434 alias,
2435 } => {
2436 write!(f, "{table} MATCH_RECOGNIZE(")?;
2437 if !partition_by.is_empty() {
2438 write!(f, "PARTITION BY {} ", display_comma_separated(partition_by))?;
2439 }
2440 if !order_by.is_empty() {
2441 write!(f, "ORDER BY {} ", display_comma_separated(order_by))?;
2442 }
2443 if !measures.is_empty() {
2444 write!(f, "MEASURES {} ", display_comma_separated(measures))?;
2445 }
2446 if let Some(rows_per_match) = rows_per_match {
2447 write!(f, "{rows_per_match} ")?;
2448 }
2449 if let Some(after_match_skip) = after_match_skip {
2450 write!(f, "{after_match_skip} ")?;
2451 }
2452 write!(f, "PATTERN ({pattern}) ")?;
2453 write!(f, "DEFINE {})", display_comma_separated(symbols))?;
2454 if let Some(alias) = alias {
2455 write!(f, " {alias}")?;
2456 }
2457 Ok(())
2458 }
2459 TableFactor::XmlTable {
2460 row_expression,
2461 passing,
2462 columns,
2463 alias,
2464 namespaces,
2465 } => {
2466 write!(f, "XMLTABLE(")?;
2467 if !namespaces.is_empty() {
2468 write!(
2469 f,
2470 "XMLNAMESPACES({}), ",
2471 display_comma_separated(namespaces)
2472 )?;
2473 }
2474 write!(
2475 f,
2476 "{row_expression}{passing} COLUMNS {columns})",
2477 columns = display_comma_separated(columns)
2478 )?;
2479 if let Some(alias) = alias {
2480 write!(f, " {alias}")?;
2481 }
2482 Ok(())
2483 }
2484 TableFactor::SemanticView {
2485 name,
2486 dimensions,
2487 metrics,
2488 facts,
2489 where_clause,
2490 alias,
2491 } => {
2492 write!(f, "SEMANTIC_VIEW({name}")?;
2493
2494 if !dimensions.is_empty() {
2495 write!(f, " DIMENSIONS {}", display_comma_separated(dimensions))?;
2496 }
2497
2498 if !metrics.is_empty() {
2499 write!(f, " METRICS {}", display_comma_separated(metrics))?;
2500 }
2501
2502 if !facts.is_empty() {
2503 write!(f, " FACTS {}", display_comma_separated(facts))?;
2504 }
2505
2506 if let Some(where_clause) = where_clause {
2507 write!(f, " WHERE {where_clause}")?;
2508 }
2509
2510 write!(f, ")")?;
2511
2512 if let Some(alias) = alias {
2513 write!(f, " {alias}")?;
2514 }
2515
2516 Ok(())
2517 }
2518 }
2519 }
2520}
2521
2522#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2523#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2524#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2525pub struct TableAlias {
2527 pub explicit: bool,
2531 pub name: Ident,
2533 pub columns: Vec<TableAliasColumnDef>,
2535 pub at: Option<Ident>,
2541}
2542
2543impl fmt::Display for TableAlias {
2544 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2545 write!(f, "{}{}", if self.explicit { "AS " } else { "" }, self.name)?;
2546 if !self.columns.is_empty() {
2547 write!(f, " ({})", display_comma_separated(&self.columns))?;
2548 }
2549 if let Some(at) = &self.at {
2550 write!(f, " AT {at}")?;
2551 }
2552 Ok(())
2553 }
2554}
2555
2556#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2562#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2563#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2564pub struct TableAliasColumnDef {
2565 pub name: Ident,
2567 pub data_type: Option<DataType>,
2569}
2570
2571impl TableAliasColumnDef {
2572 pub fn from_name<S: Into<String>>(name: S) -> Self {
2574 TableAliasColumnDef {
2575 name: Ident::new(name),
2576 data_type: None,
2577 }
2578 }
2579}
2580
2581impl fmt::Display for TableAliasColumnDef {
2582 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2583 write!(f, "{}", self.name)?;
2584 if let Some(ref data_type) = self.data_type {
2585 write!(f, " {data_type}")?;
2586 }
2587 Ok(())
2588 }
2589}
2590
2591#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2592#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2593#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2594pub enum TableVersion {
2596 ForSystemTimeAsOf(Expr),
2599 TimestampAsOf(Expr),
2603 VersionAsOf(Expr),
2607 Function(Expr),
2610 Changes {
2620 changes: Expr,
2622 at: Expr,
2624 end: Option<Expr>,
2626 },
2627}
2628
2629impl Display for TableVersion {
2630 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2631 match self {
2632 TableVersion::ForSystemTimeAsOf(e) => write!(f, "FOR SYSTEM_TIME AS OF {e}")?,
2633 TableVersion::TimestampAsOf(e) => write!(f, "TIMESTAMP AS OF {e}")?,
2634 TableVersion::VersionAsOf(e) => write!(f, "VERSION AS OF {e}")?,
2635 TableVersion::Function(func) => write!(f, "{func}")?,
2636 TableVersion::Changes { changes, at, end } => {
2637 write!(f, "{changes} {at}")?;
2638 if let Some(end) = end {
2639 write!(f, " {end}")?;
2640 }
2641 }
2642 }
2643 Ok(())
2644 }
2645}
2646
2647#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2648#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2649#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2650pub struct Join {
2652 pub relation: TableFactor,
2654 pub global: bool,
2657 pub join_operator: JoinOperator,
2659}
2660
2661impl fmt::Display for Join {
2662 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2663 fn prefix(constraint: &JoinConstraint) -> &'static str {
2664 match constraint {
2665 JoinConstraint::Natural => "NATURAL ",
2666 _ => "",
2667 }
2668 }
2669 fn suffix(constraint: &'_ JoinConstraint) -> impl fmt::Display + '_ {
2670 struct Suffix<'a>(&'a JoinConstraint);
2671 impl fmt::Display for Suffix<'_> {
2672 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2673 match self.0 {
2674 JoinConstraint::On(expr) => write!(f, " ON {expr}"),
2675 JoinConstraint::Using(attrs) => {
2676 write!(f, " USING({})", display_comma_separated(attrs))
2677 }
2678 _ => Ok(()),
2679 }
2680 }
2681 }
2682 Suffix(constraint)
2683 }
2684 if self.global {
2685 write!(f, "GLOBAL ")?;
2686 }
2687
2688 match &self.join_operator {
2689 JoinOperator::Join(constraint) => f.write_fmt(format_args!(
2690 "{}JOIN {}{}",
2691 prefix(constraint),
2692 self.relation,
2693 suffix(constraint)
2694 )),
2695 JoinOperator::Inner(constraint) => f.write_fmt(format_args!(
2696 "{}INNER JOIN {}{}",
2697 prefix(constraint),
2698 self.relation,
2699 suffix(constraint)
2700 )),
2701 JoinOperator::Left(constraint) => f.write_fmt(format_args!(
2702 "{}LEFT JOIN {}{}",
2703 prefix(constraint),
2704 self.relation,
2705 suffix(constraint)
2706 )),
2707 JoinOperator::LeftOuter(constraint) => f.write_fmt(format_args!(
2708 "{}LEFT OUTER JOIN {}{}",
2709 prefix(constraint),
2710 self.relation,
2711 suffix(constraint)
2712 )),
2713 JoinOperator::Right(constraint) => f.write_fmt(format_args!(
2714 "{}RIGHT JOIN {}{}",
2715 prefix(constraint),
2716 self.relation,
2717 suffix(constraint)
2718 )),
2719 JoinOperator::RightOuter(constraint) => f.write_fmt(format_args!(
2720 "{}RIGHT OUTER JOIN {}{}",
2721 prefix(constraint),
2722 self.relation,
2723 suffix(constraint)
2724 )),
2725 JoinOperator::FullOuter(constraint) => f.write_fmt(format_args!(
2726 "{}FULL JOIN {}{}",
2727 prefix(constraint),
2728 self.relation,
2729 suffix(constraint)
2730 )),
2731 JoinOperator::CrossJoin(constraint) => f.write_fmt(format_args!(
2732 "CROSS JOIN {}{}",
2733 self.relation,
2734 suffix(constraint)
2735 )),
2736 JoinOperator::Semi(constraint) => f.write_fmt(format_args!(
2737 "{}SEMI JOIN {}{}",
2738 prefix(constraint),
2739 self.relation,
2740 suffix(constraint)
2741 )),
2742 JoinOperator::LeftSemi(constraint) => f.write_fmt(format_args!(
2743 "{}LEFT SEMI JOIN {}{}",
2744 prefix(constraint),
2745 self.relation,
2746 suffix(constraint)
2747 )),
2748 JoinOperator::RightSemi(constraint) => f.write_fmt(format_args!(
2749 "{}RIGHT SEMI JOIN {}{}",
2750 prefix(constraint),
2751 self.relation,
2752 suffix(constraint)
2753 )),
2754 JoinOperator::Anti(constraint) => f.write_fmt(format_args!(
2755 "{}ANTI JOIN {}{}",
2756 prefix(constraint),
2757 self.relation,
2758 suffix(constraint)
2759 )),
2760 JoinOperator::LeftAnti(constraint) => f.write_fmt(format_args!(
2761 "{}LEFT ANTI JOIN {}{}",
2762 prefix(constraint),
2763 self.relation,
2764 suffix(constraint)
2765 )),
2766 JoinOperator::RightAnti(constraint) => f.write_fmt(format_args!(
2767 "{}RIGHT ANTI JOIN {}{}",
2768 prefix(constraint),
2769 self.relation,
2770 suffix(constraint)
2771 )),
2772 JoinOperator::CrossApply => f.write_fmt(format_args!("CROSS APPLY {}", self.relation)),
2773 JoinOperator::OuterApply => f.write_fmt(format_args!("OUTER APPLY {}", self.relation)),
2774 JoinOperator::AsOf {
2775 match_condition,
2776 constraint,
2777 } => f.write_fmt(format_args!(
2778 "ASOF JOIN {} MATCH_CONDITION ({match_condition}){}",
2779 self.relation,
2780 suffix(constraint)
2781 )),
2782 JoinOperator::StraightJoin(constraint) => f.write_fmt(format_args!(
2783 "STRAIGHT_JOIN {}{}",
2784 self.relation,
2785 suffix(constraint)
2786 )),
2787 JoinOperator::ArrayJoin => f.write_fmt(format_args!("ARRAY JOIN {}", self.relation)),
2788 JoinOperator::LeftArrayJoin => {
2789 f.write_fmt(format_args!("LEFT ARRAY JOIN {}", self.relation))
2790 }
2791 JoinOperator::InnerArrayJoin => {
2792 f.write_fmt(format_args!("INNER ARRAY JOIN {}", self.relation))
2793 }
2794 }
2795 }
2796}
2797
2798#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2799#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2800#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2801pub enum JoinOperator {
2803 Join(JoinConstraint),
2805 Inner(JoinConstraint),
2807 Left(JoinConstraint),
2809 LeftOuter(JoinConstraint),
2811 Right(JoinConstraint),
2813 RightOuter(JoinConstraint),
2815 FullOuter(JoinConstraint),
2817 CrossJoin(JoinConstraint),
2819 Semi(JoinConstraint),
2821 LeftSemi(JoinConstraint),
2823 RightSemi(JoinConstraint),
2825 Anti(JoinConstraint),
2827 LeftAnti(JoinConstraint),
2829 RightAnti(JoinConstraint),
2831 CrossApply,
2833 OuterApply,
2835 AsOf {
2839 match_condition: Expr,
2841 constraint: JoinConstraint,
2843 },
2844 StraightJoin(JoinConstraint),
2848 ArrayJoin,
2852 LeftArrayJoin,
2854 InnerArrayJoin,
2856}
2857
2858#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2859#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2860#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2861pub enum JoinConstraint {
2863 On(Expr),
2865 Using(Vec<ObjectName>),
2867 Natural,
2869 None,
2871}
2872
2873#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2874#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2875#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2876pub enum OrderByKind {
2878 All(OrderByOptions),
2883
2884 Expressions(Vec<OrderByExpr>),
2886}
2887
2888#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2889#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2890#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2891pub struct OrderBy {
2893 pub kind: OrderByKind,
2895
2896 pub interpolate: Option<Interpolate>,
2898}
2899
2900impl fmt::Display for OrderBy {
2901 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2902 write!(f, "ORDER BY")?;
2903 match &self.kind {
2904 OrderByKind::Expressions(exprs) => {
2905 write!(f, " {}", display_comma_separated(exprs))?;
2906 }
2907 OrderByKind::All(all) => {
2908 write!(f, " ALL{all}")?;
2909 }
2910 }
2911
2912 if let Some(ref interpolate) = self.interpolate {
2913 match &interpolate.exprs {
2914 Some(exprs) => write!(f, " INTERPOLATE ({})", display_comma_separated(exprs))?,
2915 None => write!(f, " INTERPOLATE")?,
2916 }
2917 }
2918
2919 Ok(())
2920 }
2921}
2922
2923#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2925#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2926#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2927pub struct OrderByExpr {
2928 pub expr: Expr,
2930 pub options: OrderByOptions,
2932 pub with_fill: Option<WithFill>,
2934}
2935
2936impl From<Ident> for OrderByExpr {
2937 fn from(ident: Ident) -> Self {
2938 OrderByExpr {
2939 expr: Expr::Identifier(ident),
2940 options: OrderByOptions::default(),
2941 with_fill: None,
2942 }
2943 }
2944}
2945
2946impl fmt::Display for OrderByExpr {
2947 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2948 write!(f, "{}", self.expr)?;
2949 write!(f, "{}", self.options)?;
2950 if let Some(ref with_fill) = self.with_fill {
2951 write!(f, " {with_fill}")?
2952 }
2953 Ok(())
2954 }
2955}
2956
2957#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2962#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2963#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2964pub struct WithFill {
2966 pub from: Option<Expr>,
2968 pub to: Option<Expr>,
2970 pub step: Option<Expr>,
2972}
2973
2974impl fmt::Display for WithFill {
2975 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2976 write!(f, "WITH FILL")?;
2977 if let Some(ref from) = self.from {
2978 write!(f, " FROM {from}")?;
2979 }
2980 if let Some(ref to) = self.to {
2981 write!(f, " TO {to}")?;
2982 }
2983 if let Some(ref step) = self.step {
2984 write!(f, " STEP {step}")?;
2985 }
2986 Ok(())
2987 }
2988}
2989
2990#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
2995#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
2996#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
2997pub struct InterpolateExpr {
2999 pub column: Ident,
3001 pub expr: Option<Expr>,
3003}
3004
3005#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3006#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3007#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3008pub struct Interpolate {
3010 pub exprs: Option<Vec<InterpolateExpr>>,
3012}
3013
3014impl fmt::Display for InterpolateExpr {
3015 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3016 write!(f, "{}", self.column)?;
3017 if let Some(ref expr) = self.expr {
3018 write!(f, " AS {expr}")?;
3019 }
3020 Ok(())
3021 }
3022}
3023
3024#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3029#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3030#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3031pub enum OrderBySort {
3032 Asc,
3034 Desc,
3036 Using(ObjectName),
3040}
3041
3042#[derive(Default, Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3043#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3044#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3045pub struct OrderByOptions {
3047 pub sort: Option<OrderBySort>,
3049 pub nulls_first: Option<bool>,
3051}
3052
3053impl fmt::Display for OrderByOptions {
3054 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3055 match &self.sort {
3056 Some(OrderBySort::Asc) => write!(f, " ASC")?,
3057 Some(OrderBySort::Desc) => write!(f, " DESC")?,
3058 Some(OrderBySort::Using(op)) => {
3059 if op.0.len() > 1 {
3060 write!(f, " USING OPERATOR({op})")?;
3061 } else {
3062 write!(f, " USING {op}")?;
3063 }
3064 }
3065 None => (),
3066 }
3067 match self.nulls_first {
3068 Some(true) => write!(f, " NULLS FIRST")?,
3069 Some(false) => write!(f, " NULLS LAST")?,
3070 None => (),
3071 }
3072 Ok(())
3073 }
3074}
3075
3076#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3077#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3078#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3079pub enum LimitClause {
3081 LimitOffset {
3085 limit: Option<Expr>,
3087 offset: Option<Offset>,
3089 limit_by: Vec<Expr>,
3091 },
3092 OffsetCommaLimit {
3094 offset: Expr,
3096 limit: Expr,
3098 },
3099}
3100
3101impl fmt::Display for LimitClause {
3102 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3103 match self {
3104 LimitClause::LimitOffset {
3105 limit,
3106 limit_by,
3107 offset,
3108 } => {
3109 if let Some(ref limit) = limit {
3110 write!(f, " LIMIT {limit}")?;
3111 }
3112 if let Some(ref offset) = offset {
3113 write!(f, " {offset}")?;
3114 }
3115 if !limit_by.is_empty() {
3116 debug_assert!(limit.is_some());
3117 write!(f, " BY {}", display_separated(limit_by, ", "))?;
3118 }
3119 Ok(())
3120 }
3121 LimitClause::OffsetCommaLimit { offset, limit } => {
3122 write!(f, " LIMIT {offset}, {limit}")
3123 }
3124 }
3125 }
3126}
3127
3128#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3129#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3130#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3131pub struct Offset {
3133 pub value: Expr,
3135 pub rows: OffsetRows,
3137}
3138
3139impl fmt::Display for Offset {
3140 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3141 write!(f, "OFFSET {}{}", self.value, self.rows)
3142 }
3143}
3144
3145#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3147#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3148#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3149pub enum OffsetRows {
3150 None,
3152 Row,
3154 Rows,
3156}
3157
3158impl fmt::Display for OffsetRows {
3159 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3160 match self {
3161 OffsetRows::None => Ok(()),
3162 OffsetRows::Row => write!(f, " ROW"),
3163 OffsetRows::Rows => write!(f, " ROWS"),
3164 }
3165 }
3166}
3167
3168#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3180#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3181#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3182pub enum PipeOperator {
3183 Limit {
3189 expr: Expr,
3191 offset: Option<Expr>,
3193 },
3194 Where {
3200 expr: Expr,
3202 },
3203 OrderBy {
3205 exprs: Vec<OrderByExpr>,
3207 },
3208 Select {
3214 exprs: Vec<SelectItem>,
3216 },
3217 Extend {
3223 exprs: Vec<SelectItem>,
3225 },
3226 Set {
3232 assignments: Vec<Assignment>,
3234 },
3235 Drop {
3241 columns: Vec<Ident>,
3243 },
3244 As {
3250 alias: Ident,
3252 },
3253 Aggregate {
3265 full_table_exprs: Vec<ExprWithAliasAndOrderBy>,
3267 group_by_expr: Vec<ExprWithAliasAndOrderBy>,
3269 },
3270 TableSample {
3274 sample: Box<TableSample>,
3276 },
3277 Rename {
3283 mappings: Vec<IdentWithAlias>,
3285 },
3286 Union {
3292 set_quantifier: SetQuantifier,
3294 queries: Vec<Query>,
3296 },
3297 Intersect {
3303 set_quantifier: SetQuantifier,
3305 queries: Vec<Query>,
3307 },
3308 Except {
3314 set_quantifier: SetQuantifier,
3316 queries: Vec<Query>,
3318 },
3319 Call {
3325 function: Function,
3327 alias: Option<Ident>,
3329 },
3330 Pivot {
3336 aggregate_functions: Vec<ExprWithAlias>,
3338 value_column: Vec<Ident>,
3340 value_source: PivotValueSource,
3342 alias: Option<Ident>,
3344 },
3345 Unpivot {
3354 value_column: Ident,
3356 name_column: Ident,
3358 unpivot_columns: Vec<Ident>,
3360 alias: Option<Ident>,
3362 },
3363 Join(Join),
3369}
3370
3371impl fmt::Display for PipeOperator {
3372 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3373 match self {
3374 PipeOperator::Select { exprs } => {
3375 write!(f, "SELECT {}", display_comma_separated(exprs.as_slice()))
3376 }
3377 PipeOperator::Extend { exprs } => {
3378 write!(f, "EXTEND {}", display_comma_separated(exprs.as_slice()))
3379 }
3380 PipeOperator::Set { assignments } => {
3381 write!(f, "SET {}", display_comma_separated(assignments.as_slice()))
3382 }
3383 PipeOperator::Drop { columns } => {
3384 write!(f, "DROP {}", display_comma_separated(columns.as_slice()))
3385 }
3386 PipeOperator::As { alias } => {
3387 write!(f, "AS {alias}")
3388 }
3389 PipeOperator::Limit { expr, offset } => {
3390 write!(f, "LIMIT {expr}")?;
3391 if let Some(offset) = offset {
3392 write!(f, " OFFSET {offset}")?;
3393 }
3394 Ok(())
3395 }
3396 PipeOperator::Aggregate {
3397 full_table_exprs,
3398 group_by_expr,
3399 } => {
3400 write!(f, "AGGREGATE")?;
3401 if !full_table_exprs.is_empty() {
3402 write!(
3403 f,
3404 " {}",
3405 display_comma_separated(full_table_exprs.as_slice())
3406 )?;
3407 }
3408 if !group_by_expr.is_empty() {
3409 write!(f, " GROUP BY {}", display_comma_separated(group_by_expr))?;
3410 }
3411 Ok(())
3412 }
3413
3414 PipeOperator::Where { expr } => {
3415 write!(f, "WHERE {expr}")
3416 }
3417 PipeOperator::OrderBy { exprs } => {
3418 write!(f, "ORDER BY {}", display_comma_separated(exprs.as_slice()))
3419 }
3420
3421 PipeOperator::TableSample { sample } => {
3422 write!(f, "{sample}")
3423 }
3424 PipeOperator::Rename { mappings } => {
3425 write!(f, "RENAME {}", display_comma_separated(mappings))
3426 }
3427 PipeOperator::Union {
3428 set_quantifier,
3429 queries,
3430 } => Self::fmt_set_operation(f, "UNION", set_quantifier, queries),
3431 PipeOperator::Intersect {
3432 set_quantifier,
3433 queries,
3434 } => Self::fmt_set_operation(f, "INTERSECT", set_quantifier, queries),
3435 PipeOperator::Except {
3436 set_quantifier,
3437 queries,
3438 } => Self::fmt_set_operation(f, "EXCEPT", set_quantifier, queries),
3439 PipeOperator::Call { function, alias } => {
3440 write!(f, "CALL {function}")?;
3441 Self::fmt_optional_alias(f, alias)
3442 }
3443 PipeOperator::Pivot {
3444 aggregate_functions,
3445 value_column,
3446 value_source,
3447 alias,
3448 } => {
3449 write!(
3450 f,
3451 "PIVOT({} FOR {} IN ({}))",
3452 display_comma_separated(aggregate_functions),
3453 Expr::CompoundIdentifier(value_column.to_vec()),
3454 value_source
3455 )?;
3456 Self::fmt_optional_alias(f, alias)
3457 }
3458 PipeOperator::Unpivot {
3459 value_column,
3460 name_column,
3461 unpivot_columns,
3462 alias,
3463 } => {
3464 write!(
3465 f,
3466 "UNPIVOT({} FOR {} IN ({}))",
3467 value_column,
3468 name_column,
3469 display_comma_separated(unpivot_columns)
3470 )?;
3471 Self::fmt_optional_alias(f, alias)
3472 }
3473 PipeOperator::Join(join) => write!(f, "{join}"),
3474 }
3475 }
3476}
3477
3478impl PipeOperator {
3479 fn fmt_optional_alias(f: &mut fmt::Formatter<'_>, alias: &Option<Ident>) -> fmt::Result {
3481 if let Some(alias) = alias {
3482 write!(f, " AS {alias}")?;
3483 }
3484 Ok(())
3485 }
3486
3487 fn fmt_set_operation(
3489 f: &mut fmt::Formatter<'_>,
3490 operation: &str,
3491 set_quantifier: &SetQuantifier,
3492 queries: &[Query],
3493 ) -> fmt::Result {
3494 write!(f, "{operation}")?;
3495 match set_quantifier {
3496 SetQuantifier::None => {}
3497 _ => {
3498 write!(f, " {set_quantifier}")?;
3499 }
3500 }
3501 write!(f, " ")?;
3502 let parenthesized_queries: Vec<String> =
3503 queries.iter().map(|query| format!("({query})")).collect();
3504 write!(f, "{}", display_comma_separated(&parenthesized_queries))
3505 }
3506}
3507
3508#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3509#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3510#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3511pub struct Fetch {
3513 pub with_ties: bool,
3515 pub percent: bool,
3517 pub quantity: Option<Expr>,
3519}
3520
3521impl fmt::Display for Fetch {
3522 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3523 let extension = if self.with_ties { "WITH TIES" } else { "ONLY" };
3524 if let Some(ref quantity) = self.quantity {
3525 let percent = if self.percent { " PERCENT" } else { "" };
3526 write!(f, "FETCH FIRST {quantity}{percent} ROWS {extension}")
3527 } else {
3528 write!(f, "FETCH FIRST ROWS {extension}")
3529 }
3530 }
3531}
3532
3533#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3534#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3535#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3536pub struct LockClause {
3538 pub lock_type: LockType,
3540 pub of: Option<ObjectName>,
3542 pub nonblock: Option<NonBlock>,
3544}
3545
3546impl fmt::Display for LockClause {
3547 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3548 write!(f, "FOR {}", &self.lock_type)?;
3549 if let Some(ref of) = self.of {
3550 write!(f, " OF {of}")?;
3551 }
3552 if let Some(ref nb) = self.nonblock {
3553 write!(f, " {nb}")?;
3554 }
3555 Ok(())
3556 }
3557}
3558
3559#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3560#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3561#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3562pub enum LockType {
3564 Share,
3566 Update,
3568}
3569
3570impl fmt::Display for LockType {
3571 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3572 let select_lock = match self {
3573 LockType::Share => "SHARE",
3574 LockType::Update => "UPDATE",
3575 };
3576 write!(f, "{select_lock}")
3577 }
3578}
3579
3580#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3581#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3582#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3583pub enum NonBlock {
3585 Nowait,
3587 SkipLocked,
3589}
3590
3591impl fmt::Display for NonBlock {
3592 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3593 let nonblock = match self {
3594 NonBlock::Nowait => "NOWAIT",
3595 NonBlock::SkipLocked => "SKIP LOCKED",
3596 };
3597 write!(f, "{nonblock}")
3598 }
3599}
3600
3601#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3602#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3603#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3604pub enum Distinct {
3606 All,
3611
3612 Distinct,
3614
3615 On(Vec<Expr>),
3617}
3618
3619impl fmt::Display for Distinct {
3620 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3621 match self {
3622 Distinct::All => write!(f, "ALL"),
3623 Distinct::Distinct => write!(f, "DISTINCT"),
3624 Distinct::On(col_names) => {
3625 let col_names = display_comma_separated(col_names);
3626 write!(f, "DISTINCT ON ({col_names})")
3627 }
3628 }
3629 }
3630}
3631
3632#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3633#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3634#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3635pub struct Top {
3637 pub with_ties: bool,
3640 pub percent: bool,
3642 pub quantity: Option<TopQuantity>,
3644}
3645
3646#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3647#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3648#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3649pub enum TopQuantity {
3651 Expr(Expr),
3653 Constant(u64),
3655}
3656
3657impl fmt::Display for Top {
3658 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3659 let extension = if self.with_ties { " WITH TIES" } else { "" };
3660 if let Some(ref quantity) = self.quantity {
3661 let percent = if self.percent { " PERCENT" } else { "" };
3662 match quantity {
3663 TopQuantity::Expr(quantity) => write!(f, "TOP ({quantity}){percent}{extension}"),
3664 TopQuantity::Constant(quantity) => {
3665 write!(f, "TOP {quantity}{percent}{extension}")
3666 }
3667 }
3668 } else {
3669 write!(f, "TOP{extension}")
3670 }
3671 }
3672}
3673
3674#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3675#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3676#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3677pub struct Values {
3679 pub explicit_row: bool,
3682 pub value_keyword: bool,
3685 pub rows: Vec<Parens<Vec<Expr>>>,
3687}
3688
3689impl fmt::Display for Values {
3690 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3691 match self.value_keyword {
3692 true => f.write_str("VALUE")?,
3693 false => f.write_str("VALUES")?,
3694 };
3695 let prefix = if self.explicit_row { "ROW" } else { "" };
3696 let mut delim = "";
3697 for row in &self.rows {
3698 f.write_str(delim)?;
3699 delim = ",";
3700 SpaceOrNewline.fmt(f)?;
3701 Indent(format_args!("{prefix}({})", display_comma_separated(row))).fmt(f)?;
3702 }
3703 Ok(())
3704 }
3705}
3706
3707#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3708#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3709#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3710pub struct SelectInto {
3712 pub temporary: bool,
3714 pub unlogged: bool,
3716 pub table: bool,
3718 pub targets: Vec<Expr>,
3723}
3724
3725impl fmt::Display for SelectInto {
3726 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3727 let temporary = if self.temporary { " TEMPORARY" } else { "" };
3728 let unlogged = if self.unlogged { " UNLOGGED" } else { "" };
3729 let table = if self.table { " TABLE" } else { "" };
3730
3731 write!(
3732 f,
3733 "INTO{}{}{} {}",
3734 temporary,
3735 unlogged,
3736 table,
3737 display_comma_separated(&self.targets)
3738 )
3739 }
3740}
3741
3742#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3747#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3748#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3749pub enum GroupByWithModifier {
3751 Rollup,
3753 Cube,
3755 Totals,
3757 GroupingSets(Expr),
3761}
3762
3763impl fmt::Display for GroupByWithModifier {
3764 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3765 match self {
3766 GroupByWithModifier::Rollup => write!(f, "WITH ROLLUP"),
3767 GroupByWithModifier::Cube => write!(f, "WITH CUBE"),
3768 GroupByWithModifier::Totals => write!(f, "WITH TOTALS"),
3769 GroupByWithModifier::GroupingSets(expr) => {
3770 write!(f, "{expr}")
3771 }
3772 }
3773 }
3774}
3775
3776#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3777#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3778#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3779pub enum GroupByExpr {
3782 All(Vec<GroupByWithModifier>),
3792 Expressions(Vec<Expr>, Vec<GroupByWithModifier>),
3794}
3795
3796impl fmt::Display for GroupByExpr {
3797 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3798 match self {
3799 GroupByExpr::All(modifiers) => {
3800 write!(f, "GROUP BY ALL")?;
3801 if !modifiers.is_empty() {
3802 write!(f, " {}", display_separated(modifiers, " "))?;
3803 }
3804 Ok(())
3805 }
3806 GroupByExpr::Expressions(col_names, modifiers) => {
3807 f.write_str("GROUP BY")?;
3808 SpaceOrNewline.fmt(f)?;
3809 Indent(display_comma_separated(col_names)).fmt(f)?;
3810 if !modifiers.is_empty() {
3811 write!(f, " {}", display_separated(modifiers, " "))?;
3812 }
3813 Ok(())
3814 }
3815 }
3816 }
3817}
3818
3819#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3823#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3824#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3825pub enum FormatClause {
3826 Identifier(Ident),
3828 Null,
3830}
3831
3832impl fmt::Display for FormatClause {
3833 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3834 match self {
3835 FormatClause::Identifier(ident) => write!(f, "FORMAT {ident}"),
3836 FormatClause::Null => write!(f, "FORMAT NULL"),
3837 }
3838 }
3839}
3840
3841#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3845#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3846#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3847pub struct InputFormatClause {
3848 pub ident: Ident,
3850 pub values: Vec<Expr>,
3852}
3853
3854impl fmt::Display for InputFormatClause {
3855 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3856 write!(f, "FORMAT {}", self.ident)?;
3857
3858 if !self.values.is_empty() {
3859 write!(f, " {}", display_comma_separated(self.values.as_slice()))?;
3860 }
3861
3862 Ok(())
3863 }
3864}
3865
3866#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3868#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3869#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3870pub enum ForClause {
3871 Browse,
3873 Json {
3875 for_json: ForJson,
3877 root: Option<String>,
3879 include_null_values: bool,
3881 without_array_wrapper: bool,
3883 },
3884 Xml {
3886 for_xml: ForXml,
3888 elements: bool,
3890 binary_base64: bool,
3892 root: Option<String>,
3894 r#type: bool,
3896 },
3897}
3898
3899impl fmt::Display for ForClause {
3900 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3901 match self {
3902 ForClause::Browse => write!(f, "FOR BROWSE"),
3903 ForClause::Json {
3904 for_json,
3905 root,
3906 include_null_values,
3907 without_array_wrapper,
3908 } => {
3909 write!(f, "FOR JSON ")?;
3910 write!(f, "{for_json}")?;
3911 if let Some(root) = root {
3912 write!(f, ", ROOT('{root}')")?;
3913 }
3914 if *include_null_values {
3915 write!(f, ", INCLUDE_NULL_VALUES")?;
3916 }
3917 if *without_array_wrapper {
3918 write!(f, ", WITHOUT_ARRAY_WRAPPER")?;
3919 }
3920 Ok(())
3921 }
3922 ForClause::Xml {
3923 for_xml,
3924 elements,
3925 binary_base64,
3926 root,
3927 r#type,
3928 } => {
3929 write!(f, "FOR XML ")?;
3930 write!(f, "{for_xml}")?;
3931 if *binary_base64 {
3932 write!(f, ", BINARY BASE64")?;
3933 }
3934 if *r#type {
3935 write!(f, ", TYPE")?;
3936 }
3937 if let Some(root) = root {
3938 write!(f, ", ROOT('{root}')")?;
3939 }
3940 if *elements {
3941 write!(f, ", ELEMENTS")?;
3942 }
3943 Ok(())
3944 }
3945 }
3946 }
3947}
3948
3949#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3950#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3951#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3952pub enum ForXml {
3954 Raw(Option<String>),
3956 Auto,
3958 Explicit,
3960 Path(Option<String>),
3962}
3963
3964impl fmt::Display for ForXml {
3965 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3966 match self {
3967 ForXml::Raw(root) => {
3968 write!(f, "RAW")?;
3969 if let Some(root) = root {
3970 write!(f, "('{root}')")?;
3971 }
3972 Ok(())
3973 }
3974 ForXml::Auto => write!(f, "AUTO"),
3975 ForXml::Explicit => write!(f, "EXPLICIT"),
3976 ForXml::Path(root) => {
3977 write!(f, "PATH")?;
3978 if let Some(root) = root {
3979 write!(f, "('{root}')")?;
3980 }
3981 Ok(())
3982 }
3983 }
3984 }
3985}
3986
3987#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
3988#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
3989#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
3990pub enum ForJson {
3992 Auto,
3994 Path,
3996}
3997
3998impl fmt::Display for ForJson {
3999 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4000 match self {
4001 ForJson::Auto => write!(f, "AUTO"),
4002 ForJson::Path => write!(f, "PATH"),
4003 }
4004 }
4005}
4006
4007#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4028#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4029#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4030pub enum JsonTableColumn {
4031 Named(JsonTableNamedColumn),
4033 ForOrdinality(Ident),
4035 Nested(JsonTableNestedColumn),
4037}
4038
4039impl fmt::Display for JsonTableColumn {
4040 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4041 match self {
4042 JsonTableColumn::Named(json_table_named_column) => {
4043 write!(f, "{json_table_named_column}")
4044 }
4045 JsonTableColumn::ForOrdinality(ident) => write!(f, "{ident} FOR ORDINALITY"),
4046 JsonTableColumn::Nested(json_table_nested_column) => {
4047 write!(f, "{json_table_nested_column}")
4048 }
4049 }
4050 }
4051}
4052
4053#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4057#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4058#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4059pub struct JsonTableNestedColumn {
4061 pub path: ValueWithSpan,
4063 pub columns: Vec<JsonTableColumn>,
4065}
4066
4067impl fmt::Display for JsonTableNestedColumn {
4068 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4069 write!(
4070 f,
4071 "NESTED PATH {} COLUMNS ({})",
4072 self.path,
4073 display_comma_separated(&self.columns)
4074 )
4075 }
4076}
4077
4078#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4086#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4087#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4088pub struct JsonTableNamedColumn {
4089 pub name: Ident,
4091 pub r#type: DataType,
4093 pub path: ValueWithSpan,
4095 pub exists: bool,
4097 pub on_empty: Option<JsonTableColumnErrorHandling>,
4099 pub on_error: Option<JsonTableColumnErrorHandling>,
4101}
4102
4103impl fmt::Display for JsonTableNamedColumn {
4104 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4105 write!(
4106 f,
4107 "{} {}{} PATH {}",
4108 self.name,
4109 self.r#type,
4110 if self.exists { " EXISTS" } else { "" },
4111 self.path
4112 )?;
4113 if let Some(on_empty) = &self.on_empty {
4114 write!(f, " {on_empty} ON EMPTY")?;
4115 }
4116 if let Some(on_error) = &self.on_error {
4117 write!(f, " {on_error} ON ERROR")?;
4118 }
4119 Ok(())
4120 }
4121}
4122
4123#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4126#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4127#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4128pub enum JsonTableColumnErrorHandling {
4130 Null,
4132 Default(ValueWithSpan),
4134 Error,
4136}
4137
4138impl fmt::Display for JsonTableColumnErrorHandling {
4139 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4140 match self {
4141 JsonTableColumnErrorHandling::Null => write!(f, "NULL"),
4142 JsonTableColumnErrorHandling::Default(json_string) => {
4143 write!(f, "DEFAULT {json_string}")
4144 }
4145 JsonTableColumnErrorHandling::Error => write!(f, "ERROR"),
4146 }
4147 }
4148}
4149
4150#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4158#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4159#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4160pub struct OpenJsonTableColumn {
4161 pub name: Ident,
4163 pub r#type: DataType,
4165 pub path: Option<String>,
4167 pub as_json: bool,
4169}
4170
4171impl fmt::Display for OpenJsonTableColumn {
4172 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4173 write!(f, "{} {}", self.name, self.r#type)?;
4174 if let Some(path) = &self.path {
4175 write!(f, " '{}'", value::escape_single_quote_string(path))?;
4176 }
4177 if self.as_json {
4178 write!(f, " AS JSON")?;
4179 }
4180 Ok(())
4181 }
4182}
4183
4184#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4191#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4192#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4193pub enum ValueTableMode {
4195 AsStruct,
4197 AsValue,
4199 DistinctAsStruct,
4201 DistinctAsValue,
4203}
4204
4205impl fmt::Display for ValueTableMode {
4206 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4207 match self {
4208 ValueTableMode::AsStruct => write!(f, "AS STRUCT"),
4209 ValueTableMode::AsValue => write!(f, "AS VALUE"),
4210 ValueTableMode::DistinctAsStruct => write!(f, "DISTINCT AS STRUCT"),
4211 ValueTableMode::DistinctAsValue => write!(f, "DISTINCT AS VALUE"),
4212 }
4213 }
4214}
4215
4216#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4218#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4219#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4220pub enum UpdateTableFromKind {
4221 BeforeSet(Vec<TableWithJoins>),
4224 AfterSet(Vec<TableWithJoins>),
4227}
4228
4229#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4231#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4232#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4233pub enum XmlTableColumnOption {
4234 NamedInfo {
4236 r#type: DataType,
4238 path: Option<Expr>,
4240 default: Option<Expr>,
4242 nullable: bool,
4244 },
4245 ForOrdinality,
4247}
4248
4249#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4262#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4263#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4264pub struct XmlTableColumn {
4265 pub name: Ident,
4267 pub option: XmlTableColumnOption,
4269}
4270
4271impl fmt::Display for XmlTableColumn {
4272 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4273 write!(f, "{}", self.name)?;
4274 match &self.option {
4275 XmlTableColumnOption::NamedInfo {
4276 r#type,
4277 path,
4278 default,
4279 nullable,
4280 } => {
4281 write!(f, " {type}")?;
4282 if let Some(p) = path {
4283 write!(f, " PATH {p}")?;
4284 }
4285 if let Some(d) = default {
4286 write!(f, " DEFAULT {d}")?;
4287 }
4288 if !*nullable {
4289 write!(f, " NOT NULL")?;
4290 }
4291 Ok(())
4292 }
4293 XmlTableColumnOption::ForOrdinality => {
4294 write!(f, " FOR ORDINALITY")
4295 }
4296 }
4297 }
4298}
4299
4300#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4302#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4303#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4304pub struct XmlPassingArgument {
4306 pub expr: Expr,
4308 pub alias: Option<Ident>,
4310 pub by_value: bool,
4312}
4313
4314impl fmt::Display for XmlPassingArgument {
4315 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4316 if self.by_value {
4317 write!(f, "BY VALUE ")?;
4318 }
4319 write!(f, "{}", self.expr)?;
4320 if let Some(alias) = &self.alias {
4321 write!(f, " AS {alias}")?;
4322 }
4323 Ok(())
4324 }
4325}
4326
4327#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4329#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4330#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4331pub struct XmlPassingClause {
4333 pub arguments: Vec<XmlPassingArgument>,
4335}
4336
4337impl fmt::Display for XmlPassingClause {
4338 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4339 if !self.arguments.is_empty() {
4340 write!(f, " PASSING {}", display_comma_separated(&self.arguments))?;
4341 }
4342 Ok(())
4343 }
4344}
4345
4346#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
4350#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
4351#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
4352pub struct XmlNamespaceDefinition {
4353 pub uri: Expr,
4355 pub name: Ident,
4357}
4358
4359impl fmt::Display for XmlNamespaceDefinition {
4360 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4361 write!(f, "{} AS {}", self.uri, self.name)
4362 }
4363}