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