1use crate::ast::*;
2use crate::dialects::Dialect;
3
4pub struct Generator {
10 output: String,
11 pretty: bool,
13 indent: usize,
14 dialect: Option<Dialect>,
16}
17
18impl Generator {
19 #[must_use]
20 pub fn new() -> Self {
21 Self {
22 output: String::new(),
23 pretty: false,
24 indent: 0,
25 dialect: None,
26 }
27 }
28
29 #[must_use]
31 pub fn pretty() -> Self {
32 Self {
33 output: String::new(),
34 pretty: true,
35 indent: 0,
36 dialect: None,
37 }
38 }
39
40 #[must_use]
42 pub fn with_dialect(dialect: Dialect) -> Self {
43 Self {
44 output: String::new(),
45 pretty: false,
46 indent: 0,
47 dialect: Some(dialect),
48 }
49 }
50
51 #[must_use]
53 pub fn generate(&mut self, statement: &Statement) -> String {
54 self.output.clear();
55 self.gen_statement(statement);
56 self.output.clone()
57 }
58
59 #[must_use]
61 pub fn expr_to_sql(expr: &Expr) -> String {
62 let mut g = Self::new();
63 g.gen_expr(expr);
64 g.output
65 }
66
67 fn write(&mut self, s: &str) {
68 self.output.push_str(s);
69 }
70
71 fn newline(&mut self) {
73 if self.pretty {
74 self.output.push('\n');
75 for _ in 0..self.indent {
76 self.output.push_str(" ");
77 }
78 }
79 }
80
81 fn sep(&mut self) {
83 if self.pretty {
84 self.newline();
85 } else {
86 self.output.push(' ');
87 }
88 }
89
90 fn indent_up(&mut self) {
91 self.indent += 1;
92 }
93
94 fn indent_down(&mut self) {
95 self.indent = self.indent.saturating_sub(1);
96 }
97
98 fn write_keyword(&mut self, s: &str) {
99 self.write(s);
100 }
101
102 fn write_alias(&mut self, alias: &str, style: QuoteStyle) {
107 let effective = if !style.is_quoted()
108 && matches!(self.dialect, Some(d) if crate::dialects::is_tsql_family(d))
109 && crate::dialects::is_tsql_reserved(alias)
110 {
111 QuoteStyle::Bracket
112 } else {
113 style
114 };
115 self.write_quoted(alias, effective);
116 }
117
118 fn write_quoted(&mut self, name: &str, style: QuoteStyle) {
122 let effective_style = if style.is_quoted() {
123 if let Some(dialect) = self.dialect {
124 QuoteStyle::for_dialect(dialect)
125 } else {
126 style
127 }
128 } else {
129 style
130 };
131 match effective_style {
132 QuoteStyle::None => self.write(name),
133 QuoteStyle::DoubleQuote => {
134 self.write("\"");
135 self.write(&name.replace('"', "\"\""));
136 self.write("\"");
137 }
138 QuoteStyle::Backtick => {
139 self.write("`");
140 self.write(&name.replace('`', "``"));
141 self.write("`");
142 }
143 QuoteStyle::Bracket => {
144 self.write("[");
145 self.write(&name.replace(']', "]]"));
146 self.write("]");
147 }
148 }
149 }
150
151 fn gen_comments(&mut self, comments: &[String]) {
159 for comment in comments {
160 let normalized = self.normalize_comment(comment);
161 self.write(&normalized);
162 self.newline_or_space();
163 }
164 }
165
166 fn normalize_comment(&self, comment: &str) -> String {
169 if comment.starts_with('#') {
170 let is_mysql_target = matches!(
171 self.dialect,
172 Some(Dialect::Mysql | Dialect::Doris | Dialect::SingleStore | Dialect::StarRocks)
173 );
174 if !is_mysql_target {
175 return format!("--{}", &comment[1..]);
176 }
177 }
178 comment.to_string()
179 }
180
181 fn newline_or_space(&mut self) {
183 if self.pretty {
184 self.output.push('\n');
185 for _ in 0..self.indent {
186 self.output.push_str(" ");
187 }
188 } else {
189 self.output.push('\n');
190 }
191 }
192
193 fn gen_statement(&mut self, statement: &Statement) {
194 match statement {
196 Statement::Select(s) => {
197 self.gen_comments(&s.comments);
198 self.gen_select(s);
199 }
200 Statement::Insert(s) => {
201 self.gen_comments(&s.comments);
202 self.gen_insert(s);
203 }
204 Statement::Update(s) => {
205 self.gen_comments(&s.comments);
206 self.gen_update(s);
207 }
208 Statement::Delete(s) => {
209 self.gen_comments(&s.comments);
210 self.gen_delete(s);
211 }
212 Statement::CreateTable(s) => {
213 self.gen_comments(&s.comments);
214 self.gen_create_table(s);
215 }
216 Statement::DropTable(s) => {
217 self.gen_comments(&s.comments);
218 self.gen_drop_table(s);
219 }
220 Statement::SetOperation(s) => {
221 self.gen_comments(&s.comments);
222 self.gen_set_operation(s);
223 }
224 Statement::AlterTable(s) => {
225 self.gen_comments(&s.comments);
226 self.gen_alter_table(s);
227 }
228 Statement::CreateView(s) => {
229 self.gen_comments(&s.comments);
230 self.gen_create_view(s);
231 }
232 Statement::DropView(s) => {
233 self.gen_comments(&s.comments);
234 self.gen_drop_view(s);
235 }
236 Statement::Truncate(s) => {
237 self.gen_comments(&s.comments);
238 self.gen_truncate(s);
239 }
240 Statement::Transaction(s) => self.gen_transaction(s),
241 Statement::Explain(s) => {
242 self.gen_comments(&s.comments);
243 self.gen_explain(s);
244 }
245 Statement::Use(s) => {
246 self.gen_comments(&s.comments);
247 self.gen_use(s);
248 }
249 Statement::Merge(s) => {
250 self.gen_comments(&s.comments);
251 self.gen_merge(s);
252 }
253 Statement::Expression(e) => self.gen_expr(e),
254 Statement::Command(s) => {
255 self.gen_comments(&s.comments);
256 self.gen_command(s);
257 }
258 }
259 }
260
261 fn gen_command(&mut self, c: &crate::ast::CommandStatement) {
262 self.write(&c.kind);
263 if !c.body.is_empty() {
264 self.write(" ");
265 self.write(&c.body);
266 }
267 }
268
269 fn gen_select(&mut self, sel: &SelectStatement) {
272 if !sel.ctes.is_empty() {
274 self.gen_ctes(&sel.ctes);
275 self.sep();
276 }
277
278 self.write_keyword("SELECT");
279 if sel.distinct {
280 self.write(" ");
281 self.write_keyword("DISTINCT");
282 }
283 if let Some(top) = &sel.top {
284 self.write(" ");
285 self.write_keyword("TOP ");
286 self.gen_expr(top);
287 }
288
289 if self.pretty {
291 self.indent_up();
292 for (i, item) in sel.columns.iter().enumerate() {
293 self.newline();
294 self.gen_select_item(item);
295 if i < sel.columns.len() - 1 {
296 self.write(",");
297 }
298 }
299 self.indent_down();
300 } else {
301 self.write(" ");
302 for (i, item) in sel.columns.iter().enumerate() {
303 if i > 0 {
304 self.write(", ");
305 }
306 self.gen_select_item(item);
307 }
308 }
309
310 if let Some(from) = &sel.from {
311 self.sep();
312 self.write_keyword("FROM");
313 if self.pretty {
314 self.indent_up();
315 self.newline();
316 self.gen_table_source(&from.source);
317 self.indent_down();
318 } else {
319 self.write(" ");
320 self.gen_table_source(&from.source);
321 }
322 }
323
324 for join in &sel.joins {
325 self.gen_join(join);
326 }
327
328 if let Some(wh) = &sel.where_clause {
329 self.sep();
330 self.write_keyword("WHERE");
331 if self.pretty {
332 self.indent_up();
333 self.newline();
334 self.gen_expr(wh);
335 self.indent_down();
336 } else {
337 self.write(" ");
338 self.gen_expr(wh);
339 }
340 }
341
342 if !sel.group_by.is_empty() {
343 self.sep();
344 self.write_keyword("GROUP BY");
345 if self.pretty {
346 self.indent_up();
347 self.newline();
348 self.gen_expr_list(&sel.group_by);
349 self.indent_down();
350 } else {
351 self.write(" ");
352 self.gen_expr_list(&sel.group_by);
353 }
354 }
355
356 if let Some(having) = &sel.having {
357 self.sep();
358 self.write_keyword("HAVING");
359 if self.pretty {
360 self.indent_up();
361 self.newline();
362 self.gen_expr(having);
363 self.indent_down();
364 } else {
365 self.write(" ");
366 self.gen_expr(having);
367 }
368 }
369
370 if let Some(qualify) = &sel.qualify {
371 self.sep();
372 self.write_keyword("QUALIFY");
373 if self.pretty {
374 self.indent_up();
375 self.newline();
376 self.gen_expr(qualify);
377 self.indent_down();
378 } else {
379 self.write(" ");
380 self.gen_expr(qualify);
381 }
382 }
383
384 if !sel.window_definitions.is_empty() {
385 self.sep();
386 self.write_keyword("WINDOW ");
387 for (i, wd) in sel.window_definitions.iter().enumerate() {
388 if i > 0 {
389 self.write(", ");
390 }
391 self.write(&wd.name);
392 self.write(" AS (");
393 self.gen_window_spec(&wd.spec);
394 self.write(")");
395 }
396 }
397
398 self.gen_order_by(&sel.order_by);
399
400 if let Some(limit) = &sel.limit {
401 self.sep();
402 self.write_keyword("LIMIT ");
403 self.gen_expr(limit);
404 }
405
406 if let Some(offset) = &sel.offset {
407 self.sep();
408 if matches!(
409 self.dialect,
410 Some(Dialect::Tsql) | Some(Dialect::Fabric) | Some(Dialect::Oracle)
411 ) {
412 self.write_keyword("OFFSET ");
413 self.gen_expr(offset);
414 self.write(" ");
415 self.write_keyword("ROWS");
416 } else {
417 self.write_keyword("OFFSET ");
418 self.gen_expr(offset);
419 }
420 }
421
422 if let Some(fetch) = &sel.fetch_first {
423 self.sep();
424 if matches!(self.dialect, Some(Dialect::Tsql) | Some(Dialect::Fabric)) {
425 self.write_keyword("FETCH NEXT ");
426 self.gen_expr(fetch);
427 self.write(" ");
428 self.write_keyword("ROWS ONLY");
429 } else {
430 self.write_keyword("FETCH FIRST ");
431 self.gen_expr(fetch);
432 self.write(" ");
433 self.write_keyword("ROWS ONLY");
434 }
435 }
436 }
437
438 fn gen_ctes(&mut self, ctes: &[Cte]) {
439 self.write_keyword("WITH ");
440 if ctes.iter().any(|c| c.recursive) {
441 self.write_keyword("RECURSIVE ");
442 }
443 for (i, cte) in ctes.iter().enumerate() {
444 if i > 0 {
445 self.write(",");
446 self.sep();
447 }
448 self.write_quoted(&cte.name, cte.name_quote_style);
449 if !cte.columns.is_empty() {
450 self.write("(");
451 self.write(&cte.columns.join(", "));
452 self.write(")");
453 }
454 self.write(" ");
455 self.write_keyword("AS ");
456 if let Some(true) = cte.materialized {
457 self.write_keyword("MATERIALIZED ");
458 } else if let Some(false) = cte.materialized {
459 self.write_keyword("NOT MATERIALIZED ");
460 }
461 self.write("(");
462 if self.pretty {
463 self.indent_up();
464 self.newline();
465 self.gen_statement(&cte.query);
466 self.indent_down();
467 self.newline();
468 } else {
469 self.gen_statement(&cte.query);
470 }
471 self.write(")");
472 }
473 }
474
475 fn gen_select_item(&mut self, item: &SelectItem) {
476 match item {
477 SelectItem::Wildcard => self.write("*"),
478 SelectItem::QualifiedWildcard { table } => {
479 self.write(table);
480 self.write(".*");
481 }
482 SelectItem::Expr {
483 expr,
484 alias,
485 alias_quote_style,
486 } => {
487 self.gen_expr(expr);
488 if let Some(alias) = alias {
489 self.write(" ");
490 self.write_keyword("AS ");
491 self.write_alias(alias, *alias_quote_style);
492 }
493 }
494 }
495 }
496
497 fn gen_table_source(&mut self, source: &TableSource) {
498 match source {
499 TableSource::Table(table_ref) => self.gen_table_ref(table_ref),
500 TableSource::Subquery {
501 query,
502 alias,
503 alias_quote_style,
504 } => {
505 self.write("(");
506 self.gen_statement(query);
507 self.write(")");
508 if let Some(alias) = alias {
509 self.write(" ");
510 if !self.omit_table_alias_as() {
511 self.write_keyword("AS ");
512 }
513 self.write_alias(alias, *alias_quote_style);
514 }
515 }
516 TableSource::TableFunction {
517 name,
518 args,
519 alias,
520 alias_quote_style,
521 } => {
522 self.write(name);
523 self.write("(");
524 self.gen_expr_list(args);
525 self.write(")");
526 if let Some(alias) = alias {
527 self.write(" ");
528 if !self.omit_table_alias_as() {
529 self.write_keyword("AS ");
530 }
531 self.write_alias(alias, *alias_quote_style);
532 }
533 }
534 TableSource::Lateral { source } => {
535 self.write_keyword("LATERAL ");
536 self.gen_table_source(source);
537 }
538 TableSource::Unnest {
539 expr,
540 alias,
541 alias_quote_style,
542 with_offset,
543 } => {
544 self.write_keyword("UNNEST(");
545 self.gen_expr(expr);
546 self.write(")");
547 if let Some(alias) = alias {
548 self.write(" ");
549 if !self.omit_table_alias_as() {
550 self.write_keyword("AS ");
551 }
552 self.write_quoted(alias, *alias_quote_style);
553 }
554 if *with_offset {
555 self.write(" ");
556 self.write_keyword("WITH OFFSET");
557 }
558 }
559 TableSource::Pivot {
560 source,
561 aggregate,
562 for_column,
563 in_values,
564 alias,
565 alias_quote_style,
566 } => {
567 self.gen_table_source(source);
568 self.write(" ");
569 self.write_keyword("PIVOT");
570 self.write(" (");
571 self.gen_expr(aggregate);
572 self.write(" ");
573 self.write_keyword("FOR ");
574 self.write(for_column);
575 self.write(" ");
576 self.write_keyword("IN ");
577 self.write("(");
578 self.gen_pivot_values(in_values);
579 self.write("))");
580 if let Some(alias) = alias {
581 self.write(" ");
582 if !self.omit_table_alias_as() {
583 self.write_keyword("AS ");
584 }
585 self.write_quoted(alias, *alias_quote_style);
586 }
587 }
588 TableSource::Unpivot {
589 source,
590 value_column,
591 for_column,
592 in_columns,
593 alias,
594 alias_quote_style,
595 } => {
596 self.gen_table_source(source);
597 self.write(" ");
598 self.write_keyword("UNPIVOT");
599 self.write(" (");
600 self.write(value_column);
601 self.write(" ");
602 self.write_keyword("FOR ");
603 self.write(for_column);
604 self.write(" ");
605 self.write_keyword("IN ");
606 self.write("(");
607 self.gen_pivot_values(in_columns);
608 self.write("))");
609 if let Some(alias) = alias {
610 self.write(" ");
611 if !self.omit_table_alias_as() {
612 self.write_keyword("AS ");
613 }
614 self.write_quoted(alias, *alias_quote_style);
615 }
616 }
617 }
618 }
619
620 fn gen_pivot_values(&mut self, values: &[PivotValue]) {
621 for (i, pv) in values.iter().enumerate() {
622 if i > 0 {
623 self.write(", ");
624 }
625 self.gen_expr(&pv.value);
626 if let Some(alias) = &pv.alias {
627 self.write(" ");
628 self.write_keyword("AS ");
629 self.write_alias(alias, pv.alias_quote_style);
630 }
631 }
632 }
633
634 fn omit_table_alias_as(&self) -> bool {
636 matches!(self.dialect, Some(Dialect::Oracle))
637 }
638
639 fn gen_table_ref(&mut self, table: &TableRef) {
640 if let Some(catalog) = &table.catalog {
641 self.write(catalog);
642 self.write(".");
643 }
644 if let Some(schema) = &table.schema {
645 self.write(schema);
646 self.write(".");
647 }
648 self.write_quoted(&table.name, table.name_quote_style);
649 if let Some(alias) = &table.alias {
650 self.write(" ");
651 if !self.omit_table_alias_as() {
652 self.write_keyword("AS ");
653 }
654 self.write_alias(alias, table.alias_quote_style);
655 }
656 }
657
658 fn gen_join(&mut self, join: &JoinClause) {
659 let join_kw = match join.join_type {
660 JoinType::Inner => "INNER JOIN",
661 JoinType::Left => "LEFT JOIN",
662 JoinType::Right => "RIGHT JOIN",
663 JoinType::Full => "FULL JOIN",
664 JoinType::Cross => "CROSS JOIN",
665 JoinType::Natural => "NATURAL JOIN",
666 JoinType::Lateral => "LATERAL JOIN",
667 };
668 self.sep();
669 self.write_keyword(join_kw);
670 if self.pretty {
671 self.indent_up();
672 self.newline();
673 self.gen_table_source(&join.table);
674 } else {
675 self.write(" ");
676 self.gen_table_source(&join.table);
677 }
678 if let Some(on) = &join.on {
679 if self.pretty {
680 self.newline();
681 } else {
682 self.write(" ");
683 }
684 self.write_keyword("ON ");
685 self.gen_expr(on);
686 }
687 if !join.using.is_empty() {
688 if self.pretty {
689 self.newline();
690 } else {
691 self.write(" ");
692 }
693 self.write_keyword("USING (");
694 self.write(&join.using.join(", "));
695 self.write(")");
696 }
697 if self.pretty {
698 self.indent_down();
699 }
700 }
701
702 fn gen_order_by_items_inline(&mut self, items: &[OrderByItem]) {
703 for (i, item) in items.iter().enumerate() {
704 if i > 0 {
705 self.write(", ");
706 }
707 self.gen_expr(&item.expr);
708 if !item.ascending {
709 self.write(" ");
710 self.write_keyword("DESC");
711 }
712 if let Some(nulls_first) = item.nulls_first {
713 if nulls_first {
714 self.write(" ");
715 self.write_keyword("NULLS FIRST");
716 } else {
717 self.write(" ");
718 self.write_keyword("NULLS LAST");
719 }
720 }
721 }
722 }
723
724 fn gen_order_by(&mut self, items: &[OrderByItem]) {
725 if items.is_empty() {
726 return;
727 }
728 self.sep();
729 self.write_keyword("ORDER BY");
730 if self.pretty {
731 self.indent_up();
732 self.newline();
733 } else {
734 self.write(" ");
735 }
736 for (i, item) in items.iter().enumerate() {
737 if i > 0 {
738 self.write(", ");
739 }
740 self.gen_expr(&item.expr);
741 if !item.ascending {
742 self.write(" ");
743 self.write_keyword("DESC");
744 }
745 if let Some(nulls_first) = item.nulls_first {
746 if nulls_first {
747 self.write(" ");
748 self.write_keyword("NULLS FIRST");
749 } else {
750 self.write(" ");
751 self.write_keyword("NULLS LAST");
752 }
753 }
754 }
755 if self.pretty {
756 self.indent_down();
757 }
758 }
759
760 fn gen_set_operation(&mut self, sop: &SetOperationStatement) {
763 self.gen_statement(&sop.left);
764 let op_kw = match sop.op {
765 SetOperationType::Union => "UNION",
766 SetOperationType::Intersect => "INTERSECT",
767 SetOperationType::Except => "EXCEPT",
768 };
769 self.sep();
770 self.write_keyword(op_kw);
771 if sop.all {
772 self.write(" ");
773 self.write_keyword("ALL");
774 }
775 self.sep();
776 self.gen_statement(&sop.right);
777
778 self.gen_order_by(&sop.order_by);
779
780 if let Some(limit) = &sop.limit {
781 self.sep();
782 self.write_keyword("LIMIT ");
783 self.gen_expr(limit);
784 }
785 if let Some(offset) = &sop.offset {
786 self.sep();
787 self.write_keyword("OFFSET ");
788 self.gen_expr(offset);
789 }
790 }
791
792 fn gen_insert(&mut self, ins: &InsertStatement) {
795 self.write_keyword("INSERT INTO ");
796 self.gen_table_ref(&ins.table);
797
798 if !ins.columns.is_empty() {
799 self.write(" (");
800 self.write(&ins.columns.join(", "));
801 self.write(")");
802 }
803
804 if matches!(self.dialect, Some(Dialect::Tsql) | Some(Dialect::Fabric))
806 && !ins.returning.is_empty()
807 {
808 self.sep();
809 self.gen_output_clause(&ins.returning, "INSERTED");
810 }
811
812 match &ins.source {
813 InsertSource::Values(rows) => {
814 self.sep();
815 self.write_keyword("VALUES");
816 if self.pretty {
817 self.indent_up();
818 for (i, row) in rows.iter().enumerate() {
819 self.newline();
820 self.write("(");
821 self.gen_expr_list(row);
822 self.write(")");
823 if i < rows.len() - 1 {
824 self.write(",");
825 }
826 }
827 self.indent_down();
828 } else {
829 self.write(" ");
830 for (i, row) in rows.iter().enumerate() {
831 if i > 0 {
832 self.write(", ");
833 }
834 self.write("(");
835 self.gen_expr_list(row);
836 self.write(")");
837 }
838 }
839 }
840 InsertSource::Query(query) => {
841 self.sep();
842 self.gen_statement(query);
843 }
844 InsertSource::Default => {
845 self.sep();
846 self.write_keyword("DEFAULT VALUES");
847 }
848 }
849
850 if let Some(on_conflict) = &ins.on_conflict {
851 self.sep();
852 self.write_keyword("ON CONFLICT");
853 if !on_conflict.columns.is_empty() {
854 self.write(" (");
855 self.write(&on_conflict.columns.join(", "));
856 self.write(")");
857 }
858 match &on_conflict.action {
859 ConflictAction::DoNothing => {
860 self.write(" ");
861 self.write_keyword("DO NOTHING");
862 }
863 ConflictAction::DoUpdate(assignments) => {
864 self.write(" ");
865 self.write_keyword("DO UPDATE SET ");
866 for (i, (col, val)) in assignments.iter().enumerate() {
867 if i > 0 {
868 self.write(", ");
869 }
870 self.write(col);
871 self.write(" = ");
872 self.gen_expr(val);
873 }
874 }
875 }
876 }
877
878 if !matches!(self.dialect, Some(Dialect::Tsql) | Some(Dialect::Fabric))
880 && !ins.returning.is_empty()
881 {
882 self.sep();
883 self.write_keyword("RETURNING ");
884 for (i, item) in ins.returning.iter().enumerate() {
885 if i > 0 {
886 self.write(", ");
887 }
888 self.gen_select_item(item);
889 }
890 }
891 }
892
893 fn gen_update(&mut self, upd: &UpdateStatement) {
896 self.write_keyword("UPDATE ");
897 self.gen_table_ref(&upd.table);
898 self.sep();
899 self.write_keyword("SET");
900
901 if self.pretty {
902 self.indent_up();
903 for (i, (col, val)) in upd.assignments.iter().enumerate() {
904 self.newline();
905 self.write(col);
906 self.write(" = ");
907 self.gen_expr(val);
908 if i < upd.assignments.len() - 1 {
909 self.write(",");
910 }
911 }
912 self.indent_down();
913 } else {
914 self.write(" ");
915 for (i, (col, val)) in upd.assignments.iter().enumerate() {
916 if i > 0 {
917 self.write(", ");
918 }
919 self.write(col);
920 self.write(" = ");
921 self.gen_expr(val);
922 }
923 }
924
925 if let Some(from) = &upd.from {
926 self.sep();
927 self.write_keyword("FROM ");
928 self.gen_table_source(&from.source);
929 }
930
931 if let Some(wh) = &upd.where_clause {
932 self.sep();
933 self.write_keyword("WHERE");
934 if self.pretty {
935 self.indent_up();
936 self.newline();
937 self.gen_expr(wh);
938 self.indent_down();
939 } else {
940 self.write(" ");
941 self.gen_expr(wh);
942 }
943 }
944
945 if !upd.returning.is_empty() {
946 self.sep();
947 if matches!(self.dialect, Some(Dialect::Tsql) | Some(Dialect::Fabric)) {
948 self.gen_output_clause(&upd.returning, "INSERTED");
949 } else {
950 self.write_keyword("RETURNING ");
951 for (i, item) in upd.returning.iter().enumerate() {
952 if i > 0 {
953 self.write(", ");
954 }
955 self.gen_select_item(item);
956 }
957 }
958 }
959 }
960
961 fn gen_delete(&mut self, del: &DeleteStatement) {
964 self.write_keyword("DELETE FROM ");
965 self.gen_table_ref(&del.table);
966
967 if let Some(using) = &del.using {
968 self.sep();
969 self.write_keyword("USING ");
970 self.gen_table_source(&using.source);
971 }
972
973 if !del.returning.is_empty()
975 && matches!(self.dialect, Some(Dialect::Tsql) | Some(Dialect::Fabric))
976 {
977 self.sep();
978 self.gen_output_clause(&del.returning, "DELETED");
979 }
980
981 if let Some(wh) = &del.where_clause {
982 self.sep();
983 self.write_keyword("WHERE");
984 if self.pretty {
985 self.indent_up();
986 self.newline();
987 self.gen_expr(wh);
988 self.indent_down();
989 } else {
990 self.write(" ");
991 self.gen_expr(wh);
992 }
993 }
994
995 if !del.returning.is_empty()
997 && !matches!(self.dialect, Some(Dialect::Tsql) | Some(Dialect::Fabric))
998 {
999 self.sep();
1000 self.write_keyword("RETURNING ");
1001 for (i, item) in del.returning.iter().enumerate() {
1002 if i > 0 {
1003 self.write(", ");
1004 }
1005 self.gen_select_item(item);
1006 }
1007 }
1008 }
1009
1010 fn gen_output_clause(&mut self, items: &[SelectItem], prefix: &str) {
1014 self.write_keyword("OUTPUT ");
1015 for (i, item) in items.iter().enumerate() {
1016 if i > 0 {
1017 self.write(", ");
1018 }
1019 match item {
1020 SelectItem::Wildcard => {
1021 self.write(prefix);
1022 self.write(".*");
1023 }
1024 SelectItem::QualifiedWildcard { table } => {
1025 self.write(prefix);
1026 self.write(".");
1027 self.write(table);
1028 self.write(".*");
1029 }
1030 SelectItem::Expr { expr, .. } => match expr {
1031 Expr::Column { name, .. } => {
1032 self.write(prefix);
1033 self.write(".");
1034 self.write(name);
1035 }
1036 Expr::Star | Expr::Wildcard => {
1037 self.write(prefix);
1038 self.write(".*");
1039 }
1040 _ => {
1041 self.write(prefix);
1042 self.write(".");
1043 self.gen_expr(expr);
1044 }
1045 },
1046 }
1047 }
1048 }
1049
1050 fn gen_merge(&mut self, merge: &MergeStatement) {
1053 self.write_keyword("MERGE INTO ");
1054 self.gen_table_ref(&merge.target);
1055
1056 self.sep();
1057 self.write_keyword("USING ");
1058 self.gen_table_source(&merge.source);
1059
1060 self.sep();
1061 self.write_keyword("ON");
1062 if self.pretty {
1063 self.indent_up();
1064 self.newline();
1065 self.gen_expr(&merge.on);
1066 self.indent_down();
1067 } else {
1068 self.write(" ");
1069 self.gen_expr(&merge.on);
1070 }
1071
1072 for clause in &merge.clauses {
1073 self.sep();
1074 self.gen_merge_clause(clause);
1075 }
1076
1077 if !merge.output.is_empty() {
1078 self.sep();
1079 self.write_keyword("OUTPUT ");
1080 for (i, item) in merge.output.iter().enumerate() {
1081 if i > 0 {
1082 self.write(", ");
1083 }
1084 self.gen_select_item(item);
1085 }
1086 }
1087 }
1088
1089 fn gen_merge_clause(&mut self, clause: &MergeClause) {
1090 self.write_keyword("WHEN ");
1091 match &clause.kind {
1092 MergeClauseKind::Matched => self.write_keyword("MATCHED"),
1093 MergeClauseKind::NotMatched => self.write_keyword("NOT MATCHED"),
1094 MergeClauseKind::NotMatchedBySource => self.write_keyword("NOT MATCHED BY SOURCE"),
1095 }
1096
1097 if let Some(cond) = &clause.condition {
1098 self.write_keyword(" AND ");
1099 self.gen_expr(cond);
1100 }
1101
1102 self.write_keyword(" THEN");
1103
1104 match &clause.action {
1105 MergeAction::Update(assignments) => {
1106 self.sep();
1107 self.write_keyword("UPDATE SET");
1108 if self.pretty {
1109 self.indent_up();
1110 for (i, (col, val)) in assignments.iter().enumerate() {
1111 self.newline();
1112 self.write(col);
1113 self.write(" = ");
1114 self.gen_expr(val);
1115 if i < assignments.len() - 1 {
1116 self.write(",");
1117 }
1118 }
1119 self.indent_down();
1120 } else {
1121 self.write(" ");
1122 for (i, (col, val)) in assignments.iter().enumerate() {
1123 if i > 0 {
1124 self.write(", ");
1125 }
1126 self.write(col);
1127 self.write(" = ");
1128 self.gen_expr(val);
1129 }
1130 }
1131 }
1132 MergeAction::Insert { columns, values } => {
1133 self.sep();
1134 self.write_keyword("INSERT");
1135 if !columns.is_empty() {
1136 self.write(" (");
1137 self.write(&columns.join(", "));
1138 self.write(")");
1139 }
1140 self.write_keyword(" VALUES");
1141 self.write(" (");
1142 for (i, val) in values.iter().enumerate() {
1143 if i > 0 {
1144 self.write(", ");
1145 }
1146 self.gen_expr(val);
1147 }
1148 self.write(")");
1149 }
1150 MergeAction::InsertRow => {
1151 self.sep();
1152 self.write_keyword("INSERT ROW");
1153 }
1154 MergeAction::Delete => {
1155 self.sep();
1156 self.write_keyword("DELETE");
1157 }
1158 }
1159 }
1160
1161 fn gen_create_table(&mut self, ct: &CreateTableStatement) {
1164 self.write_keyword("CREATE ");
1165 if ct.temporary {
1166 self.write_keyword("TEMPORARY ");
1167 }
1168 self.write_keyword("TABLE ");
1169 if ct.if_not_exists {
1170 self.write_keyword("IF NOT EXISTS ");
1171 }
1172 self.gen_table_ref(&ct.table);
1173
1174 if let Some(as_select) = &ct.as_select {
1175 self.write(" ");
1176 self.write_keyword("AS ");
1177 self.gen_statement(as_select);
1178 return;
1179 }
1180
1181 self.write(" (");
1182
1183 if self.pretty {
1184 self.indent_up();
1185 for (i, col) in ct.columns.iter().enumerate() {
1186 self.newline();
1187 self.gen_column_def(col);
1188 if i < ct.columns.len() - 1 || !ct.constraints.is_empty() {
1189 self.write(",");
1190 }
1191 }
1192 for (i, constraint) in ct.constraints.iter().enumerate() {
1193 self.newline();
1194 self.gen_table_constraint(constraint);
1195 if i < ct.constraints.len() - 1 {
1196 self.write(",");
1197 }
1198 }
1199 self.indent_down();
1200 self.newline();
1201 } else {
1202 for (i, col) in ct.columns.iter().enumerate() {
1203 if i > 0 {
1204 self.write(", ");
1205 }
1206 self.gen_column_def(col);
1207 }
1208 for (i, constraint) in ct.constraints.iter().enumerate() {
1209 if i + ct.columns.len() > 0 {
1210 self.write(", ");
1211 }
1212 self.gen_table_constraint(constraint);
1213 }
1214 }
1215
1216 self.write(")");
1217 }
1218
1219 fn gen_column_def(&mut self, col: &ColumnDef) {
1220 self.write(&col.name);
1221 self.write(" ");
1222 self.gen_data_type(&col.data_type);
1223
1224 if col.primary_key {
1225 self.write(" ");
1226 self.write_keyword("PRIMARY KEY");
1227 }
1228 if col.unique {
1229 self.write(" ");
1230 self.write_keyword("UNIQUE");
1231 }
1232 if col.auto_increment {
1233 self.write(" ");
1234 self.write_keyword("AUTOINCREMENT");
1235 }
1236
1237 match col.nullable {
1238 Some(false) => {
1239 self.write(" ");
1240 self.write_keyword("NOT NULL");
1241 }
1242 Some(true) => {
1243 self.write(" ");
1244 self.write_keyword("NULL");
1245 }
1246 None => {}
1247 }
1248
1249 if let Some(default) = &col.default {
1250 self.write(" ");
1251 self.write_keyword("DEFAULT ");
1252 self.gen_expr(default);
1253 }
1254
1255 if let Some(collation) = &col.collation {
1256 self.write(" ");
1257 self.write_keyword("COLLATE ");
1258 self.write(collation);
1259 }
1260
1261 if let Some(comment) = &col.comment {
1262 self.write(" ");
1263 self.write_keyword("COMMENT '");
1264 self.write(&comment.replace('\'', "''"));
1265 self.write("'");
1266 }
1267 }
1268
1269 fn gen_table_constraint(&mut self, constraint: &TableConstraint) {
1270 match constraint {
1271 TableConstraint::PrimaryKey { name, columns } => {
1272 if let Some(name) = name {
1273 self.write_keyword("CONSTRAINT ");
1274 self.write(name);
1275 self.write(" ");
1276 }
1277 self.write_keyword("PRIMARY KEY (");
1278 self.write(&columns.join(", "));
1279 self.write(")");
1280 }
1281 TableConstraint::Unique { name, columns } => {
1282 if let Some(name) = name {
1283 self.write_keyword("CONSTRAINT ");
1284 self.write(name);
1285 self.write(" ");
1286 }
1287 self.write_keyword("UNIQUE (");
1288 self.write(&columns.join(", "));
1289 self.write(")");
1290 }
1291 TableConstraint::ForeignKey {
1292 name,
1293 columns,
1294 ref_table,
1295 ref_columns,
1296 on_delete,
1297 on_update,
1298 } => {
1299 if let Some(name) = name {
1300 self.write_keyword("CONSTRAINT ");
1301 self.write(name);
1302 self.write(" ");
1303 }
1304 self.write_keyword("FOREIGN KEY (");
1305 self.write(&columns.join(", "));
1306 self.write(") ");
1307 self.write_keyword("REFERENCES ");
1308 self.gen_table_ref(ref_table);
1309 self.write(" (");
1310 self.write(&ref_columns.join(", "));
1311 self.write(")");
1312 if let Some(action) = on_delete {
1313 self.write(" ");
1314 self.write_keyword("ON DELETE ");
1315 self.gen_referential_action(action);
1316 }
1317 if let Some(action) = on_update {
1318 self.write(" ");
1319 self.write_keyword("ON UPDATE ");
1320 self.gen_referential_action(action);
1321 }
1322 }
1323 TableConstraint::Check { name, expr } => {
1324 if let Some(name) = name {
1325 self.write_keyword("CONSTRAINT ");
1326 self.write(name);
1327 self.write(" ");
1328 }
1329 self.write_keyword("CHECK (");
1330 self.gen_expr(expr);
1331 self.write(")");
1332 }
1333 }
1334 }
1335
1336 fn gen_referential_action(&mut self, action: &ReferentialAction) {
1337 match action {
1338 ReferentialAction::Cascade => self.write_keyword("CASCADE"),
1339 ReferentialAction::Restrict => self.write_keyword("RESTRICT"),
1340 ReferentialAction::NoAction => self.write_keyword("NO ACTION"),
1341 ReferentialAction::SetNull => self.write_keyword("SET NULL"),
1342 ReferentialAction::SetDefault => self.write_keyword("SET DEFAULT"),
1343 }
1344 }
1345
1346 fn gen_drop_table(&mut self, dt: &DropTableStatement) {
1349 self.write_keyword("DROP TABLE ");
1350 if dt.if_exists {
1351 self.write_keyword("IF EXISTS ");
1352 }
1353 self.gen_table_ref(&dt.table);
1354 if dt.cascade {
1355 self.write(" ");
1356 self.write_keyword("CASCADE");
1357 }
1358 }
1359
1360 fn gen_alter_table(&mut self, alt: &AlterTableStatement) {
1363 self.write_keyword("ALTER TABLE ");
1364 self.gen_table_ref(&alt.table);
1365
1366 for (i, action) in alt.actions.iter().enumerate() {
1367 if i > 0 {
1368 self.write(",");
1369 }
1370 self.write(" ");
1371 match action {
1372 AlterTableAction::AddColumn(col) => {
1373 self.write_keyword("ADD COLUMN ");
1374 self.gen_column_def(col);
1375 }
1376 AlterTableAction::DropColumn { name, if_exists } => {
1377 self.write_keyword("DROP COLUMN ");
1378 if *if_exists {
1379 self.write_keyword("IF EXISTS ");
1380 }
1381 self.write(name);
1382 }
1383 AlterTableAction::RenameColumn { old_name, new_name } => {
1384 self.write_keyword("RENAME COLUMN ");
1385 self.write(old_name);
1386 self.write(" ");
1387 self.write_keyword("TO ");
1388 self.write(new_name);
1389 }
1390 AlterTableAction::AlterColumnType { name, data_type } => {
1391 self.write_keyword("ALTER COLUMN ");
1392 self.write(name);
1393 self.write(" ");
1394 self.write_keyword("TYPE ");
1395 self.gen_data_type(data_type);
1396 }
1397 AlterTableAction::AddConstraint(constraint) => {
1398 self.write_keyword("ADD ");
1399 self.gen_table_constraint(constraint);
1400 }
1401 AlterTableAction::DropConstraint { name } => {
1402 self.write_keyword("DROP CONSTRAINT ");
1403 self.write(name);
1404 }
1405 AlterTableAction::RenameTable { new_name } => {
1406 self.write_keyword("RENAME TO ");
1407 self.write(new_name);
1408 }
1409 }
1410 }
1411 }
1412
1413 fn gen_create_view(&mut self, cv: &CreateViewStatement) {
1416 self.write_keyword("CREATE ");
1417 if cv.or_replace {
1418 self.write_keyword("OR REPLACE ");
1419 }
1420 if cv.materialized {
1421 self.write_keyword("MATERIALIZED ");
1422 }
1423 self.write_keyword("VIEW ");
1424 if cv.if_not_exists {
1425 self.write_keyword("IF NOT EXISTS ");
1426 }
1427 self.gen_table_ref(&cv.name);
1428
1429 if !cv.columns.is_empty() {
1430 self.write(" (");
1431 self.write(&cv.columns.join(", "));
1432 self.write(")");
1433 }
1434
1435 self.write(" ");
1436 self.write_keyword("AS ");
1437 self.gen_statement(&cv.query);
1438 }
1439
1440 fn gen_drop_view(&mut self, dv: &DropViewStatement) {
1441 self.write_keyword("DROP ");
1442 if dv.materialized {
1443 self.write_keyword("MATERIALIZED ");
1444 }
1445 self.write_keyword("VIEW ");
1446 if dv.if_exists {
1447 self.write_keyword("IF EXISTS ");
1448 }
1449 self.gen_table_ref(&dv.name);
1450 }
1451
1452 fn gen_truncate(&mut self, t: &TruncateStatement) {
1455 self.write_keyword("TRUNCATE TABLE ");
1456 self.gen_table_ref(&t.table);
1457 }
1458
1459 fn gen_transaction(&mut self, t: &TransactionStatement) {
1462 match t {
1463 TransactionStatement::Begin => self.write_keyword("BEGIN"),
1464 TransactionStatement::Commit => self.write_keyword("COMMIT"),
1465 TransactionStatement::Rollback => self.write_keyword("ROLLBACK"),
1466 TransactionStatement::Savepoint(name) => {
1467 self.write_keyword("SAVEPOINT ");
1468 self.write(name);
1469 }
1470 TransactionStatement::ReleaseSavepoint(name) => {
1471 self.write_keyword("RELEASE SAVEPOINT ");
1472 self.write(name);
1473 }
1474 TransactionStatement::RollbackTo(name) => {
1475 self.write_keyword("ROLLBACK TO SAVEPOINT ");
1476 self.write(name);
1477 }
1478 }
1479 }
1480
1481 fn gen_explain(&mut self, e: &ExplainStatement) {
1484 self.write_keyword("EXPLAIN ");
1485 if e.analyze {
1486 self.write_keyword("ANALYZE ");
1487 }
1488 self.gen_statement(&e.statement);
1489 }
1490
1491 fn gen_use(&mut self, u: &UseStatement) {
1494 self.write_keyword("USE ");
1495 self.write(&u.name);
1496 }
1497
1498 fn gen_data_type(&mut self, dt: &DataType) {
1503 match dt {
1504 DataType::TinyInt => self.write("TINYINT"),
1505 DataType::SmallInt => self.write("SMALLINT"),
1506 DataType::Int => self.write("INT"),
1507 DataType::BigInt => self.write("BIGINT"),
1508 DataType::Float => self.write("FLOAT"),
1509 DataType::Double => self.write("DOUBLE"),
1510 DataType::Real => self.write("REAL"),
1511 DataType::Decimal { precision, scale } | DataType::Numeric { precision, scale } => {
1512 self.write(if matches!(dt, DataType::Numeric { .. }) {
1513 "NUMERIC"
1514 } else {
1515 "DECIMAL"
1516 });
1517 if let Some(p) = precision {
1518 self.write(&format!("({p}"));
1519 if let Some(s) = scale {
1520 self.write(&format!(", {s}"));
1521 }
1522 self.write(")");
1523 }
1524 }
1525 DataType::Varchar(len) => {
1526 self.write("VARCHAR");
1527 if let Some(n) = len {
1528 self.write(&format!("({n})"));
1529 }
1530 }
1531 DataType::Char(len) => {
1532 self.write("CHAR");
1533 if let Some(n) = len {
1534 self.write(&format!("({n})"));
1535 }
1536 }
1537 DataType::Text => self.write("TEXT"),
1538 DataType::String => self.write("STRING"),
1539 DataType::Binary(len) => {
1540 self.write("BINARY");
1541 if let Some(n) = len {
1542 self.write(&format!("({n})"));
1543 }
1544 }
1545 DataType::Varbinary(len) => {
1546 self.write("VARBINARY");
1547 match len {
1548 Some(n) => self.write(&format!("({n})")),
1549 None if matches!(self.dialect, Some(Dialect::Tsql) | Some(Dialect::Fabric)) => {
1550 self.write("(MAX)");
1551 }
1552 None => {}
1553 }
1554 }
1555 DataType::Boolean => self.write("BOOLEAN"),
1556 DataType::Date => self.write("DATE"),
1557 DataType::Time { precision } => {
1558 self.write("TIME");
1559 if let Some(p) = precision {
1560 self.write(&format!("({p})"));
1561 }
1562 }
1563 DataType::Timestamp { precision, with_tz } => {
1564 self.write("TIMESTAMP");
1565 if let Some(p) = precision {
1566 self.write(&format!("({p})"));
1567 }
1568 if *with_tz {
1569 self.write(" WITH TIME ZONE");
1570 }
1571 }
1572 DataType::Interval => self.write("INTERVAL"),
1573 DataType::DateTime => self.write("DATETIME"),
1574 DataType::Blob => self.write("BLOB"),
1575 DataType::Bytea => self.write("BYTEA"),
1576 DataType::Bytes => self.write("BYTES"),
1577 DataType::Json => self.write("JSON"),
1578 DataType::Jsonb => self.write("JSONB"),
1579 DataType::Uuid => self.write("UUID"),
1580 DataType::Array(inner) => {
1581 let is_postgres = matches!(
1582 self.dialect,
1583 Some(
1584 Dialect::Postgres
1585 | Dialect::Redshift
1586 | Dialect::Materialize
1587 | Dialect::RisingWave
1588 )
1589 );
1590 if is_postgres {
1591 if let Some(inner) = inner {
1593 self.gen_data_type(inner);
1594 self.write("[]");
1595 } else {
1596 self.write("ARRAY");
1597 }
1598 } else {
1599 self.write("ARRAY");
1600 if let Some(inner) = inner {
1601 self.write("<");
1602 self.gen_data_type(inner);
1603 self.write(">");
1604 }
1605 }
1606 }
1607 DataType::Map { key, value } => {
1608 self.write("MAP<");
1609 self.gen_data_type(key);
1610 self.write(", ");
1611 self.gen_data_type(value);
1612 self.write(">");
1613 }
1614 DataType::Struct(fields) => {
1615 self.write("STRUCT<");
1616 for (i, (name, dt)) in fields.iter().enumerate() {
1617 if i > 0 {
1618 self.write(", ");
1619 }
1620 self.write(name);
1621 self.write(" ");
1622 self.gen_data_type(dt);
1623 }
1624 self.write(">");
1625 }
1626 DataType::Tuple(types) => {
1627 self.write("TUPLE(");
1628 for (i, dt) in types.iter().enumerate() {
1629 if i > 0 {
1630 self.write(", ");
1631 }
1632 self.gen_data_type(dt);
1633 }
1634 self.write(")");
1635 }
1636 DataType::Null => self.write("NULL"),
1637 DataType::Variant => self.write("VARIANT"),
1638 DataType::Object => self.write("OBJECT"),
1639 DataType::Xml => self.write("XML"),
1640 DataType::Inet => self.write("INET"),
1641 DataType::Cidr => self.write("CIDR"),
1642 DataType::Macaddr => self.write("MACADDR"),
1643 DataType::Bit(len) => {
1644 self.write("BIT");
1645 if let Some(n) = len {
1646 self.write(&format!("({n})"));
1647 }
1648 }
1649 DataType::Money => self.write("MONEY"),
1650 DataType::Serial => self.write("SERIAL"),
1651 DataType::BigSerial => self.write("BIGSERIAL"),
1652 DataType::SmallSerial => self.write("SMALLSERIAL"),
1653 DataType::Regclass => self.write("REGCLASS"),
1654 DataType::Regtype => self.write("REGTYPE"),
1655 DataType::Hstore => self.write("HSTORE"),
1656 DataType::Geography => self.write("GEOGRAPHY"),
1657 DataType::Geometry => self.write("GEOMETRY"),
1658 DataType::Super => self.write("SUPER"),
1659 DataType::Unknown(name) => self.write(name),
1660 }
1661 }
1662
1663 fn binary_op_str(op: &BinaryOperator) -> &'static str {
1668 match op {
1669 BinaryOperator::Plus => " + ",
1670 BinaryOperator::Minus => " - ",
1671 BinaryOperator::Multiply => " * ",
1672 BinaryOperator::Divide => " / ",
1673 BinaryOperator::Modulo => " % ",
1674 BinaryOperator::Eq => " = ",
1675 BinaryOperator::Neq => " <> ",
1676 BinaryOperator::Lt => " < ",
1677 BinaryOperator::Gt => " > ",
1678 BinaryOperator::LtEq => " <= ",
1679 BinaryOperator::GtEq => " >= ",
1680 BinaryOperator::And => " AND ",
1681 BinaryOperator::Or => " OR ",
1682 BinaryOperator::Xor => " XOR ",
1683 BinaryOperator::Concat => " || ",
1684 BinaryOperator::BitwiseAnd => " & ",
1685 BinaryOperator::BitwiseOr => " | ",
1686 BinaryOperator::BitwiseXor => " ^ ",
1687 BinaryOperator::ShiftLeft => " << ",
1688 BinaryOperator::ShiftRight => " >> ",
1689 BinaryOperator::Arrow => " -> ",
1690 BinaryOperator::DoubleArrow => " ->> ",
1691 BinaryOperator::AtArrow => " @> ",
1692 BinaryOperator::ArrowAt => " <@ ",
1693 }
1694 }
1695
1696 fn gen_expr_list(&mut self, exprs: &[Expr]) {
1697 for (i, expr) in exprs.iter().enumerate() {
1698 if i > 0 {
1699 self.write(", ");
1700 }
1701 self.gen_expr(expr);
1702 }
1703 }
1704
1705 fn gen_expr(&mut self, expr: &Expr) {
1706 match expr {
1707 Expr::Column {
1708 table,
1709 name,
1710 quote_style,
1711 table_quote_style,
1712 } => {
1713 if let Some(t) = table {
1714 self.write_quoted(t, *table_quote_style);
1715 self.write(".");
1716 }
1717 self.write_quoted(name, *quote_style);
1718 }
1719 Expr::Number(n) => self.write(n),
1720 Expr::StringLiteral(s) => {
1721 if matches!(self.dialect, Some(Dialect::Oracle) | Some(Dialect::Tsql))
1724 && !s.is_ascii()
1725 {
1726 self.write("N'");
1727 } else {
1728 self.write("'");
1729 }
1730 self.write(&s.replace('\'', "''"));
1731 self.write("'");
1732 }
1733 Expr::NationalStringLiteral(s) => {
1734 if matches!(self.dialect, Some(Dialect::Oracle) | Some(Dialect::Tsql)) {
1735 self.write("N'");
1736 } else {
1737 self.write("'");
1738 }
1739 self.write(&s.replace('\'', "''"));
1740 self.write("'");
1741 }
1742 Expr::Boolean(b) => {
1743 if matches!(self.dialect, Some(Dialect::Tsql) | Some(Dialect::Fabric)) {
1744 self.write(if *b { "1" } else { "0" });
1745 } else {
1746 self.write(if *b { "TRUE" } else { "FALSE" });
1747 }
1748 }
1749 Expr::Null => self.write("NULL"),
1750 Expr::Default => self.write_keyword("DEFAULT"),
1751 Expr::Wildcard | Expr::Star => self.write("*"),
1752
1753 Expr::Cube { exprs } => {
1754 self.write_keyword("CUBE");
1755 self.write("(");
1756 self.gen_expr_list(exprs);
1757 self.write(")");
1758 }
1759 Expr::Rollup { exprs } => {
1760 self.write_keyword("ROLLUP");
1761 self.write("(");
1762 self.gen_expr_list(exprs);
1763 self.write(")");
1764 }
1765 Expr::GroupingSets { sets } => {
1766 self.write_keyword("GROUPING SETS");
1767 self.write("(");
1768 self.gen_expr_list(sets);
1769 self.write(")");
1770 }
1771
1772 Expr::BinaryOp { left, op, right } => {
1773 self.gen_expr(left);
1774 self.write(Self::binary_op_str(op));
1775 self.gen_expr(right);
1776 }
1777 Expr::AnyOp { expr, op, right } => {
1778 self.gen_expr(expr);
1779 self.write(Self::binary_op_str(op));
1780 self.write_keyword("ANY");
1781 self.write("(");
1782 if let Expr::Subquery(query) = right.as_ref() {
1783 self.gen_statement(query);
1784 } else {
1785 self.gen_expr(right);
1786 }
1787 self.write(")");
1788 }
1789 Expr::AllOp { expr, op, right } => {
1790 self.gen_expr(expr);
1791 self.write(Self::binary_op_str(op));
1792 self.write_keyword("ALL");
1793 self.write("(");
1794 if let Expr::Subquery(query) = right.as_ref() {
1795 self.gen_statement(query);
1796 } else {
1797 self.gen_expr(right);
1798 }
1799 self.write(")");
1800 }
1801 Expr::UnaryOp { op, expr } => {
1802 let op_str = match op {
1803 UnaryOperator::Not => "NOT ",
1804 UnaryOperator::Minus => "-",
1805 UnaryOperator::Plus => "+",
1806 UnaryOperator::BitwiseNot => "~",
1807 };
1808 self.write(op_str);
1809 self.gen_expr(expr);
1810 }
1811 Expr::Function {
1812 name,
1813 args,
1814 distinct,
1815 filter,
1816 over,
1817 order_by,
1818 within_group,
1819 } => {
1820 self.write(name);
1821 self.write("(");
1822 if *distinct {
1823 self.write_keyword("DISTINCT ");
1824 }
1825 self.gen_expr_list(args);
1826 if !*within_group && !order_by.is_empty() {
1828 self.write(" ");
1829 self.write_keyword("ORDER BY ");
1830 self.gen_order_by_items_inline(order_by);
1831 }
1832 self.write(")");
1833
1834 if *within_group && !order_by.is_empty() {
1836 self.write(" ");
1837 self.write_keyword("WITHIN GROUP (ORDER BY ");
1838 self.gen_order_by_items_inline(order_by);
1839 self.write(")");
1840 }
1841
1842 if let Some(filter_expr) = filter {
1843 self.write(" ");
1844 self.write_keyword("FILTER (WHERE ");
1845 self.gen_expr(filter_expr);
1846 self.write(")");
1847 }
1848 if let Some(spec) = over {
1849 self.write(" ");
1850 self.write_keyword("OVER ");
1851 if let Some(wref) = &spec.window_ref {
1852 if spec.partition_by.is_empty()
1853 && spec.order_by.is_empty()
1854 && spec.frame.is_none()
1855 {
1856 self.write(wref);
1857 } else {
1858 self.write("(");
1859 self.gen_window_spec(spec);
1860 self.write(")");
1861 }
1862 } else {
1863 self.write("(");
1864 self.gen_window_spec(spec);
1865 self.write(")");
1866 }
1867 }
1868 }
1869 Expr::Between {
1870 expr,
1871 low,
1872 high,
1873 negated,
1874 } => {
1875 self.gen_expr(expr);
1876 if *negated {
1877 self.write(" ");
1878 self.write_keyword("NOT");
1879 }
1880 self.write(" ");
1881 self.write_keyword("BETWEEN ");
1882 self.gen_expr(low);
1883 self.write(" ");
1884 self.write_keyword("AND ");
1885 self.gen_expr(high);
1886 }
1887 Expr::InList {
1888 expr,
1889 list,
1890 negated,
1891 } => {
1892 self.gen_expr(expr);
1893 if *negated {
1894 self.write(" ");
1895 self.write_keyword("NOT");
1896 }
1897 self.write(" ");
1898 self.write_keyword("IN (");
1899 self.gen_expr_list(list);
1900 self.write(")");
1901 }
1902 Expr::InSubquery {
1903 expr,
1904 subquery,
1905 negated,
1906 } => {
1907 self.gen_expr(expr);
1908 if *negated {
1909 self.write(" ");
1910 self.write_keyword("NOT");
1911 }
1912 self.write(" ");
1913 self.write_keyword("IN (");
1914 self.gen_statement(subquery);
1915 self.write(")");
1916 }
1917 Expr::IsNull { expr, negated } => {
1918 self.gen_expr(expr);
1919 if *negated {
1920 self.write(" ");
1921 self.write_keyword("IS NOT NULL");
1922 } else {
1923 self.write(" ");
1924 self.write_keyword("IS NULL");
1925 }
1926 }
1927 Expr::IsBool {
1928 expr,
1929 value,
1930 negated,
1931 } => {
1932 self.gen_expr(expr);
1933 self.write(" ");
1934 match (negated, value) {
1935 (false, true) => self.write_keyword("IS TRUE"),
1936 (false, false) => self.write_keyword("IS FALSE"),
1937 (true, true) => self.write_keyword("IS NOT TRUE"),
1938 (true, false) => self.write_keyword("IS NOT FALSE"),
1939 }
1940 }
1941 Expr::Like {
1942 expr,
1943 pattern,
1944 negated,
1945 escape,
1946 } => {
1947 self.gen_expr(expr);
1948 if *negated {
1949 self.write(" ");
1950 self.write_keyword("NOT");
1951 }
1952 self.write(" ");
1953 self.write_keyword("LIKE ");
1954 self.gen_expr(pattern);
1955 if let Some(esc) = escape {
1956 self.write(" ");
1957 self.write_keyword("ESCAPE ");
1958 self.gen_expr(esc);
1959 }
1960 }
1961 Expr::ILike {
1962 expr,
1963 pattern,
1964 negated,
1965 escape,
1966 } => {
1967 self.gen_expr(expr);
1968 if *negated {
1969 self.write(" ");
1970 self.write_keyword("NOT");
1971 }
1972 self.write(" ");
1973 self.write_keyword("ILIKE ");
1974 self.gen_expr(pattern);
1975 if let Some(esc) = escape {
1976 self.write(" ");
1977 self.write_keyword("ESCAPE ");
1978 self.gen_expr(esc);
1979 }
1980 }
1981 Expr::SimilarTo {
1982 expr,
1983 pattern,
1984 negated,
1985 escape,
1986 } => {
1987 self.gen_expr(expr);
1988 if *negated {
1989 self.write(" ");
1990 self.write_keyword("NOT");
1991 }
1992 self.write(" ");
1993 self.write_keyword("SIMILAR TO ");
1994 self.gen_expr(pattern);
1995 if let Some(esc) = escape {
1996 self.write(" ");
1997 self.write_keyword("ESCAPE ");
1998 self.gen_expr(esc);
1999 }
2000 }
2001 Expr::Case {
2002 operand,
2003 when_clauses,
2004 else_clause,
2005 } => {
2006 self.write_keyword("CASE");
2007 if let Some(op) = operand {
2008 self.write(" ");
2009 self.gen_expr(op);
2010 }
2011 for (cond, result) in when_clauses {
2012 self.write(" ");
2013 self.write_keyword("WHEN ");
2014 self.gen_expr(cond);
2015 self.write(" ");
2016 self.write_keyword("THEN ");
2017 self.gen_expr(result);
2018 }
2019 if let Some(el) = else_clause {
2020 self.write(" ");
2021 self.write_keyword("ELSE ");
2022 self.gen_expr(el);
2023 }
2024 self.write(" ");
2025 self.write_keyword("END");
2026 }
2027 Expr::Nested(inner) => {
2028 self.write("(");
2029 self.gen_expr(inner);
2030 self.write(")");
2031 }
2032 Expr::Subquery(query) => {
2033 self.write("(");
2034 self.gen_statement(query);
2035 self.write(")");
2036 }
2037 Expr::Exists { subquery, negated } => {
2038 if *negated {
2039 self.write_keyword("NOT ");
2040 }
2041 self.write_keyword("EXISTS (");
2042 self.gen_statement(subquery);
2043 self.write(")");
2044 }
2045 Expr::Cast { expr, data_type } => {
2046 if let Expr::StringLiteral(val) = expr.as_ref() {
2048 let ansi_keyword = match data_type {
2049 DataType::Date => Some("DATE"),
2050 DataType::Timestamp { .. } => Some("TIMESTAMP"),
2051 DataType::Time { .. } => Some("TIME"),
2052 _ => None,
2053 };
2054 if let Some(kw) = ansi_keyword {
2055 let ansi_typed_literal_unsupported = matches!(
2062 self.dialect,
2063 Some(
2064 Dialect::Mysql
2065 | Dialect::Doris
2066 | Dialect::SingleStore
2067 | Dialect::StarRocks
2068 | Dialect::Tsql
2069 | Dialect::Fabric
2070 )
2071 );
2072 if !ansi_typed_literal_unsupported {
2073 self.write_keyword(kw);
2074 self.write(" '");
2075 self.write(val);
2076 self.write("'");
2077 return;
2078 }
2079 }
2080 }
2081
2082 let is_postgres = matches!(
2083 self.dialect,
2084 Some(
2085 Dialect::Postgres
2086 | Dialect::Redshift
2087 | Dialect::Materialize
2088 | Dialect::RisingWave
2089 )
2090 );
2091 if is_postgres {
2092 self.gen_expr(expr);
2093 self.write("::");
2094 self.gen_data_type(data_type);
2095 } else {
2096 self.write_keyword("CAST(");
2097 self.gen_expr(expr);
2098 self.write(" ");
2099 self.write_keyword("AS ");
2100 self.gen_data_type(data_type);
2101 self.write(")");
2102 }
2103 }
2104 Expr::TryCast { expr, data_type } => {
2105 self.write_keyword("TRY_CAST(");
2106 self.gen_expr(expr);
2107 self.write(" ");
2108 self.write_keyword("AS ");
2109 self.gen_data_type(data_type);
2110 self.write(")");
2111 }
2112 Expr::Extract { field, expr } => {
2113 if matches!(self.dialect, Some(Dialect::Tsql) | Some(Dialect::Fabric)) {
2114 match field {
2115 DateTimeField::Epoch => {
2116 self.write_keyword("DATEDIFF(SECOND, '1970-01-01', ");
2118 self.gen_expr(expr);
2119 self.write(")");
2120 }
2121 DateTimeField::DayOfWeek => {
2122 self.write_keyword("(DATEPART(WEEKDAY, ");
2127 self.gen_expr(expr);
2128 self.write_keyword(") + @@DATEFIRST - 1) % 7");
2129 }
2130 _ => {
2131 self.write_keyword("DATEPART(");
2132 match field {
2133 DateTimeField::DayOfYear => self.write("DAYOFYEAR"),
2135 DateTimeField::Week => self.write("ISO_WEEK"),
2137 _ => self.gen_datetime_field(field),
2143 }
2144 self.write(", ");
2145 self.gen_expr(expr);
2146 self.write(")");
2147 }
2148 }
2149 } else {
2150 self.write_keyword("EXTRACT(");
2151 self.gen_datetime_field(field);
2152 self.write(" ");
2153 self.write_keyword("FROM ");
2154 self.gen_expr(expr);
2155 self.write(")");
2156 }
2157 }
2158 Expr::Interval { value, unit } => {
2159 self.write_keyword("INTERVAL ");
2160 self.gen_expr(value);
2161 if let Some(unit) = unit {
2162 self.write(" ");
2163 self.gen_datetime_field(unit);
2164 }
2165 }
2166 Expr::ArrayLiteral(items) => {
2167 self.write_keyword("ARRAY[");
2168 self.gen_expr_list(items);
2169 self.write("]");
2170 }
2171 Expr::Tuple(items) => {
2172 self.write("(");
2173 self.gen_expr_list(items);
2174 self.write(")");
2175 }
2176 Expr::Coalesce(items) => {
2177 self.write_keyword("COALESCE(");
2178 self.gen_expr_list(items);
2179 self.write(")");
2180 }
2181 Expr::If {
2182 condition,
2183 true_val,
2184 false_val,
2185 } => {
2186 self.write_keyword("IF(");
2187 self.gen_expr(condition);
2188 self.write(", ");
2189 self.gen_expr(true_val);
2190 if let Some(fv) = false_val {
2191 self.write(", ");
2192 self.gen_expr(fv);
2193 }
2194 self.write(")");
2195 }
2196 Expr::NullIf { expr, r#else } => {
2197 self.write_keyword("NULLIF(");
2198 self.gen_expr(expr);
2199 self.write(", ");
2200 self.gen_expr(r#else);
2201 self.write(")");
2202 }
2203 Expr::Collate { expr, collation } => {
2204 self.gen_expr(expr);
2205 self.write(" ");
2206 self.write_keyword("COLLATE ");
2207 self.write(collation);
2208 }
2209 Expr::Parameter(p) => self.write(p),
2210 Expr::TypeExpr(dt) => self.gen_data_type(dt),
2211 Expr::QualifiedWildcard { table } => {
2212 self.write(table);
2213 self.write(".*");
2214 }
2215 Expr::Alias { expr, name } => {
2216 self.gen_expr(expr);
2217 self.write(" ");
2218 self.write_keyword("AS ");
2219 self.write(name);
2220 }
2221 Expr::ArrayIndex { expr, index } => {
2222 self.gen_expr(expr);
2223 self.write("[");
2224 self.gen_expr(index);
2225 self.write("]");
2226 }
2227 Expr::JsonAccess {
2228 expr,
2229 path,
2230 as_text,
2231 } => {
2232 self.gen_expr(expr);
2233 if *as_text {
2234 self.write("->>");
2235 } else {
2236 self.write("->");
2237 }
2238 self.gen_expr(path);
2239 }
2240 Expr::Lambda { params, body } => {
2241 if params.len() == 1 {
2242 self.write(¶ms[0]);
2243 } else {
2244 self.write("(");
2245 self.write(¶ms.join(", "));
2246 self.write(")");
2247 }
2248 self.write(" -> ");
2249 self.gen_expr(body);
2250 }
2251 Expr::TypedFunction { func, filter, over } => {
2252 self.gen_typed_function(func);
2253
2254 if let Some(filter_expr) = filter {
2255 self.write(" ");
2256 self.write_keyword("FILTER (WHERE ");
2257 self.gen_expr(filter_expr);
2258 self.write(")");
2259 }
2260 if let Some(spec) = over {
2261 self.write(" ");
2262 self.write_keyword("OVER ");
2263 if let Some(wref) = &spec.window_ref {
2264 if spec.partition_by.is_empty()
2265 && spec.order_by.is_empty()
2266 && spec.frame.is_none()
2267 {
2268 self.write(wref);
2269 } else {
2270 self.write("(");
2271 self.gen_window_spec(spec);
2272 self.write(")");
2273 }
2274 } else {
2275 self.write("(");
2276 self.gen_window_spec(spec);
2277 self.write(")");
2278 }
2279 }
2280 }
2281 Expr::Commented { expr, comments } => {
2282 for comment in comments {
2283 let normalized = self.normalize_comment(comment);
2284 self.write(&normalized);
2285 self.write(" ");
2286 }
2287 self.gen_expr(expr);
2288 }
2289 }
2290 }
2291
2292 fn gen_window_spec(&mut self, spec: &WindowSpec) {
2293 if let Some(wref) = &spec.window_ref {
2294 self.write(wref);
2295 if !spec.partition_by.is_empty() || !spec.order_by.is_empty() || spec.frame.is_some() {
2296 self.write(" ");
2297 }
2298 }
2299 if !spec.partition_by.is_empty() {
2300 self.write_keyword("PARTITION BY ");
2301 self.gen_expr_list(&spec.partition_by);
2302 }
2303 if !spec.order_by.is_empty() {
2304 if !spec.partition_by.is_empty() {
2305 self.write(" ");
2306 }
2307 self.write_keyword("ORDER BY ");
2308 for (i, item) in spec.order_by.iter().enumerate() {
2309 if i > 0 {
2310 self.write(", ");
2311 }
2312 self.gen_expr(&item.expr);
2313 if !item.ascending {
2314 self.write(" ");
2315 self.write_keyword("DESC");
2316 }
2317 if let Some(nulls_first) = item.nulls_first {
2318 if nulls_first {
2319 self.write(" ");
2320 self.write_keyword("NULLS FIRST");
2321 } else {
2322 self.write(" ");
2323 self.write_keyword("NULLS LAST");
2324 }
2325 }
2326 }
2327 }
2328 if let Some(frame) = &spec.frame {
2329 self.write(" ");
2330 self.gen_window_frame(frame);
2331 }
2332 }
2333
2334 fn gen_window_frame(&mut self, frame: &WindowFrame) {
2335 match frame.kind {
2336 WindowFrameKind::Rows => self.write_keyword("ROWS "),
2337 WindowFrameKind::Range => self.write_keyword("RANGE "),
2338 WindowFrameKind::Groups => self.write_keyword("GROUPS "),
2339 }
2340 if let Some(end) = &frame.end {
2341 self.write_keyword("BETWEEN ");
2342 self.gen_window_frame_bound(&frame.start);
2343 self.write(" ");
2344 self.write_keyword("AND ");
2345 self.gen_window_frame_bound(end);
2346 } else {
2347 self.gen_window_frame_bound(&frame.start);
2348 }
2349 }
2350
2351 fn gen_window_frame_bound(&mut self, bound: &WindowFrameBound) {
2352 match bound {
2353 WindowFrameBound::CurrentRow => self.write_keyword("CURRENT ROW"),
2354 WindowFrameBound::Preceding(None) => self.write_keyword("UNBOUNDED PRECEDING"),
2355 WindowFrameBound::Preceding(Some(n)) => {
2356 self.gen_expr(n);
2357 self.write(" ");
2358 self.write_keyword("PRECEDING");
2359 }
2360 WindowFrameBound::Following(None) => self.write_keyword("UNBOUNDED FOLLOWING"),
2361 WindowFrameBound::Following(Some(n)) => {
2362 self.gen_expr(n);
2363 self.write(" ");
2364 self.write_keyword("FOLLOWING");
2365 }
2366 }
2367 }
2368
2369 fn gen_datetime_field(&mut self, field: &DateTimeField) {
2370 let name = match field {
2371 DateTimeField::Year => "YEAR",
2372 DateTimeField::Quarter => "QUARTER",
2373 DateTimeField::Month => "MONTH",
2374 DateTimeField::Week => "WEEK",
2375 DateTimeField::Day => "DAY",
2376 DateTimeField::DayOfWeek => "DOW",
2377 DateTimeField::DayOfYear => "DOY",
2378 DateTimeField::Hour => "HOUR",
2379 DateTimeField::Minute => "MINUTE",
2380 DateTimeField::Second => "SECOND",
2381 DateTimeField::Millisecond => "MILLISECOND",
2382 DateTimeField::Microsecond => "MICROSECOND",
2383 DateTimeField::Nanosecond => "NANOSECOND",
2384 DateTimeField::Epoch => "EPOCH",
2385 DateTimeField::Timezone => "TIMEZONE",
2386 DateTimeField::TimezoneHour => "TIMEZONE_HOUR",
2387 DateTimeField::TimezoneMinute => "TIMEZONE_MINUTE",
2388 };
2389 self.write(name);
2390 }
2391
2392 fn gen_typed_function(&mut self, func: &TypedFunction) {
2394 let dialect = self.dialect;
2395 let is_tsql = matches!(dialect, Some(Dialect::Tsql) | Some(Dialect::Fabric));
2396 let is_mysql = matches!(
2397 dialect,
2398 Some(Dialect::Mysql)
2399 | Some(Dialect::SingleStore)
2400 | Some(Dialect::Doris)
2401 | Some(Dialect::StarRocks)
2402 );
2403 let is_bigquery = matches!(dialect, Some(Dialect::BigQuery));
2404 let is_snowflake = matches!(dialect, Some(Dialect::Snowflake));
2405 let is_oracle = matches!(dialect, Some(Dialect::Oracle));
2406 let is_hive_family = matches!(
2407 dialect,
2408 Some(Dialect::Hive) | Some(Dialect::Spark) | Some(Dialect::Databricks)
2409 );
2410
2411 match func {
2412 TypedFunction::DateAdd {
2414 expr,
2415 interval,
2416 unit,
2417 } => {
2418 if is_tsql || is_snowflake {
2419 self.write_keyword("DATEADD(");
2420 if let Some(u) = unit {
2421 self.gen_datetime_field(u);
2422 } else {
2423 self.write_keyword("DAY");
2424 }
2425 self.write(", ");
2426 self.gen_expr(interval);
2427 self.write(", ");
2428 self.gen_expr(expr);
2429 self.write(")");
2430 } else if is_bigquery {
2431 self.write_keyword("DATE_ADD(");
2432 self.gen_expr(expr);
2433 self.write(", ");
2434 self.write_keyword("INTERVAL ");
2435 self.gen_expr(interval);
2436 self.write(" ");
2437 if let Some(u) = unit {
2438 self.gen_datetime_field(u);
2439 } else {
2440 self.write_keyword("DAY");
2441 }
2442 self.write(")");
2443 } else {
2444 self.write_keyword("DATE_ADD(");
2445 self.gen_expr(expr);
2446 self.write(", ");
2447 self.gen_expr(interval);
2448 if let Some(u) = unit {
2449 self.write(", ");
2450 self.gen_datetime_field(u);
2451 }
2452 self.write(")");
2453 }
2454 }
2455 TypedFunction::DateDiff { start, end, unit } => {
2456 if is_tsql || is_snowflake {
2457 self.write_keyword("DATEDIFF(");
2458 if let Some(u) = unit {
2459 self.gen_datetime_field(u);
2460 } else {
2461 self.write_keyword("DAY");
2462 }
2463 self.write(", ");
2464 self.gen_expr(start);
2465 self.write(", ");
2466 self.gen_expr(end);
2467 self.write(")");
2468 } else if is_bigquery {
2469 self.write_keyword("DATE_DIFF(");
2470 self.gen_expr(end);
2471 self.write(", ");
2472 self.gen_expr(start);
2473 self.write(", ");
2474 if let Some(u) = unit {
2475 self.gen_datetime_field(u);
2476 } else {
2477 self.write_keyword("DAY");
2478 }
2479 self.write(")");
2480 } else {
2481 self.write_keyword("DATEDIFF(");
2482 self.gen_expr(start);
2483 self.write(", ");
2484 self.gen_expr(end);
2485 if let Some(u) = unit {
2486 self.write(", ");
2487 self.gen_datetime_field(u);
2488 }
2489 self.write(")");
2490 }
2491 }
2492 TypedFunction::DateTrunc { unit, expr } => {
2493 if is_tsql {
2494 self.write_keyword("DATETRUNC(");
2495 self.gen_datetime_field(unit);
2496 self.write(", ");
2497 self.gen_expr(expr);
2498 self.write(")");
2499 } else if is_oracle {
2500 self.write_keyword("TRUNC(");
2501 self.gen_expr(expr);
2502 self.write(", '");
2503 self.gen_datetime_field(unit);
2504 self.write("')");
2505 } else {
2506 self.write_keyword("DATE_TRUNC(");
2507 self.write("'");
2508 self.gen_datetime_field(unit);
2509 self.write("'");
2510 self.write(", ");
2511 self.gen_expr(expr);
2512 self.write(")");
2513 }
2514 }
2515 TypedFunction::DateSub {
2516 expr,
2517 interval,
2518 unit,
2519 } => {
2520 if is_tsql || is_snowflake {
2521 self.write_keyword("DATEADD(");
2522 if let Some(u) = unit {
2523 self.gen_datetime_field(u);
2524 } else {
2525 self.write_keyword("DAY");
2526 }
2527 self.write(", -(");
2528 self.gen_expr(interval);
2529 self.write("), ");
2530 self.gen_expr(expr);
2531 self.write(")");
2532 } else if is_bigquery {
2533 self.write_keyword("DATE_SUB(");
2534 self.gen_expr(expr);
2535 self.write(", ");
2536 self.write_keyword("INTERVAL ");
2537 self.gen_expr(interval);
2538 self.write(" ");
2539 if let Some(u) = unit {
2540 self.gen_datetime_field(u);
2541 } else {
2542 self.write_keyword("DAY");
2543 }
2544 self.write(")");
2545 } else {
2546 self.write_keyword("DATE_SUB(");
2547 self.gen_expr(expr);
2548 self.write(", ");
2549 self.gen_expr(interval);
2550 if let Some(u) = unit {
2551 self.write(", ");
2552 self.gen_datetime_field(u);
2553 }
2554 self.write(")");
2555 }
2556 }
2557 TypedFunction::CurrentDate => {
2558 if is_tsql {
2559 self.write_keyword("CAST(GETDATE() AS DATE)");
2560 } else if is_mysql || is_hive_family {
2561 self.write_keyword("CURRENT_DATE()");
2562 } else {
2563 self.write_keyword("CURRENT_DATE");
2564 }
2565 }
2566 TypedFunction::CurrentTime => {
2567 if is_tsql {
2568 self.write_keyword("CAST(GETDATE() AS TIME)");
2569 } else if is_mysql || is_hive_family {
2570 self.write_keyword("CURRENT_TIME()");
2571 } else {
2572 self.write_keyword("CURRENT_TIME");
2573 }
2574 }
2575 TypedFunction::CurrentTimestamp => {
2576 if is_tsql {
2577 self.write_keyword("GETDATE()");
2578 } else if is_mysql
2579 || matches!(
2580 dialect,
2581 Some(Dialect::Postgres)
2582 | Some(Dialect::DuckDb)
2583 | Some(Dialect::Sqlite)
2584 | Some(Dialect::Redshift)
2585 )
2586 {
2587 self.write_keyword("NOW()");
2588 } else {
2589 self.write_keyword("CURRENT_TIMESTAMP()");
2590 }
2591 }
2592 TypedFunction::StrToTime { expr, format } => {
2593 if is_mysql {
2594 self.write_keyword("STR_TO_DATE(");
2595 } else if is_bigquery {
2596 self.write_keyword("PARSE_TIMESTAMP(");
2597 } else {
2598 self.write_keyword("TO_TIMESTAMP(");
2599 }
2600 self.gen_expr(expr);
2601 self.write(", ");
2602 self.gen_expr(format);
2603 self.write(")");
2604 }
2605 TypedFunction::TimeToStr { expr, format } => {
2606 if is_mysql || is_hive_family {
2607 self.write_keyword("DATE_FORMAT(");
2608 } else if is_bigquery {
2609 self.write_keyword("FORMAT_TIMESTAMP(");
2610 } else if is_tsql {
2611 self.write_keyword("FORMAT(");
2612 } else {
2613 self.write_keyword("TO_CHAR(");
2614 }
2615 self.gen_expr(expr);
2616 self.write(", ");
2617 self.gen_expr(format);
2618 self.write(")");
2619 }
2620 TypedFunction::TsOrDsToDate { expr } => {
2621 if is_mysql {
2622 self.write_keyword("DATE(");
2623 self.gen_expr(expr);
2624 self.write(")");
2625 } else {
2626 self.write_keyword("CAST(");
2627 self.gen_expr(expr);
2628 self.write(" ");
2629 self.write_keyword("AS DATE)");
2630 }
2631 }
2632 TypedFunction::Year { expr } => {
2633 if is_tsql {
2634 self.write_keyword("YEAR(");
2635 self.gen_expr(expr);
2636 self.write(")");
2637 } else {
2638 self.write_keyword("EXTRACT(YEAR FROM ");
2639 self.gen_expr(expr);
2640 self.write(")");
2641 }
2642 }
2643 TypedFunction::Month { expr } => {
2644 if is_tsql {
2645 self.write_keyword("MONTH(");
2646 self.gen_expr(expr);
2647 self.write(")");
2648 } else {
2649 self.write_keyword("EXTRACT(MONTH FROM ");
2650 self.gen_expr(expr);
2651 self.write(")");
2652 }
2653 }
2654 TypedFunction::Day { expr } => {
2655 if is_tsql {
2656 self.write_keyword("DAY(");
2657 self.gen_expr(expr);
2658 self.write(")");
2659 } else {
2660 self.write_keyword("EXTRACT(DAY FROM ");
2661 self.gen_expr(expr);
2662 self.write(")");
2663 }
2664 }
2665
2666 TypedFunction::Trim {
2668 expr,
2669 trim_type,
2670 trim_chars,
2671 } => {
2672 self.write_keyword("TRIM(");
2673 match trim_type {
2674 TrimType::Leading => self.write_keyword("LEADING "),
2675 TrimType::Trailing => self.write_keyword("TRAILING "),
2676 TrimType::Both => {} }
2678 if let Some(chars) = trim_chars {
2679 self.gen_expr(chars);
2680 self.write(" ");
2681 self.write_keyword("FROM ");
2682 }
2683 self.gen_expr(expr);
2684 self.write(")");
2685 }
2686 TypedFunction::Substring {
2687 expr,
2688 start,
2689 length,
2690 } => {
2691 let name = if is_oracle
2692 || is_hive_family
2693 || is_mysql
2694 || matches!(
2695 dialect,
2696 Some(Dialect::Sqlite)
2697 | Some(Dialect::Doris)
2698 | Some(Dialect::SingleStore)
2699 | Some(Dialect::StarRocks)
2700 ) {
2701 "SUBSTR"
2702 } else {
2703 "SUBSTRING"
2704 };
2705 self.write_keyword(name);
2706 self.write("(");
2707 self.gen_expr(expr);
2708 self.write(", ");
2709 self.gen_expr(start);
2710 if let Some(l) = length {
2711 self.write(", ");
2712 self.gen_expr(l);
2713 }
2714 self.write(")");
2715 }
2716 TypedFunction::Upper { expr } => {
2717 self.write_keyword("UPPER(");
2718 self.gen_expr(expr);
2719 self.write(")");
2720 }
2721 TypedFunction::Lower { expr } => {
2722 self.write_keyword("LOWER(");
2723 self.gen_expr(expr);
2724 self.write(")");
2725 }
2726 TypedFunction::RegexpLike {
2727 expr,
2728 pattern,
2729 flags,
2730 } => {
2731 self.write_keyword("REGEXP_LIKE(");
2732 self.gen_expr(expr);
2733 self.write(", ");
2734 self.gen_expr(pattern);
2735 if let Some(f) = flags {
2736 self.write(", ");
2737 self.gen_expr(f);
2738 }
2739 self.write(")");
2740 }
2741 TypedFunction::RegexpExtract {
2742 expr,
2743 pattern,
2744 group_index,
2745 } => {
2746 if is_bigquery || is_hive_family {
2747 self.write_keyword("REGEXP_EXTRACT(");
2748 } else {
2749 self.write_keyword("REGEXP_SUBSTR(");
2750 }
2751 self.gen_expr(expr);
2752 self.write(", ");
2753 self.gen_expr(pattern);
2754 if let Some(g) = group_index {
2755 self.write(", ");
2756 self.gen_expr(g);
2757 }
2758 self.write(")");
2759 }
2760 TypedFunction::RegexpReplace {
2761 expr,
2762 pattern,
2763 replacement,
2764 flags,
2765 } => {
2766 self.write_keyword("REGEXP_REPLACE(");
2767 self.gen_expr(expr);
2768 self.write(", ");
2769 self.gen_expr(pattern);
2770 self.write(", ");
2771 self.gen_expr(replacement);
2772 if let Some(f) = flags {
2773 self.write(", ");
2774 self.gen_expr(f);
2775 }
2776 self.write(")");
2777 }
2778 TypedFunction::ConcatWs { separator, exprs } => {
2779 self.write_keyword("CONCAT_WS(");
2780 self.gen_expr(separator);
2781 for e in exprs {
2782 self.write(", ");
2783 self.gen_expr(e);
2784 }
2785 self.write(")");
2786 }
2787 TypedFunction::Split { expr, delimiter } => {
2788 if is_tsql {
2789 self.write_keyword("STRING_SPLIT(");
2790 } else {
2791 self.write_keyword("SPLIT(");
2792 }
2793 self.gen_expr(expr);
2794 self.write(", ");
2795 self.gen_expr(delimiter);
2796 self.write(")");
2797 }
2798 TypedFunction::Initcap { expr } => {
2799 self.write_keyword("INITCAP(");
2800 self.gen_expr(expr);
2801 self.write(")");
2802 }
2803 TypedFunction::Length { expr } => {
2804 let name = if is_tsql || is_bigquery || is_snowflake {
2805 "LEN"
2806 } else {
2807 "LENGTH"
2808 };
2809 self.write_keyword(name);
2810 self.write("(");
2811 self.gen_expr(expr);
2812 self.write(")");
2813 }
2814 TypedFunction::Replace { expr, from, to } => {
2815 self.write_keyword("REPLACE(");
2816 self.gen_expr(expr);
2817 self.write(", ");
2818 self.gen_expr(from);
2819 self.write(", ");
2820 self.gen_expr(to);
2821 self.write(")");
2822 }
2823 TypedFunction::Reverse { expr } => {
2824 self.write_keyword("REVERSE(");
2825 self.gen_expr(expr);
2826 self.write(")");
2827 }
2828 TypedFunction::Left { expr, n } => {
2829 self.write_keyword("LEFT(");
2830 self.gen_expr(expr);
2831 self.write(", ");
2832 self.gen_expr(n);
2833 self.write(")");
2834 }
2835 TypedFunction::Right { expr, n } => {
2836 self.write_keyword("RIGHT(");
2837 self.gen_expr(expr);
2838 self.write(", ");
2839 self.gen_expr(n);
2840 self.write(")");
2841 }
2842 TypedFunction::Lpad { expr, length, pad } => {
2843 self.write_keyword("LPAD(");
2844 self.gen_expr(expr);
2845 self.write(", ");
2846 self.gen_expr(length);
2847 if let Some(p) = pad {
2848 self.write(", ");
2849 self.gen_expr(p);
2850 }
2851 self.write(")");
2852 }
2853 TypedFunction::Rpad { expr, length, pad } => {
2854 self.write_keyword("RPAD(");
2855 self.gen_expr(expr);
2856 self.write(", ");
2857 self.gen_expr(length);
2858 if let Some(p) = pad {
2859 self.write(", ");
2860 self.gen_expr(p);
2861 }
2862 self.write(")");
2863 }
2864
2865 TypedFunction::Count { expr, distinct } => {
2867 self.write_keyword("COUNT(");
2868 if *distinct {
2869 self.write_keyword("DISTINCT ");
2870 }
2871 self.gen_expr(expr);
2872 self.write(")");
2873 }
2874 TypedFunction::Sum { expr, distinct } => {
2875 self.write_keyword("SUM(");
2876 if *distinct {
2877 self.write_keyword("DISTINCT ");
2878 }
2879 self.gen_expr(expr);
2880 self.write(")");
2881 }
2882 TypedFunction::Avg { expr, distinct } => {
2883 self.write_keyword("AVG(");
2884 if *distinct {
2885 self.write_keyword("DISTINCT ");
2886 }
2887 self.gen_expr(expr);
2888 self.write(")");
2889 }
2890 TypedFunction::Min { expr } => {
2891 self.write_keyword("MIN(");
2892 self.gen_expr(expr);
2893 self.write(")");
2894 }
2895 TypedFunction::Max { expr } => {
2896 self.write_keyword("MAX(");
2897 self.gen_expr(expr);
2898 self.write(")");
2899 }
2900 TypedFunction::ArrayAgg { expr, distinct } => {
2901 let name = if matches!(dialect, Some(Dialect::DuckDb)) {
2902 "LIST"
2903 } else if is_hive_family {
2904 "COLLECT_LIST"
2905 } else {
2906 "ARRAY_AGG"
2907 };
2908 self.write_keyword(name);
2909 self.write("(");
2910 if *distinct {
2911 self.write_keyword("DISTINCT ");
2912 }
2913 self.gen_expr(expr);
2914 self.write(")");
2915 }
2916 TypedFunction::ApproxDistinct { expr } => {
2917 let name = if is_hive_family
2918 || matches!(
2919 dialect,
2920 Some(Dialect::Presto) | Some(Dialect::Trino) | Some(Dialect::Athena)
2921 ) {
2922 "APPROX_DISTINCT"
2923 } else {
2924 "APPROX_COUNT_DISTINCT"
2925 };
2926 self.write_keyword(name);
2927 self.write("(");
2928 self.gen_expr(expr);
2929 self.write(")");
2930 }
2931 TypedFunction::Variance { expr } => {
2932 let name = if is_tsql || is_oracle {
2933 "VAR"
2934 } else {
2935 "VARIANCE"
2936 };
2937 self.write_keyword(name);
2938 self.write("(");
2939 self.gen_expr(expr);
2940 self.write(")");
2941 }
2942 TypedFunction::VariancePop { expr } => {
2943 let name = if is_tsql { "VARP" } else { "VAR_POP" };
2945 self.write_keyword(name);
2946 self.write("(");
2947 self.gen_expr(expr);
2948 self.write(")");
2949 }
2950 TypedFunction::Stddev { expr } => {
2951 let name = if is_tsql { "STDEV" } else { "STDDEV" };
2954 self.write_keyword(name);
2955 self.write("(");
2956 self.gen_expr(expr);
2957 self.write(")");
2958 }
2959 TypedFunction::StddevPop { expr } => {
2960 let name = if is_tsql { "STDEVP" } else { "STDDEV_POP" };
2963 self.write_keyword(name);
2964 self.write("(");
2965 self.gen_expr(expr);
2966 self.write(")");
2967 }
2968 TypedFunction::GroupConcat {
2969 exprs,
2970 separator,
2971 order_by,
2972 distinct,
2973 } => {
2974 self.gen_group_concat(exprs, separator.as_deref(), order_by, *distinct);
2975 }
2976
2977 TypedFunction::ArrayConcat { arrays } => {
2979 let name = if matches!(
2980 dialect,
2981 Some(Dialect::Postgres) | Some(Dialect::Redshift) | Some(Dialect::DuckDb)
2982 ) {
2983 "ARRAY_CAT"
2984 } else {
2985 "ARRAY_CONCAT"
2986 };
2987 self.write_keyword(name);
2988 self.write("(");
2989 self.gen_expr_list(arrays);
2990 self.write(")");
2991 }
2992 TypedFunction::ArrayContains { array, element } => {
2993 self.write_keyword("ARRAY_CONTAINS(");
2994 self.gen_expr(array);
2995 self.write(", ");
2996 self.gen_expr(element);
2997 self.write(")");
2998 }
2999 TypedFunction::ArraySize { expr } => {
3000 let name = if matches!(dialect, Some(Dialect::Postgres) | Some(Dialect::Redshift)) {
3001 "ARRAY_LENGTH"
3002 } else if is_hive_family {
3003 "SIZE"
3004 } else {
3005 "ARRAY_SIZE"
3006 };
3007 self.write_keyword(name);
3008 self.write("(");
3009 self.gen_expr(expr);
3010 self.write(")");
3011 }
3012 TypedFunction::Explode { expr } => {
3013 self.write_keyword("EXPLODE(");
3014 self.gen_expr(expr);
3015 self.write(")");
3016 }
3017 TypedFunction::GenerateSeries { start, stop, step } => {
3018 self.write_keyword("GENERATE_SERIES(");
3019 self.gen_expr(start);
3020 self.write(", ");
3021 self.gen_expr(stop);
3022 if let Some(s) = step {
3023 self.write(", ");
3024 self.gen_expr(s);
3025 }
3026 self.write(")");
3027 }
3028 TypedFunction::Flatten { expr } => {
3029 self.write_keyword("FLATTEN(");
3030 self.gen_expr(expr);
3031 self.write(")");
3032 }
3033
3034 TypedFunction::JSONExtract { expr, path } => {
3036 if is_tsql {
3037 self.write_keyword("JSON_VALUE(");
3038 } else {
3039 self.write_keyword("JSON_EXTRACT(");
3040 }
3041 self.gen_expr(expr);
3042 self.write(", ");
3043 self.gen_expr(path);
3044 self.write(")");
3045 }
3046 TypedFunction::JSONExtractScalar { expr, path } => {
3047 if is_bigquery {
3048 self.write_keyword("JSON_EXTRACT_SCALAR(");
3049 } else if is_tsql {
3050 self.write_keyword("JSON_VALUE(");
3051 } else {
3052 self.write_keyword("JSON_EXTRACT_SCALAR(");
3053 }
3054 self.gen_expr(expr);
3055 self.write(", ");
3056 self.gen_expr(path);
3057 self.write(")");
3058 }
3059 TypedFunction::ParseJSON { expr } => {
3060 if is_snowflake {
3061 self.write_keyword("PARSE_JSON(");
3062 } else if is_bigquery {
3063 self.write_keyword("JSON_PARSE(");
3064 } else {
3065 self.write_keyword("PARSE_JSON(");
3066 }
3067 self.gen_expr(expr);
3068 self.write(")");
3069 }
3070 TypedFunction::JSONFormat { expr } => {
3071 if is_bigquery {
3072 self.write_keyword("TO_JSON_STRING(");
3073 } else {
3074 self.write_keyword("JSON_FORMAT(");
3075 }
3076 self.gen_expr(expr);
3077 self.write(")");
3078 }
3079
3080 TypedFunction::RowNumber => self.write_keyword("ROW_NUMBER()"),
3082 TypedFunction::Rank => self.write_keyword("RANK()"),
3083 TypedFunction::DenseRank => self.write_keyword("DENSE_RANK()"),
3084 TypedFunction::NTile { n } => {
3085 self.write_keyword("NTILE(");
3086 self.gen_expr(n);
3087 self.write(")");
3088 }
3089 TypedFunction::Lead {
3090 expr,
3091 offset,
3092 default,
3093 } => {
3094 self.write_keyword("LEAD(");
3095 self.gen_expr(expr);
3096 if let Some(o) = offset {
3097 self.write(", ");
3098 self.gen_expr(o);
3099 }
3100 if let Some(d) = default {
3101 self.write(", ");
3102 self.gen_expr(d);
3103 }
3104 self.write(")");
3105 }
3106 TypedFunction::Lag {
3107 expr,
3108 offset,
3109 default,
3110 } => {
3111 self.write_keyword("LAG(");
3112 self.gen_expr(expr);
3113 if let Some(o) = offset {
3114 self.write(", ");
3115 self.gen_expr(o);
3116 }
3117 if let Some(d) = default {
3118 self.write(", ");
3119 self.gen_expr(d);
3120 }
3121 self.write(")");
3122 }
3123 TypedFunction::FirstValue { expr } => {
3124 self.write_keyword("FIRST_VALUE(");
3125 self.gen_expr(expr);
3126 self.write(")");
3127 }
3128 TypedFunction::LastValue { expr } => {
3129 self.write_keyword("LAST_VALUE(");
3130 self.gen_expr(expr);
3131 self.write(")");
3132 }
3133
3134 TypedFunction::Abs { expr } => {
3136 self.write_keyword("ABS(");
3137 self.gen_expr(expr);
3138 self.write(")");
3139 }
3140 TypedFunction::Ceil { expr } => {
3141 let name = if is_tsql { "CEILING" } else { "CEIL" };
3142 self.write_keyword(name);
3143 self.write("(");
3144 self.gen_expr(expr);
3145 self.write(")");
3146 }
3147 TypedFunction::Floor { expr } => {
3148 self.write_keyword("FLOOR(");
3149 self.gen_expr(expr);
3150 self.write(")");
3151 }
3152 TypedFunction::Round { expr, decimals } => {
3153 self.write_keyword("ROUND(");
3154 self.gen_expr(expr);
3155 if let Some(d) = decimals {
3156 self.write(", ");
3157 self.gen_expr(d);
3158 }
3159 self.write(")");
3160 }
3161 TypedFunction::Log { expr, base } => {
3162 if let Some(b) = base {
3163 self.write_keyword("LOG(");
3164 if matches!(dialect, Some(Dialect::Postgres) | Some(Dialect::DuckDb)) {
3165 self.gen_expr(b);
3167 self.write(", ");
3168 self.gen_expr(expr);
3169 } else {
3170 self.gen_expr(expr);
3172 self.write(", ");
3173 self.gen_expr(b);
3174 }
3175 self.write(")");
3176 } else {
3177 self.write_keyword("LOG(");
3179 self.gen_expr(expr);
3180 self.write(")");
3181 }
3182 }
3183 TypedFunction::Ln { expr } => {
3184 self.write_keyword("LN(");
3185 self.gen_expr(expr);
3186 self.write(")");
3187 }
3188 TypedFunction::Pow { base, exponent } => {
3189 let name = if is_tsql || is_oracle { "POWER" } else { "POW" };
3190 self.write_keyword(name);
3191 self.write("(");
3192 self.gen_expr(base);
3193 self.write(", ");
3194 self.gen_expr(exponent);
3195 self.write(")");
3196 }
3197 TypedFunction::Sqrt { expr } => {
3198 self.write_keyword("SQRT(");
3199 self.gen_expr(expr);
3200 self.write(")");
3201 }
3202 TypedFunction::Greatest { exprs } => {
3203 self.write_keyword("GREATEST(");
3204 self.gen_expr_list(exprs);
3205 self.write(")");
3206 }
3207 TypedFunction::Least { exprs } => {
3208 self.write_keyword("LEAST(");
3209 self.gen_expr_list(exprs);
3210 self.write(")");
3211 }
3212 TypedFunction::Mod { left, right } => {
3213 self.write_keyword("MOD(");
3214 self.gen_expr(left);
3215 self.write(", ");
3216 self.gen_expr(right);
3217 self.write(")");
3218 }
3219
3220 TypedFunction::Hex { expr } => {
3222 let name = if matches!(
3223 dialect,
3224 Some(Dialect::Presto) | Some(Dialect::Trino) | Some(Dialect::Athena)
3225 ) {
3226 "TO_HEX"
3227 } else {
3228 "HEX"
3229 };
3230 self.write_keyword(name);
3231 self.write("(");
3232 self.gen_expr(expr);
3233 self.write(")");
3234 }
3235 TypedFunction::Unhex { expr } => {
3236 let name = if matches!(
3237 dialect,
3238 Some(Dialect::Presto) | Some(Dialect::Trino) | Some(Dialect::Athena)
3239 ) {
3240 "FROM_HEX"
3241 } else {
3242 "UNHEX"
3243 };
3244 self.write_keyword(name);
3245 self.write("(");
3246 self.gen_expr(expr);
3247 self.write(")");
3248 }
3249 TypedFunction::Md5 { expr } => {
3250 self.write_keyword("MD5(");
3251 self.gen_expr(expr);
3252 self.write(")");
3253 }
3254 TypedFunction::Sha { expr } => {
3255 let name = if is_mysql { "SHA1" } else { "SHA" };
3256 self.write_keyword(name);
3257 self.write("(");
3258 self.gen_expr(expr);
3259 self.write(")");
3260 }
3261 TypedFunction::Sha2 { expr, bit_length } => {
3262 self.write_keyword("SHA2(");
3263 self.gen_expr(expr);
3264 self.write(", ");
3265 self.gen_expr(bit_length);
3266 self.write(")");
3267 }
3268 }
3269 }
3270
3271 fn gen_group_concat(
3274 &mut self,
3275 exprs: &[Expr],
3276 separator: Option<&Expr>,
3277 order_by: &[OrderByItem],
3278 distinct: bool,
3279 ) {
3280 let dialect = self.dialect;
3281 let is_sqlite = matches!(dialect, Some(Dialect::Sqlite));
3282 let is_string_agg = matches!(
3283 dialect,
3284 Some(Dialect::Postgres)
3285 | Some(Dialect::Redshift)
3286 | Some(Dialect::BigQuery)
3287 | Some(Dialect::Tsql)
3288 | Some(Dialect::Fabric)
3289 | Some(Dialect::DuckDb)
3290 );
3291 let is_listagg = matches!(dialect, Some(Dialect::Oracle) | Some(Dialect::Snowflake));
3292
3293 if is_string_agg {
3294 self.write_keyword("STRING_AGG(");
3296 if distinct {
3297 self.write_keyword("DISTINCT ");
3298 }
3299 self.gen_group_concat_exprs(exprs);
3300 self.write(", ");
3301 match separator {
3302 Some(s) => self.gen_expr(s),
3303 None => self.write("','"),
3304 }
3305 if !order_by.is_empty() {
3306 self.write(" ");
3307 self.gen_group_concat_order_by(order_by);
3308 }
3309 self.write(")");
3310 } else if is_listagg {
3311 self.write_keyword("LISTAGG(");
3313 if distinct {
3314 self.write_keyword("DISTINCT ");
3315 }
3316 self.gen_group_concat_exprs(exprs);
3317 self.write(", ");
3318 match separator {
3319 Some(s) => self.gen_expr(s),
3320 None => self.write("','"),
3321 }
3322 self.write(")");
3323 if !order_by.is_empty() {
3324 self.write(" ");
3325 self.write_keyword("WITHIN GROUP");
3326 self.write(" (");
3327 self.gen_group_concat_order_by(order_by);
3328 self.write(")");
3329 }
3330 } else if is_sqlite {
3331 self.write_keyword("GROUP_CONCAT(");
3334 self.gen_group_concat_exprs(exprs);
3335 if let Some(s) = separator {
3336 self.write(", ");
3337 self.gen_expr(s);
3338 }
3339 self.write(")");
3340 } else {
3341 self.write_keyword("GROUP_CONCAT(");
3343 if distinct {
3344 self.write_keyword("DISTINCT ");
3345 }
3346 self.gen_group_concat_exprs(exprs);
3347 if !order_by.is_empty() {
3348 self.write(" ");
3349 self.gen_group_concat_order_by(order_by);
3350 }
3351 if let Some(s) = separator {
3352 self.write(" ");
3353 self.write_keyword("SEPARATOR");
3354 self.write(" ");
3355 self.gen_expr(s);
3356 }
3357 self.write(")");
3358 }
3359 }
3360
3361 fn gen_group_concat_exprs(&mut self, exprs: &[Expr]) {
3362 for (i, e) in exprs.iter().enumerate() {
3363 if i > 0 {
3364 self.write(", ");
3365 }
3366 self.gen_expr(e);
3367 }
3368 }
3369
3370 fn gen_group_concat_order_by(&mut self, order_by: &[OrderByItem]) {
3371 self.write_keyword("ORDER BY");
3372 self.write(" ");
3373 for (i, item) in order_by.iter().enumerate() {
3374 if i > 0 {
3375 self.write(", ");
3376 }
3377 self.gen_expr(&item.expr);
3378 if !item.ascending {
3379 self.write(" ");
3380 self.write_keyword("DESC");
3381 }
3382 if let Some(nulls_first) = item.nulls_first {
3383 self.write(" ");
3384 self.write_keyword(if nulls_first {
3385 "NULLS FIRST"
3386 } else {
3387 "NULLS LAST"
3388 });
3389 }
3390 }
3391 }
3392}
3393
3394impl Default for Generator {
3395 fn default() -> Self {
3396 Self::new()
3397 }
3398}
3399
3400#[cfg(test)]
3401mod tests {
3402 use super::*;
3403 use crate::parser::Parser;
3404
3405 fn roundtrip(sql: &str) -> String {
3406 let stmt = Parser::new(sql).unwrap().parse_statement().unwrap();
3407 let mut g = Generator::new();
3408 g.generate(&stmt)
3409 }
3410
3411 #[test]
3412 fn test_select_roundtrip() {
3413 assert_eq!(roundtrip("SELECT a, b FROM t"), "SELECT a, b FROM t");
3414 }
3415
3416 #[test]
3417 fn test_select_where() {
3418 assert_eq!(
3419 roundtrip("SELECT x FROM t WHERE x > 10"),
3420 "SELECT x FROM t WHERE x > 10"
3421 );
3422 }
3423
3424 #[test]
3425 fn test_select_wildcard() {
3426 assert_eq!(roundtrip("SELECT * FROM users"), "SELECT * FROM users");
3427 }
3428
3429 #[test]
3430 fn test_insert_values() {
3431 assert_eq!(
3432 roundtrip("INSERT INTO t (a, b) VALUES (1, 'hello')"),
3433 "INSERT INTO t (a, b) VALUES (1, 'hello')"
3434 );
3435 }
3436
3437 #[test]
3438 fn test_delete() {
3439 assert_eq!(
3440 roundtrip("DELETE FROM users WHERE id = 1"),
3441 "DELETE FROM users WHERE id = 1"
3442 );
3443 }
3444
3445 #[test]
3446 fn test_join() {
3447 assert_eq!(
3448 roundtrip("SELECT a.id, b.name FROM a INNER JOIN b ON a.id = b.a_id"),
3449 "SELECT a.id, b.name FROM a INNER JOIN b ON a.id = b.a_id"
3450 );
3451 }
3452
3453 #[test]
3454 fn test_create_table() {
3455 assert_eq!(
3456 roundtrip("CREATE TABLE users (id INT NOT NULL, name VARCHAR(255), email TEXT)"),
3457 "CREATE TABLE users (id INT NOT NULL, name VARCHAR(255), email TEXT)"
3458 );
3459 }
3460
3461 #[test]
3462 fn test_cte_roundtrip() {
3463 let sql = "WITH cte AS (SELECT 1 AS x) SELECT x FROM cte";
3464 assert_eq!(
3465 roundtrip(sql),
3466 "WITH cte AS (SELECT 1 AS x) SELECT x FROM cte"
3467 );
3468 }
3469
3470 #[test]
3471 fn test_union_roundtrip() {
3472 let sql = "SELECT 1 UNION ALL SELECT 2";
3473 assert_eq!(roundtrip(sql), "SELECT 1 UNION ALL SELECT 2");
3474 }
3475
3476 #[test]
3477 fn test_cast_roundtrip() {
3478 assert_eq!(
3479 roundtrip("SELECT CAST(x AS INT) FROM t"),
3480 "SELECT CAST(x AS INT) FROM t"
3481 );
3482 }
3483
3484 #[test]
3485 fn test_exists_roundtrip() {
3486 assert_eq!(
3487 roundtrip("SELECT * FROM t WHERE EXISTS (SELECT 1 FROM t2)"),
3488 "SELECT * FROM t WHERE EXISTS (SELECT 1 FROM t2)"
3489 );
3490 }
3491
3492 #[test]
3493 fn test_extract_roundtrip() {
3494 assert_eq!(
3495 roundtrip("SELECT EXTRACT(YEAR FROM created_at) FROM t"),
3496 "SELECT EXTRACT(YEAR FROM created_at) FROM t"
3497 );
3498 }
3499
3500 #[test]
3501 fn test_window_function_roundtrip() {
3502 assert_eq!(
3503 roundtrip("SELECT ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) FROM emp"),
3504 "SELECT ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) FROM emp"
3505 );
3506 }
3507
3508 #[test]
3509 fn test_subquery_from_roundtrip() {
3510 assert_eq!(
3511 roundtrip("SELECT * FROM (SELECT 1 AS x) AS sub"),
3512 "SELECT * FROM (SELECT 1 AS x) AS sub"
3513 );
3514 }
3515
3516 #[test]
3517 fn test_in_subquery_roundtrip() {
3518 assert_eq!(
3519 roundtrip("SELECT * FROM t WHERE id IN (SELECT id FROM t2)"),
3520 "SELECT * FROM t WHERE id IN (SELECT id FROM t2)"
3521 );
3522 }
3523
3524 fn pretty_print(sql: &str) -> String {
3529 let stmt = Parser::new(sql).unwrap().parse_statement().unwrap();
3530 let mut g = Generator::pretty();
3531 g.generate(&stmt)
3532 }
3533
3534 #[test]
3535 fn test_pretty_simple_select() {
3536 assert_eq!(
3537 pretty_print("SELECT a, b, c FROM t"),
3538 "SELECT\n a,\n b,\n c\nFROM\n t"
3539 );
3540 }
3541
3542 #[test]
3543 fn test_pretty_select_where() {
3544 assert_eq!(
3545 pretty_print("SELECT a FROM t WHERE a > 1"),
3546 "SELECT\n a\nFROM\n t\nWHERE\n a > 1"
3547 );
3548 }
3549
3550 #[test]
3551 fn test_pretty_select_group_by_having() {
3552 assert_eq!(
3553 pretty_print("SELECT a, COUNT(*) FROM t GROUP BY a HAVING COUNT(*) > 1"),
3554 "SELECT\n a,\n COUNT(*)\nFROM\n t\nGROUP BY\n a\nHAVING\n COUNT(*) > 1"
3555 );
3556 }
3557
3558 #[test]
3559 fn test_pretty_select_order_by_limit() {
3560 assert_eq!(
3561 pretty_print("SELECT a FROM t ORDER BY a DESC LIMIT 10"),
3562 "SELECT\n a\nFROM\n t\nORDER BY\n a DESC\nLIMIT 10"
3563 );
3564 }
3565
3566 #[test]
3567 fn test_pretty_join() {
3568 assert_eq!(
3569 pretty_print("SELECT a.id, b.name FROM a INNER JOIN b ON a.id = b.a_id"),
3570 "SELECT\n a.id,\n b.name\nFROM\n a\nINNER JOIN\n b\n ON a.id = b.a_id"
3571 );
3572 }
3573
3574 #[test]
3575 fn test_pretty_cte() {
3576 assert_eq!(
3577 pretty_print("WITH cte AS (SELECT 1 AS x) SELECT x FROM cte"),
3578 "WITH cte AS (\n SELECT\n 1 AS x\n)\nSELECT\n x\nFROM\n cte"
3579 );
3580 }
3581
3582 #[test]
3583 fn test_pretty_union() {
3584 assert_eq!(
3585 pretty_print("SELECT 1 UNION ALL SELECT 2"),
3586 "SELECT\n 1\nUNION ALL\nSELECT\n 2"
3587 );
3588 }
3589
3590 #[test]
3591 fn test_pretty_insert() {
3592 assert_eq!(
3593 pretty_print("INSERT INTO t (a, b) VALUES (1, 'hello'), (2, 'world')"),
3594 "INSERT INTO t (a, b)\nVALUES\n (1, 'hello'),\n (2, 'world')"
3595 );
3596 }
3597
3598 #[test]
3599 fn test_pretty_update() {
3600 assert_eq!(
3601 pretty_print("UPDATE t SET a = 1, b = 2 WHERE c = 3"),
3602 "UPDATE t\nSET\n a = 1,\n b = 2\nWHERE\n c = 3"
3603 );
3604 }
3605
3606 #[test]
3607 fn test_pretty_delete() {
3608 assert_eq!(
3609 pretty_print("DELETE FROM t WHERE id = 1"),
3610 "DELETE FROM t\nWHERE\n id = 1"
3611 );
3612 }
3613
3614 #[test]
3615 fn test_pretty_create_table() {
3616 assert_eq!(
3617 pretty_print("CREATE TABLE t (id INT NOT NULL, name VARCHAR(255), email TEXT)"),
3618 "CREATE TABLE t (\n id INT NOT NULL,\n name VARCHAR(255),\n email TEXT\n)"
3619 );
3620 }
3621
3622 #[test]
3623 fn test_pretty_complex_query() {
3624 let sql = "SELECT a, SUM(b) FROM t1 INNER JOIN t2 ON t1.id = t2.id WHERE t1.x > 1 GROUP BY a HAVING SUM(b) > 10 ORDER BY a LIMIT 100";
3625 let expected = "SELECT\n a,\n SUM(b)\nFROM\n t1\nINNER JOIN\n t2\n ON t1.id = t2.id\nWHERE\n t1.x > 1\nGROUP BY\n a\nHAVING\n SUM(b) > 10\nORDER BY\n a\nLIMIT 100";
3626 assert_eq!(pretty_print(sql), expected);
3627 }
3628
3629 #[test]
3630 fn test_pretty_select_distinct() {
3631 assert_eq!(
3632 pretty_print("SELECT DISTINCT a, b FROM t"),
3633 "SELECT DISTINCT\n a,\n b\nFROM\n t"
3634 );
3635 }
3636}