Skip to main content

sqlglot_rust/generator/
sql_generator.rs

1use crate::ast::*;
2use crate::dialects::Dialect;
3
4/// SQL code generator that converts an AST into a SQL string.
5///
6/// Supports all statement and expression types defined in the AST,
7/// including CTEs, subqueries, UNION/INTERSECT/EXCEPT, CAST, window
8/// functions, EXISTS, EXTRACT, INTERVAL, and more.
9pub struct Generator {
10    output: String,
11    /// When true, emit formatted SQL with indentation and newlines.
12    pretty: bool,
13    indent: usize,
14    /// Target dialect for dialect-specific generation (typed functions).
15    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    /// Create a generator that produces formatted SQL.
30    #[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    /// Create a generator targeting a specific dialect.
41    #[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    /// Generate SQL from a statement.
52    #[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    /// Generate SQL for an expression (static helper for `Expr::sql()`).
60    #[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    /// Emit a newline followed by current indentation (pretty mode only).
72    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    /// In pretty mode: newline + indent. In compact mode: a single space.
82    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    /// Emit a column/table alias, automatically wrapping it in the target
103    /// dialect's canonical quoting style when the alias collides with a
104    /// reserved keyword for that dialect. Preserves any explicit quoting
105    /// the source already specified.
106    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    /// Write an identifier with the given quoting style.
119    /// If a target dialect is set and the identifier is quoted, the quoting
120    /// is transformed to the target dialect's canonical style.
121    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    // ══════════════════════════════════════════════════════════════
152    // Statements
153    // ══════════════════════════════════════════════════════════════
154
155    /// Emit comment strings, each on its own line.
156    /// MySQL hash comments (`#`) are converted to standard `--` comments
157    /// when the target dialect is not MySQL.
158    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    /// Normalize a comment for the target dialect.
167    /// Converts MySQL `#` comments to `--` when targeting non-MySQL dialects.
168    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    /// Emit a newline in pretty mode or a space in compact mode.
182    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        // Emit leading comments for statements that carry them.
195        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    // ── SELECT ──────────────────────────────────────────────────
270
271    fn gen_select(&mut self, sel: &SelectStatement) {
272        // CTEs
273        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        // columns
290        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            // Oracle 21c and earlier reject a FROM-less SELECT (ORA-00923). Emit
324            // `FROM DUAL` for portability — valid on every Oracle version. All
325            // FROM-less selects funnel through here (top-level statements, scalar
326            // subqueries, EXISTS, derived tables, and each set-operation branch),
327            // so nested cases are covered too. (PSQ-2848)
328            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    /// Returns true if the target dialect forbids `AS` in table aliases.
643    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    // ── Set operations ──────────────────────────────────────────
769
770    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    // ── INSERT ──────────────────────────────────────────────────
801
802    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        // T-SQL: OUTPUT goes before VALUES
813        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        // Non-T-SQL: RETURNING goes after VALUES
887        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    // ── UPDATE ──────────────────────────────────────────────────
902
903    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    // ── DELETE ──────────────────────────────────────────────────
970
971    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        // T-SQL: OUTPUT clause comes before WHERE
982        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        // Non-T-SQL: RETURNING after WHERE
1004        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    // ── CREATE TABLE ────────────────────────────────────────────
1019
1020    /// Emit a T-SQL OUTPUT clause: `OUTPUT prefix.col1, prefix.col2`
1021    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    // ── MERGE ───────────────────────────────────────────────────
1059
1060    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    // ── CREATE TABLE ────────────────────────────────────────────
1170
1171    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    // ── DROP TABLE ──────────────────────────────────────────────
1355
1356    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    // ── ALTER TABLE ─────────────────────────────────────────────
1369
1370    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    // ── CREATE / DROP VIEW ──────────────────────────────────────
1422
1423    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    // ── TRUNCATE ────────────────────────────────────────────────
1461
1462    fn gen_truncate(&mut self, t: &TruncateStatement) {
1463        self.write_keyword("TRUNCATE TABLE ");
1464        self.gen_table_ref(&t.table);
1465    }
1466
1467    // ── Transaction ─────────────────────────────────────────────
1468
1469    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    // ── EXPLAIN ─────────────────────────────────────────────────
1490
1491    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    // ── USE ─────────────────────────────────────────────────────
1500
1501    fn gen_use(&mut self, u: &UseStatement) {
1502        self.write_keyword("USE ");
1503        self.write(&u.name);
1504    }
1505
1506    // ══════════════════════════════════════════════════════════════
1507    // Data types
1508    // ══════════════════════════════════════════════════════════════
1509
1510    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::Boolean => self.write("BOOLEAN"),
1564            DataType::Date => self.write("DATE"),
1565            DataType::Time { precision } => {
1566                self.write("TIME");
1567                if let Some(p) = precision {
1568                    self.write(&format!("({p})"));
1569                }
1570            }
1571            DataType::Timestamp { precision, with_tz } => {
1572                self.write("TIMESTAMP");
1573                if let Some(p) = precision {
1574                    self.write(&format!("({p})"));
1575                }
1576                if *with_tz {
1577                    self.write(" WITH TIME ZONE");
1578                }
1579            }
1580            DataType::Interval => self.write("INTERVAL"),
1581            DataType::DateTime => self.write("DATETIME"),
1582            DataType::Blob => self.write("BLOB"),
1583            DataType::Bytea => self.write("BYTEA"),
1584            DataType::Bytes => self.write("BYTES"),
1585            DataType::Json => self.write("JSON"),
1586            DataType::Jsonb => self.write("JSONB"),
1587            DataType::Uuid => self.write("UUID"),
1588            DataType::Array(inner) => {
1589                let is_postgres = matches!(
1590                    self.dialect,
1591                    Some(
1592                        Dialect::Postgres
1593                            | Dialect::Redshift
1594                            | Dialect::Materialize
1595                            | Dialect::RisingWave
1596                    )
1597                );
1598                if is_postgres {
1599                    // PostgreSQL: emit "typename[]"
1600                    if let Some(inner) = inner {
1601                        self.gen_data_type(inner);
1602                        self.write("[]");
1603                    } else {
1604                        self.write("ARRAY");
1605                    }
1606                } else {
1607                    self.write("ARRAY");
1608                    if let Some(inner) = inner {
1609                        self.write("<");
1610                        self.gen_data_type(inner);
1611                        self.write(">");
1612                    }
1613                }
1614            }
1615            DataType::Map { key, value } => {
1616                self.write("MAP<");
1617                self.gen_data_type(key);
1618                self.write(", ");
1619                self.gen_data_type(value);
1620                self.write(">");
1621            }
1622            DataType::Struct(fields) => {
1623                self.write("STRUCT<");
1624                for (i, (name, dt)) in fields.iter().enumerate() {
1625                    if i > 0 {
1626                        self.write(", ");
1627                    }
1628                    self.write(name);
1629                    self.write(" ");
1630                    self.gen_data_type(dt);
1631                }
1632                self.write(">");
1633            }
1634            DataType::Tuple(types) => {
1635                self.write("TUPLE(");
1636                for (i, dt) in types.iter().enumerate() {
1637                    if i > 0 {
1638                        self.write(", ");
1639                    }
1640                    self.gen_data_type(dt);
1641                }
1642                self.write(")");
1643            }
1644            DataType::Null => self.write("NULL"),
1645            DataType::Variant => self.write("VARIANT"),
1646            DataType::Object => self.write("OBJECT"),
1647            DataType::Xml => self.write("XML"),
1648            DataType::Inet => self.write("INET"),
1649            DataType::Cidr => self.write("CIDR"),
1650            DataType::Macaddr => self.write("MACADDR"),
1651            DataType::Bit(len) => {
1652                self.write("BIT");
1653                if let Some(n) = len {
1654                    self.write(&format!("({n})"));
1655                }
1656            }
1657            DataType::Money => self.write("MONEY"),
1658            DataType::Serial => self.write("SERIAL"),
1659            DataType::BigSerial => self.write("BIGSERIAL"),
1660            DataType::SmallSerial => self.write("SMALLSERIAL"),
1661            DataType::Regclass => self.write("REGCLASS"),
1662            DataType::Regtype => self.write("REGTYPE"),
1663            DataType::Hstore => self.write("HSTORE"),
1664            DataType::Geography => self.write("GEOGRAPHY"),
1665            DataType::Geometry => self.write("GEOMETRY"),
1666            DataType::Super => self.write("SUPER"),
1667            DataType::Unknown(name) => self.write(name),
1668        }
1669    }
1670
1671    // ══════════════════════════════════════════════════════════════
1672    // Expressions
1673    // ══════════════════════════════════════════════════════════════
1674
1675    fn binary_op_str(op: &BinaryOperator) -> &'static str {
1676        match op {
1677            BinaryOperator::Plus => " + ",
1678            BinaryOperator::Minus => " - ",
1679            BinaryOperator::Multiply => " * ",
1680            BinaryOperator::Divide => " / ",
1681            BinaryOperator::Modulo => " % ",
1682            BinaryOperator::Eq => " = ",
1683            BinaryOperator::Neq => " <> ",
1684            BinaryOperator::Lt => " < ",
1685            BinaryOperator::Gt => " > ",
1686            BinaryOperator::LtEq => " <= ",
1687            BinaryOperator::GtEq => " >= ",
1688            BinaryOperator::And => " AND ",
1689            BinaryOperator::Or => " OR ",
1690            BinaryOperator::Xor => " XOR ",
1691            BinaryOperator::Concat => " || ",
1692            BinaryOperator::BitwiseAnd => " & ",
1693            BinaryOperator::BitwiseOr => " | ",
1694            BinaryOperator::BitwiseXor => " ^ ",
1695            BinaryOperator::ShiftLeft => " << ",
1696            BinaryOperator::ShiftRight => " >> ",
1697            BinaryOperator::Arrow => " -> ",
1698            BinaryOperator::DoubleArrow => " ->> ",
1699            BinaryOperator::AtArrow => " @> ",
1700            BinaryOperator::ArrowAt => " <@ ",
1701        }
1702    }
1703
1704    fn gen_expr_list(&mut self, exprs: &[Expr]) {
1705        for (i, expr) in exprs.iter().enumerate() {
1706            if i > 0 {
1707                self.write(", ");
1708            }
1709            self.gen_expr(expr);
1710        }
1711    }
1712
1713    /// Emit `e` in a *condition* (search-condition) position.
1714    ///
1715    /// SQL Server has no native boolean type: a bare boolean expression (a
1716    /// `bit` column, function result, or boolean literal) is not a valid
1717    /// predicate and is rejected with error 4145 ("An expression of non-boolean
1718    /// type specified in a context where a condition is expected"). For the
1719    /// T-SQL family we wrap such a bare boolean as `<e> = 1`, recursing through
1720    /// the logical connectives (`AND`/`OR`/`XOR`/`NOT`/parentheses) so each
1721    /// nested operand is fixed, and lowering a bare boolean literal to `1 = 1`
1722    /// / `1 = 0`. Expressions that are already predicates (comparisons,
1723    /// `IS NULL`, `IN`, `LIKE`, `BETWEEN`, `EXISTS`, …) are emitted unchanged.
1724    ///
1725    /// Oracle has the same restriction for a *bare boolean literal* (`WHERE 1`
1726    /// and `WHERE TRUE` are not valid conditions), so it also lowers
1727    /// `TRUE`/`FALSE` to `1 = 1` / `1 = 0`, recursing through the connectives —
1728    /// but, unlike the T-SQL family, it does NOT wrap other bare scalars as
1729    /// `<e> = 1` (PSQ-2848). Every other dialect delegates straight to
1730    /// `gen_expr`, so their output is byte-for-byte identical.
1731    fn gen_condition(&mut self, e: &Expr) {
1732        let is_tsql = matches!(self.dialect, Some(d) if crate::dialects::is_tsql_family(d));
1733        let is_oracle = matches!(self.dialect, Some(Dialect::Oracle));
1734        if !is_tsql && !is_oracle {
1735            self.gen_expr(e);
1736            return;
1737        }
1738        match e {
1739            // Logical connectives: each operand is itself a condition position.
1740            Expr::BinaryOp { left, op, right }
1741                if matches!(
1742                    op,
1743                    BinaryOperator::And | BinaryOperator::Or | BinaryOperator::Xor
1744                ) =>
1745            {
1746                self.gen_condition(left);
1747                self.write(Self::binary_op_str(op));
1748                self.gen_condition(right);
1749            }
1750            Expr::UnaryOp {
1751                op: UnaryOperator::Not,
1752                expr,
1753            } => {
1754                self.write("NOT ");
1755                self.gen_condition(expr);
1756            }
1757            Expr::Nested(inner) => {
1758                self.write("(");
1759                self.gen_condition(inner);
1760                self.write(")");
1761            }
1762            // Already boolean-typed predicates: emit unchanged.
1763            Expr::BinaryOp {
1764                op:
1765                    BinaryOperator::Eq
1766                    | BinaryOperator::Neq
1767                    | BinaryOperator::Lt
1768                    | BinaryOperator::Gt
1769                    | BinaryOperator::LtEq
1770                    | BinaryOperator::GtEq,
1771                ..
1772            }
1773            | Expr::Between { .. }
1774            | Expr::IsNull { .. }
1775            | Expr::IsBool { .. }
1776            | Expr::InList { .. }
1777            | Expr::InSubquery { .. }
1778            | Expr::Like { .. }
1779            | Expr::ILike { .. }
1780            | Expr::SimilarTo { .. }
1781            | Expr::Exists { .. }
1782            | Expr::AnyOp { .. }
1783            | Expr::AllOp { .. } => self.gen_expr(e),
1784            // Bare boolean literal in a condition position → `1 = 1` / `1 = 0`.
1785            Expr::Boolean(b) => self.write(if *b { "1 = 1" } else { "1 = 0" }),
1786            // Any other bare scalar (column, function, cast, scalar subquery, …)
1787            // is a PostgreSQL boolean here. SQL Server wraps it into a predicate
1788            // (`<e> = 1`); Oracle leaves it unchanged, since the generator makes
1789            // no assumption about non-literal Oracle expressions.
1790            _ => {
1791                self.gen_expr(e);
1792                if is_tsql {
1793                    self.write(" = 1");
1794                }
1795            }
1796        }
1797    }
1798
1799    fn gen_expr(&mut self, expr: &Expr) {
1800        match expr {
1801            Expr::Column {
1802                table,
1803                name,
1804                quote_style,
1805                table_quote_style,
1806            } => {
1807                if let Some(t) = table {
1808                    self.write_quoted(t, *table_quote_style);
1809                    self.write(".");
1810                }
1811                self.write_quoted(name, *quote_style);
1812            }
1813            Expr::Number(n) => self.write(n),
1814            Expr::StringLiteral(s) => {
1815                // TSQL and Oracle require N'...' prefix for string literals containing
1816                // non-ASCII characters to prevent code-page corruption (CR-007).
1817                if matches!(self.dialect, Some(Dialect::Oracle) | Some(Dialect::Tsql))
1818                    && !s.is_ascii()
1819                {
1820                    self.write("N'");
1821                } else {
1822                    self.write("'");
1823                }
1824                self.write(&s.replace('\'', "''"));
1825                self.write("'");
1826            }
1827            Expr::NationalStringLiteral(s) => {
1828                if matches!(self.dialect, Some(Dialect::Oracle) | Some(Dialect::Tsql)) {
1829                    self.write("N'");
1830                } else {
1831                    self.write("'");
1832                }
1833                self.write(&s.replace('\'', "''"));
1834                self.write("'");
1835            }
1836            Expr::Boolean(b) => {
1837                // SQL Server/Fabric have no boolean type and Oracle (<= 21c) has
1838                // no boolean literal, so emit 1/0 for all three in operand and
1839                // projection positions (e.g. `col = TRUE` -> `col = 1`,
1840                // `SELECT TRUE` -> `SELECT 1`). Other dialects keep TRUE/FALSE.
1841                // Bare booleans in a *condition* position are handled by
1842                // `gen_condition`. (Oracle: PSQ-2848)
1843                if matches!(
1844                    self.dialect,
1845                    Some(Dialect::Tsql) | Some(Dialect::Fabric) | Some(Dialect::Oracle)
1846                ) {
1847                    self.write(if *b { "1" } else { "0" });
1848                } else {
1849                    self.write(if *b { "TRUE" } else { "FALSE" });
1850                }
1851            }
1852            Expr::Null => self.write("NULL"),
1853            Expr::Default => self.write_keyword("DEFAULT"),
1854            Expr::Wildcard | Expr::Star => self.write("*"),
1855
1856            Expr::Cube { exprs } => {
1857                self.write_keyword("CUBE");
1858                self.write("(");
1859                self.gen_expr_list(exprs);
1860                self.write(")");
1861            }
1862            Expr::Rollup { exprs } => {
1863                self.write_keyword("ROLLUP");
1864                self.write("(");
1865                self.gen_expr_list(exprs);
1866                self.write(")");
1867            }
1868            Expr::GroupingSets { sets } => {
1869                self.write_keyword("GROUPING SETS");
1870                self.write("(");
1871                self.gen_expr_list(sets);
1872                self.write(")");
1873            }
1874
1875            Expr::BinaryOp { left, op, right } => {
1876                self.gen_expr(left);
1877                self.write(Self::binary_op_str(op));
1878                self.gen_expr(right);
1879            }
1880            Expr::AnyOp { expr, op, right } => {
1881                self.gen_expr(expr);
1882                self.write(Self::binary_op_str(op));
1883                self.write_keyword("ANY");
1884                self.write("(");
1885                if let Expr::Subquery(query) = right.as_ref() {
1886                    self.gen_statement(query);
1887                } else {
1888                    self.gen_expr(right);
1889                }
1890                self.write(")");
1891            }
1892            Expr::AllOp { expr, op, right } => {
1893                self.gen_expr(expr);
1894                self.write(Self::binary_op_str(op));
1895                self.write_keyword("ALL");
1896                self.write("(");
1897                if let Expr::Subquery(query) = right.as_ref() {
1898                    self.gen_statement(query);
1899                } else {
1900                    self.gen_expr(right);
1901                }
1902                self.write(")");
1903            }
1904            Expr::UnaryOp { op, expr } => {
1905                let op_str = match op {
1906                    UnaryOperator::Not => "NOT ",
1907                    UnaryOperator::Minus => "-",
1908                    UnaryOperator::Plus => "+",
1909                    UnaryOperator::BitwiseNot => "~",
1910                };
1911                self.write(op_str);
1912                self.gen_expr(expr);
1913            }
1914            Expr::Function {
1915                name,
1916                args,
1917                distinct,
1918                filter,
1919                over,
1920                order_by,
1921                within_group,
1922            } => {
1923                self.write(name);
1924                self.write("(");
1925                if *distinct {
1926                    self.write_keyword("DISTINCT ");
1927                }
1928                self.gen_expr_list(args);
1929                // Aggregate ORDER BY embedded in the argument list (not WITHIN GROUP).
1930                if !*within_group && !order_by.is_empty() {
1931                    self.write(" ");
1932                    self.write_keyword("ORDER BY ");
1933                    self.gen_order_by_items_inline(order_by);
1934                }
1935                self.write(")");
1936
1937                // WITHIN GROUP (ORDER BY ...) — ordered-set aggregates.
1938                if *within_group && !order_by.is_empty() {
1939                    self.write(" ");
1940                    self.write_keyword("WITHIN GROUP (ORDER BY ");
1941                    self.gen_order_by_items_inline(order_by);
1942                    self.write(")");
1943                }
1944
1945                if let Some(filter_expr) = filter {
1946                    self.write(" ");
1947                    self.write_keyword("FILTER (WHERE ");
1948                    self.gen_expr(filter_expr);
1949                    self.write(")");
1950                }
1951                if let Some(spec) = over {
1952                    self.write(" ");
1953                    self.write_keyword("OVER ");
1954                    if let Some(wref) = &spec.window_ref {
1955                        if spec.partition_by.is_empty()
1956                            && spec.order_by.is_empty()
1957                            && spec.frame.is_none()
1958                        {
1959                            self.write(wref);
1960                        } else {
1961                            self.write("(");
1962                            self.gen_window_spec(spec);
1963                            self.write(")");
1964                        }
1965                    } else {
1966                        self.write("(");
1967                        self.gen_window_spec(spec);
1968                        self.write(")");
1969                    }
1970                }
1971            }
1972            Expr::Between {
1973                expr,
1974                low,
1975                high,
1976                negated,
1977            } => {
1978                self.gen_expr(expr);
1979                if *negated {
1980                    self.write(" ");
1981                    self.write_keyword("NOT");
1982                }
1983                self.write(" ");
1984                self.write_keyword("BETWEEN ");
1985                self.gen_expr(low);
1986                self.write(" ");
1987                self.write_keyword("AND ");
1988                self.gen_expr(high);
1989            }
1990            Expr::InList {
1991                expr,
1992                list,
1993                negated,
1994            } => {
1995                self.gen_expr(expr);
1996                if *negated {
1997                    self.write(" ");
1998                    self.write_keyword("NOT");
1999                }
2000                self.write(" ");
2001                self.write_keyword("IN (");
2002                self.gen_expr_list(list);
2003                self.write(")");
2004            }
2005            Expr::InSubquery {
2006                expr,
2007                subquery,
2008                negated,
2009            } => {
2010                self.gen_expr(expr);
2011                if *negated {
2012                    self.write(" ");
2013                    self.write_keyword("NOT");
2014                }
2015                self.write(" ");
2016                self.write_keyword("IN (");
2017                self.gen_statement(subquery);
2018                self.write(")");
2019            }
2020            Expr::IsNull { expr, negated } => {
2021                self.gen_expr(expr);
2022                if *negated {
2023                    self.write(" ");
2024                    self.write_keyword("IS NOT NULL");
2025                } else {
2026                    self.write(" ");
2027                    self.write_keyword("IS NULL");
2028                }
2029            }
2030            Expr::IsBool {
2031                expr,
2032                value,
2033                negated,
2034            } => {
2035                self.gen_expr(expr);
2036                self.write(" ");
2037                match (negated, value) {
2038                    (false, true) => self.write_keyword("IS TRUE"),
2039                    (false, false) => self.write_keyword("IS FALSE"),
2040                    (true, true) => self.write_keyword("IS NOT TRUE"),
2041                    (true, false) => self.write_keyword("IS NOT FALSE"),
2042                }
2043            }
2044            Expr::Like {
2045                expr,
2046                pattern,
2047                negated,
2048                escape,
2049            } => {
2050                self.gen_expr(expr);
2051                if *negated {
2052                    self.write(" ");
2053                    self.write_keyword("NOT");
2054                }
2055                self.write(" ");
2056                self.write_keyword("LIKE ");
2057                self.gen_expr(pattern);
2058                if let Some(esc) = escape {
2059                    self.write(" ");
2060                    self.write_keyword("ESCAPE ");
2061                    self.gen_expr(esc);
2062                }
2063            }
2064            Expr::ILike {
2065                expr,
2066                pattern,
2067                negated,
2068                escape,
2069            } => {
2070                self.gen_expr(expr);
2071                if *negated {
2072                    self.write(" ");
2073                    self.write_keyword("NOT");
2074                }
2075                self.write(" ");
2076                self.write_keyword("ILIKE ");
2077                self.gen_expr(pattern);
2078                if let Some(esc) = escape {
2079                    self.write(" ");
2080                    self.write_keyword("ESCAPE ");
2081                    self.gen_expr(esc);
2082                }
2083            }
2084            Expr::SimilarTo {
2085                expr,
2086                pattern,
2087                negated,
2088                escape,
2089            } => {
2090                self.gen_expr(expr);
2091                if *negated {
2092                    self.write(" ");
2093                    self.write_keyword("NOT");
2094                }
2095                self.write(" ");
2096                self.write_keyword("SIMILAR TO ");
2097                self.gen_expr(pattern);
2098                if let Some(esc) = escape {
2099                    self.write(" ");
2100                    self.write_keyword("ESCAPE ");
2101                    self.gen_expr(esc);
2102                }
2103            }
2104            Expr::Case {
2105                operand,
2106                when_clauses,
2107                else_clause,
2108            } => {
2109                self.write_keyword("CASE");
2110                if let Some(op) = operand {
2111                    self.write(" ");
2112                    self.gen_expr(op);
2113                }
2114                for (cond, result) in when_clauses {
2115                    self.write(" ");
2116                    self.write_keyword("WHEN ");
2117                    // A simple CASE (`CASE <operand> WHEN <value>`) compares each
2118                    // WHEN value against the operand, so it is NOT a condition
2119                    // position. Only a searched CASE (`CASE WHEN <cond>`) puts a
2120                    // boolean search condition here and needs T-SQL wrapping.
2121                    if operand.is_some() {
2122                        self.gen_expr(cond);
2123                    } else {
2124                        self.gen_condition(cond);
2125                    }
2126                    self.write(" ");
2127                    self.write_keyword("THEN ");
2128                    self.gen_expr(result);
2129                }
2130                if let Some(el) = else_clause {
2131                    self.write(" ");
2132                    self.write_keyword("ELSE ");
2133                    self.gen_expr(el);
2134                }
2135                self.write(" ");
2136                self.write_keyword("END");
2137            }
2138            Expr::Nested(inner) => {
2139                self.write("(");
2140                self.gen_expr(inner);
2141                self.write(")");
2142            }
2143            Expr::Subquery(query) => {
2144                self.write("(");
2145                self.gen_statement(query);
2146                self.write(")");
2147            }
2148            Expr::Exists { subquery, negated } => {
2149                if *negated {
2150                    self.write_keyword("NOT ");
2151                }
2152                self.write_keyword("EXISTS (");
2153                self.gen_statement(subquery);
2154                self.write(")");
2155            }
2156            Expr::Cast { expr, data_type } => {
2157                // ANSI typed string literals: emit DATE 'x' / TIMESTAMP 'x' / TIME 'x'
2158                if let Expr::StringLiteral(val) = expr.as_ref() {
2159                    let ansi_keyword = match data_type {
2160                        DataType::Date => Some("DATE"),
2161                        DataType::Timestamp { .. } => Some("TIMESTAMP"),
2162                        DataType::Time { .. } => Some("TIME"),
2163                        _ => None,
2164                    };
2165                    if let Some(kw) = ansi_keyword {
2166                        // Emit the ANSI typed string literal (DATE 'x' / TIME 'x' /
2167                        // TIMESTAMP 'x') only for dialects that support it. The MySQL
2168                        // family and the T-SQL family (SQL Server, Fabric) do NOT —
2169                        // they must use CAST(... AS DATE|TIME), produced by the
2170                        // fallthrough below. SQL Server rejects ANSI date/time
2171                        // literals with syntax errors 102/156.
2172                        let ansi_typed_literal_unsupported = matches!(
2173                            self.dialect,
2174                            Some(
2175                                Dialect::Mysql
2176                                    | Dialect::Doris
2177                                    | Dialect::SingleStore
2178                                    | Dialect::StarRocks
2179                                    | Dialect::Tsql
2180                                    | Dialect::Fabric
2181                            )
2182                        );
2183                        if !ansi_typed_literal_unsupported {
2184                            self.write_keyword(kw);
2185                            self.write(" '");
2186                            self.write(val);
2187                            self.write("'");
2188                            return;
2189                        }
2190                    }
2191                }
2192
2193                let is_postgres = matches!(
2194                    self.dialect,
2195                    Some(
2196                        Dialect::Postgres
2197                            | Dialect::Redshift
2198                            | Dialect::Materialize
2199                            | Dialect::RisingWave
2200                    )
2201                );
2202                if is_postgres {
2203                    self.gen_expr(expr);
2204                    self.write("::");
2205                    self.gen_data_type(data_type);
2206                } else {
2207                    self.write_keyword("CAST(");
2208                    self.gen_expr(expr);
2209                    self.write(" ");
2210                    self.write_keyword("AS ");
2211                    self.gen_data_type(data_type);
2212                    self.write(")");
2213                }
2214            }
2215            Expr::TryCast { expr, data_type } => {
2216                self.write_keyword("TRY_CAST(");
2217                self.gen_expr(expr);
2218                self.write(" ");
2219                self.write_keyword("AS ");
2220                self.gen_data_type(data_type);
2221                self.write(")");
2222            }
2223            Expr::Extract { field, expr } => {
2224                if matches!(self.dialect, Some(Dialect::Tsql) | Some(Dialect::Fabric)) {
2225                    match field {
2226                        DateTimeField::Epoch => {
2227                            // EXTRACT(EPOCH FROM x) → DATEDIFF(SECOND, '1970-01-01', x)
2228                            self.write_keyword("DATEDIFF(SECOND, '1970-01-01', ");
2229                            self.gen_expr(expr);
2230                            self.write(")");
2231                        }
2232                        DateTimeField::DayOfWeek => {
2233                            // PG DOW = 0(Sun)..6(Sat); T-SQL DATEPART(weekday, ..) = 1..7
2234                            // and is @@DATEFIRST-dependent. Preserve PG numbering in a
2235                            // @@DATEFIRST-independent way. Parentheses are required: T-SQL
2236                            // `%` binds tighter than `+`/`-`.
2237                            self.write_keyword("(DATEPART(WEEKDAY, ");
2238                            self.gen_expr(expr);
2239                            self.write_keyword(") + @@DATEFIRST - 1) % 7");
2240                        }
2241                        _ => {
2242                            self.write_keyword("DATEPART(");
2243                            match field {
2244                                // Postgres spellings that are not valid T-SQL dateparts.
2245                                DateTimeField::DayOfYear => self.write("DAYOFYEAR"),
2246                                // PG WEEK is ISO-8601; plain T-SQL `week` is not.
2247                                DateTimeField::Week => self.write("ISO_WEEK"),
2248                                // YEAR/QUARTER/MONTH/DAY/HOUR/MINUTE/SECOND/MILLI/MICRO/NANO
2249                                // already render to valid dateparts. TIMEZONE/TIMEZONE_HOUR/
2250                                // TIMEZONE_MINUTE have no equivalent and fall through to an
2251                                // invalid name on purpose (fail-safe hard error rather than
2252                                // silently wrong units).
2253                                _ => self.gen_datetime_field(field),
2254                            }
2255                            self.write(", ");
2256                            self.gen_expr(expr);
2257                            self.write(")");
2258                        }
2259                    }
2260                } else if matches!(self.dialect, Some(Dialect::Oracle)) {
2261                    // Oracle EXTRACT accepts only YEAR/MONTH/DAY/HOUR/MINUTE/SECOND/
2262                    // TIMEZONE_*. The Postgres-only fields (QUARTER/WEEK/DOY/DOW) must be
2263                    // rewritten or Oracle rejects the field name (ORA-00907). TO_CHAR
2264                    // returns VARCHAR2, so wrap in TO_NUMBER to preserve Postgres'
2265                    // numeric EXTRACT result type (parity for GROUP BY/ORDER BY/compare).
2266                    match field {
2267                        DateTimeField::Quarter => {
2268                            self.write_keyword("TO_NUMBER(TO_CHAR(");
2269                            self.gen_expr(expr);
2270                            self.write_keyword(", 'Q'))");
2271                        }
2272                        DateTimeField::Week => {
2273                            // PG EXTRACT(WEEK) is ISO-8601 → 'IW' (NOT 'WW', Jan-1-based).
2274                            self.write_keyword("TO_NUMBER(TO_CHAR(");
2275                            self.gen_expr(expr);
2276                            self.write_keyword(", 'IW'))");
2277                        }
2278                        DateTimeField::DayOfYear => {
2279                            self.write_keyword("TO_NUMBER(TO_CHAR(");
2280                            self.gen_expr(expr);
2281                            self.write_keyword(", 'DDD'))");
2282                        }
2283                        DateTimeField::DayOfWeek => {
2284                            // PG DOW = 0(Sun)..6(Sat). TO_CHAR(x,'D') is NLS_TERRITORY-
2285                            // dependent, so anchor on a known Sunday (1970-01-04) and take
2286                            // the day count mod 7 — NLS-independent, preserves PG numbering.
2287                            self.write_keyword("MOD(TRUNC(");
2288                            self.gen_expr(expr);
2289                            self.write_keyword(") - DATE '1970-01-04', 7)");
2290                        }
2291                        _ => {
2292                            // YEAR/MONTH/DAY/HOUR/MINUTE/SECOND/TIMEZONE_HOUR/TIMEZONE_MINUTE
2293                            // are valid Oracle EXTRACT fields — keep the native form. Fields
2294                            // with no Oracle equivalent (EPOCH, MILLI/MICRO/NANO, bare
2295                            // TIMEZONE) fall through to a native EXTRACT Oracle rejects — a
2296                            // fail-safe hard error rather than silently-wrong output.
2297                            self.write_keyword("EXTRACT(");
2298                            self.gen_datetime_field(field);
2299                            self.write(" ");
2300                            self.write_keyword("FROM ");
2301                            self.gen_expr(expr);
2302                            self.write(")");
2303                        }
2304                    }
2305                } else {
2306                    self.write_keyword("EXTRACT(");
2307                    self.gen_datetime_field(field);
2308                    self.write(" ");
2309                    self.write_keyword("FROM ");
2310                    self.gen_expr(expr);
2311                    self.write(")");
2312                }
2313            }
2314            Expr::Interval { value, unit } => {
2315                self.write_keyword("INTERVAL ");
2316                self.gen_expr(value);
2317                if let Some(unit) = unit {
2318                    self.write(" ");
2319                    self.gen_datetime_field(unit);
2320                }
2321            }
2322            Expr::ArrayLiteral(items) => {
2323                self.write_keyword("ARRAY[");
2324                self.gen_expr_list(items);
2325                self.write("]");
2326            }
2327            Expr::Tuple(items) => {
2328                self.write("(");
2329                self.gen_expr_list(items);
2330                self.write(")");
2331            }
2332            Expr::Coalesce(items) => {
2333                self.write_keyword("COALESCE(");
2334                self.gen_expr_list(items);
2335                self.write(")");
2336            }
2337            Expr::If {
2338                condition,
2339                true_val,
2340                false_val,
2341            } => {
2342                self.write_keyword("IF(");
2343                self.gen_expr(condition);
2344                self.write(", ");
2345                self.gen_expr(true_val);
2346                if let Some(fv) = false_val {
2347                    self.write(", ");
2348                    self.gen_expr(fv);
2349                }
2350                self.write(")");
2351            }
2352            Expr::NullIf { expr, r#else } => {
2353                self.write_keyword("NULLIF(");
2354                self.gen_expr(expr);
2355                self.write(", ");
2356                self.gen_expr(r#else);
2357                self.write(")");
2358            }
2359            Expr::Collate { expr, collation } => {
2360                self.gen_expr(expr);
2361                self.write(" ");
2362                self.write_keyword("COLLATE ");
2363                self.write(collation);
2364            }
2365            Expr::Parameter(p) => self.write(p),
2366            Expr::TypeExpr(dt) => self.gen_data_type(dt),
2367            Expr::QualifiedWildcard { table } => {
2368                self.write(table);
2369                self.write(".*");
2370            }
2371            Expr::Alias { expr, name } => {
2372                self.gen_expr(expr);
2373                self.write(" ");
2374                self.write_keyword("AS ");
2375                self.write(name);
2376            }
2377            Expr::ArrayIndex { expr, index } => {
2378                self.gen_expr(expr);
2379                self.write("[");
2380                self.gen_expr(index);
2381                self.write("]");
2382            }
2383            Expr::JsonAccess {
2384                expr,
2385                path,
2386                as_text,
2387            } => {
2388                self.gen_expr(expr);
2389                if *as_text {
2390                    self.write("->>");
2391                } else {
2392                    self.write("->");
2393                }
2394                self.gen_expr(path);
2395            }
2396            Expr::Lambda { params, body } => {
2397                if params.len() == 1 {
2398                    self.write(&params[0]);
2399                } else {
2400                    self.write("(");
2401                    self.write(&params.join(", "));
2402                    self.write(")");
2403                }
2404                self.write(" -> ");
2405                self.gen_expr(body);
2406            }
2407            Expr::TypedFunction { func, filter, over } => {
2408                self.gen_typed_function(func);
2409
2410                if let Some(filter_expr) = filter {
2411                    self.write(" ");
2412                    self.write_keyword("FILTER (WHERE ");
2413                    self.gen_expr(filter_expr);
2414                    self.write(")");
2415                }
2416                if let Some(spec) = over {
2417                    self.write(" ");
2418                    self.write_keyword("OVER ");
2419                    if let Some(wref) = &spec.window_ref {
2420                        if spec.partition_by.is_empty()
2421                            && spec.order_by.is_empty()
2422                            && spec.frame.is_none()
2423                        {
2424                            self.write(wref);
2425                        } else {
2426                            self.write("(");
2427                            self.gen_window_spec(spec);
2428                            self.write(")");
2429                        }
2430                    } else {
2431                        self.write("(");
2432                        self.gen_window_spec(spec);
2433                        self.write(")");
2434                    }
2435                }
2436            }
2437            Expr::Commented { expr, comments } => {
2438                for comment in comments {
2439                    let normalized = self.normalize_comment(comment);
2440                    self.write(&normalized);
2441                    self.write(" ");
2442                }
2443                self.gen_expr(expr);
2444            }
2445        }
2446    }
2447
2448    fn gen_window_spec(&mut self, spec: &WindowSpec) {
2449        if let Some(wref) = &spec.window_ref {
2450            self.write(wref);
2451            if !spec.partition_by.is_empty() || !spec.order_by.is_empty() || spec.frame.is_some() {
2452                self.write(" ");
2453            }
2454        }
2455        if !spec.partition_by.is_empty() {
2456            self.write_keyword("PARTITION BY ");
2457            self.gen_expr_list(&spec.partition_by);
2458        }
2459        if !spec.order_by.is_empty() {
2460            if !spec.partition_by.is_empty() {
2461                self.write(" ");
2462            }
2463            self.write_keyword("ORDER BY ");
2464            for (i, item) in spec.order_by.iter().enumerate() {
2465                if i > 0 {
2466                    self.write(", ");
2467                }
2468                self.gen_expr(&item.expr);
2469                if !item.ascending {
2470                    self.write(" ");
2471                    self.write_keyword("DESC");
2472                }
2473                if let Some(nulls_first) = item.nulls_first {
2474                    if nulls_first {
2475                        self.write(" ");
2476                        self.write_keyword("NULLS FIRST");
2477                    } else {
2478                        self.write(" ");
2479                        self.write_keyword("NULLS LAST");
2480                    }
2481                }
2482            }
2483        }
2484        if let Some(frame) = &spec.frame {
2485            self.write(" ");
2486            self.gen_window_frame(frame);
2487        }
2488    }
2489
2490    fn gen_window_frame(&mut self, frame: &WindowFrame) {
2491        match frame.kind {
2492            WindowFrameKind::Rows => self.write_keyword("ROWS "),
2493            WindowFrameKind::Range => self.write_keyword("RANGE "),
2494            WindowFrameKind::Groups => self.write_keyword("GROUPS "),
2495        }
2496        if let Some(end) = &frame.end {
2497            self.write_keyword("BETWEEN ");
2498            self.gen_window_frame_bound(&frame.start);
2499            self.write(" ");
2500            self.write_keyword("AND ");
2501            self.gen_window_frame_bound(end);
2502        } else {
2503            self.gen_window_frame_bound(&frame.start);
2504        }
2505    }
2506
2507    fn gen_window_frame_bound(&mut self, bound: &WindowFrameBound) {
2508        match bound {
2509            WindowFrameBound::CurrentRow => self.write_keyword("CURRENT ROW"),
2510            WindowFrameBound::Preceding(None) => self.write_keyword("UNBOUNDED PRECEDING"),
2511            WindowFrameBound::Preceding(Some(n)) => {
2512                self.gen_expr(n);
2513                self.write(" ");
2514                self.write_keyword("PRECEDING");
2515            }
2516            WindowFrameBound::Following(None) => self.write_keyword("UNBOUNDED FOLLOWING"),
2517            WindowFrameBound::Following(Some(n)) => {
2518                self.gen_expr(n);
2519                self.write(" ");
2520                self.write_keyword("FOLLOWING");
2521            }
2522        }
2523    }
2524
2525    fn gen_datetime_field(&mut self, field: &DateTimeField) {
2526        let name = match field {
2527            DateTimeField::Year => "YEAR",
2528            DateTimeField::Quarter => "QUARTER",
2529            DateTimeField::Month => "MONTH",
2530            DateTimeField::Week => "WEEK",
2531            DateTimeField::Day => "DAY",
2532            DateTimeField::DayOfWeek => "DOW",
2533            DateTimeField::DayOfYear => "DOY",
2534            DateTimeField::Hour => "HOUR",
2535            DateTimeField::Minute => "MINUTE",
2536            DateTimeField::Second => "SECOND",
2537            DateTimeField::Millisecond => "MILLISECOND",
2538            DateTimeField::Microsecond => "MICROSECOND",
2539            DateTimeField::Nanosecond => "NANOSECOND",
2540            DateTimeField::Epoch => "EPOCH",
2541            DateTimeField::Timezone => "TIMEZONE",
2542            DateTimeField::TimezoneHour => "TIMEZONE_HOUR",
2543            DateTimeField::TimezoneMinute => "TIMEZONE_MINUTE",
2544        };
2545        self.write(name);
2546    }
2547
2548    /// Generate SQL for a typed function expression.
2549    fn gen_typed_function(&mut self, func: &TypedFunction) {
2550        let dialect = self.dialect;
2551        let is_tsql = matches!(dialect, Some(Dialect::Tsql) | Some(Dialect::Fabric));
2552        let is_mysql = matches!(
2553            dialect,
2554            Some(Dialect::Mysql)
2555                | Some(Dialect::SingleStore)
2556                | Some(Dialect::Doris)
2557                | Some(Dialect::StarRocks)
2558        );
2559        let is_bigquery = matches!(dialect, Some(Dialect::BigQuery));
2560        let is_snowflake = matches!(dialect, Some(Dialect::Snowflake));
2561        let is_oracle = matches!(dialect, Some(Dialect::Oracle));
2562        let is_hive_family = matches!(
2563            dialect,
2564            Some(Dialect::Hive) | Some(Dialect::Spark) | Some(Dialect::Databricks)
2565        );
2566
2567        match func {
2568            // ── Date/Time ──────────────────────────────────────────────
2569            TypedFunction::DateAdd {
2570                expr,
2571                interval,
2572                unit,
2573            } => {
2574                if is_tsql || is_snowflake {
2575                    self.write_keyword("DATEADD(");
2576                    if let Some(u) = unit {
2577                        self.gen_datetime_field(u);
2578                    } else {
2579                        self.write_keyword("DAY");
2580                    }
2581                    self.write(", ");
2582                    self.gen_expr(interval);
2583                    self.write(", ");
2584                    self.gen_expr(expr);
2585                    self.write(")");
2586                } else if is_bigquery {
2587                    self.write_keyword("DATE_ADD(");
2588                    self.gen_expr(expr);
2589                    self.write(", ");
2590                    self.write_keyword("INTERVAL ");
2591                    self.gen_expr(interval);
2592                    self.write(" ");
2593                    if let Some(u) = unit {
2594                        self.gen_datetime_field(u);
2595                    } else {
2596                        self.write_keyword("DAY");
2597                    }
2598                    self.write(")");
2599                } else {
2600                    self.write_keyword("DATE_ADD(");
2601                    self.gen_expr(expr);
2602                    self.write(", ");
2603                    self.gen_expr(interval);
2604                    if let Some(u) = unit {
2605                        self.write(", ");
2606                        self.gen_datetime_field(u);
2607                    }
2608                    self.write(")");
2609                }
2610            }
2611            TypedFunction::DateDiff { start, end, unit } => {
2612                if is_tsql || is_snowflake {
2613                    self.write_keyword("DATEDIFF(");
2614                    if let Some(u) = unit {
2615                        self.gen_datetime_field(u);
2616                    } else {
2617                        self.write_keyword("DAY");
2618                    }
2619                    self.write(", ");
2620                    self.gen_expr(start);
2621                    self.write(", ");
2622                    self.gen_expr(end);
2623                    self.write(")");
2624                } else if is_bigquery {
2625                    self.write_keyword("DATE_DIFF(");
2626                    self.gen_expr(end);
2627                    self.write(", ");
2628                    self.gen_expr(start);
2629                    self.write(", ");
2630                    if let Some(u) = unit {
2631                        self.gen_datetime_field(u);
2632                    } else {
2633                        self.write_keyword("DAY");
2634                    }
2635                    self.write(")");
2636                } else {
2637                    self.write_keyword("DATEDIFF(");
2638                    self.gen_expr(start);
2639                    self.write(", ");
2640                    self.gen_expr(end);
2641                    if let Some(u) = unit {
2642                        self.write(", ");
2643                        self.gen_datetime_field(u);
2644                    }
2645                    self.write(")");
2646                }
2647            }
2648            TypedFunction::DateTrunc { unit, expr } => {
2649                if is_tsql {
2650                    self.write_keyword("DATETRUNC(");
2651                    self.gen_datetime_field(unit);
2652                    self.write(", ");
2653                    self.gen_expr(expr);
2654                    self.write(")");
2655                } else if is_oracle {
2656                    self.write_keyword("TRUNC(");
2657                    self.gen_expr(expr);
2658                    self.write(", '");
2659                    self.gen_datetime_field(unit);
2660                    self.write("')");
2661                } else {
2662                    self.write_keyword("DATE_TRUNC(");
2663                    self.write("'");
2664                    self.gen_datetime_field(unit);
2665                    self.write("'");
2666                    self.write(", ");
2667                    self.gen_expr(expr);
2668                    self.write(")");
2669                }
2670            }
2671            TypedFunction::DateSub {
2672                expr,
2673                interval,
2674                unit,
2675            } => {
2676                if is_tsql || is_snowflake {
2677                    self.write_keyword("DATEADD(");
2678                    if let Some(u) = unit {
2679                        self.gen_datetime_field(u);
2680                    } else {
2681                        self.write_keyword("DAY");
2682                    }
2683                    self.write(", -(");
2684                    self.gen_expr(interval);
2685                    self.write("), ");
2686                    self.gen_expr(expr);
2687                    self.write(")");
2688                } else if is_bigquery {
2689                    self.write_keyword("DATE_SUB(");
2690                    self.gen_expr(expr);
2691                    self.write(", ");
2692                    self.write_keyword("INTERVAL ");
2693                    self.gen_expr(interval);
2694                    self.write(" ");
2695                    if let Some(u) = unit {
2696                        self.gen_datetime_field(u);
2697                    } else {
2698                        self.write_keyword("DAY");
2699                    }
2700                    self.write(")");
2701                } else {
2702                    self.write_keyword("DATE_SUB(");
2703                    self.gen_expr(expr);
2704                    self.write(", ");
2705                    self.gen_expr(interval);
2706                    if let Some(u) = unit {
2707                        self.write(", ");
2708                        self.gen_datetime_field(u);
2709                    }
2710                    self.write(")");
2711                }
2712            }
2713            TypedFunction::CurrentDate => {
2714                if is_tsql {
2715                    self.write_keyword("CAST(GETDATE() AS DATE)");
2716                } else if is_mysql || is_hive_family {
2717                    self.write_keyword("CURRENT_DATE()");
2718                } else {
2719                    self.write_keyword("CURRENT_DATE");
2720                }
2721            }
2722            TypedFunction::CurrentTime => {
2723                if is_tsql {
2724                    self.write_keyword("CAST(GETDATE() AS TIME)");
2725                } else if is_mysql || is_hive_family {
2726                    self.write_keyword("CURRENT_TIME()");
2727                } else {
2728                    self.write_keyword("CURRENT_TIME");
2729                }
2730            }
2731            TypedFunction::CurrentTimestamp => {
2732                if is_tsql {
2733                    self.write_keyword("GETDATE()");
2734                } else if is_mysql
2735                    || matches!(
2736                        dialect,
2737                        Some(Dialect::Postgres)
2738                            | Some(Dialect::DuckDb)
2739                            | Some(Dialect::Sqlite)
2740                            | Some(Dialect::Redshift)
2741                    )
2742                {
2743                    self.write_keyword("NOW()");
2744                } else {
2745                    self.write_keyword("CURRENT_TIMESTAMP()");
2746                }
2747            }
2748            TypedFunction::StrToTime { expr, format } => {
2749                if is_mysql {
2750                    self.write_keyword("STR_TO_DATE(");
2751                } else if is_bigquery {
2752                    self.write_keyword("PARSE_TIMESTAMP(");
2753                } else {
2754                    self.write_keyword("TO_TIMESTAMP(");
2755                }
2756                self.gen_expr(expr);
2757                self.write(", ");
2758                self.gen_expr(format);
2759                self.write(")");
2760            }
2761            TypedFunction::TimeToStr { expr, format } => {
2762                if is_mysql || is_hive_family {
2763                    self.write_keyword("DATE_FORMAT(");
2764                } else if is_bigquery {
2765                    self.write_keyword("FORMAT_TIMESTAMP(");
2766                } else if is_tsql {
2767                    self.write_keyword("FORMAT(");
2768                } else {
2769                    self.write_keyword("TO_CHAR(");
2770                }
2771                self.gen_expr(expr);
2772                self.write(", ");
2773                self.gen_expr(format);
2774                self.write(")");
2775            }
2776            TypedFunction::TsOrDsToDate { expr } => {
2777                if is_mysql {
2778                    self.write_keyword("DATE(");
2779                    self.gen_expr(expr);
2780                    self.write(")");
2781                } else {
2782                    self.write_keyword("CAST(");
2783                    self.gen_expr(expr);
2784                    self.write(" ");
2785                    self.write_keyword("AS DATE)");
2786                }
2787            }
2788            TypedFunction::Year { expr } => {
2789                if is_tsql {
2790                    self.write_keyword("YEAR(");
2791                    self.gen_expr(expr);
2792                    self.write(")");
2793                } else {
2794                    self.write_keyword("EXTRACT(YEAR FROM ");
2795                    self.gen_expr(expr);
2796                    self.write(")");
2797                }
2798            }
2799            TypedFunction::Month { expr } => {
2800                if is_tsql {
2801                    self.write_keyword("MONTH(");
2802                    self.gen_expr(expr);
2803                    self.write(")");
2804                } else {
2805                    self.write_keyword("EXTRACT(MONTH FROM ");
2806                    self.gen_expr(expr);
2807                    self.write(")");
2808                }
2809            }
2810            TypedFunction::Day { expr } => {
2811                if is_tsql {
2812                    self.write_keyword("DAY(");
2813                    self.gen_expr(expr);
2814                    self.write(")");
2815                } else {
2816                    self.write_keyword("EXTRACT(DAY FROM ");
2817                    self.gen_expr(expr);
2818                    self.write(")");
2819                }
2820            }
2821
2822            // ── String ─────────────────────────────────────────────────
2823            TypedFunction::Trim {
2824                expr,
2825                trim_type,
2826                trim_chars,
2827            } => {
2828                self.write_keyword("TRIM(");
2829                match trim_type {
2830                    TrimType::Leading => self.write_keyword("LEADING "),
2831                    TrimType::Trailing => self.write_keyword("TRAILING "),
2832                    TrimType::Both => {} // BOTH is default
2833                }
2834                if let Some(chars) = trim_chars {
2835                    self.gen_expr(chars);
2836                    self.write(" ");
2837                    self.write_keyword("FROM ");
2838                }
2839                self.gen_expr(expr);
2840                self.write(")");
2841            }
2842            TypedFunction::Substring {
2843                expr,
2844                start,
2845                length,
2846            } => {
2847                let name = if is_oracle
2848                    || is_hive_family
2849                    || is_mysql
2850                    || matches!(
2851                        dialect,
2852                        Some(Dialect::Sqlite)
2853                            | Some(Dialect::Doris)
2854                            | Some(Dialect::SingleStore)
2855                            | Some(Dialect::StarRocks)
2856                    ) {
2857                    "SUBSTR"
2858                } else {
2859                    "SUBSTRING"
2860                };
2861                self.write_keyword(name);
2862                self.write("(");
2863                self.gen_expr(expr);
2864                self.write(", ");
2865                self.gen_expr(start);
2866                if let Some(l) = length {
2867                    self.write(", ");
2868                    self.gen_expr(l);
2869                }
2870                self.write(")");
2871            }
2872            TypedFunction::Upper { expr } => {
2873                self.write_keyword("UPPER(");
2874                self.gen_expr(expr);
2875                self.write(")");
2876            }
2877            TypedFunction::Lower { expr } => {
2878                self.write_keyword("LOWER(");
2879                self.gen_expr(expr);
2880                self.write(")");
2881            }
2882            TypedFunction::RegexpLike {
2883                expr,
2884                pattern,
2885                flags,
2886            } => {
2887                self.write_keyword("REGEXP_LIKE(");
2888                self.gen_expr(expr);
2889                self.write(", ");
2890                self.gen_expr(pattern);
2891                if let Some(f) = flags {
2892                    self.write(", ");
2893                    self.gen_expr(f);
2894                }
2895                self.write(")");
2896            }
2897            TypedFunction::RegexpExtract {
2898                expr,
2899                pattern,
2900                group_index,
2901            } => {
2902                if is_bigquery || is_hive_family {
2903                    self.write_keyword("REGEXP_EXTRACT(");
2904                } else {
2905                    self.write_keyword("REGEXP_SUBSTR(");
2906                }
2907                self.gen_expr(expr);
2908                self.write(", ");
2909                self.gen_expr(pattern);
2910                if let Some(g) = group_index {
2911                    self.write(", ");
2912                    self.gen_expr(g);
2913                }
2914                self.write(")");
2915            }
2916            TypedFunction::RegexpReplace {
2917                expr,
2918                pattern,
2919                replacement,
2920                flags,
2921            } => {
2922                self.write_keyword("REGEXP_REPLACE(");
2923                self.gen_expr(expr);
2924                self.write(", ");
2925                self.gen_expr(pattern);
2926                self.write(", ");
2927                self.gen_expr(replacement);
2928                if let Some(f) = flags {
2929                    self.write(", ");
2930                    self.gen_expr(f);
2931                }
2932                self.write(")");
2933            }
2934            TypedFunction::ConcatWs { separator, exprs } => {
2935                self.write_keyword("CONCAT_WS(");
2936                self.gen_expr(separator);
2937                for e in exprs {
2938                    self.write(", ");
2939                    self.gen_expr(e);
2940                }
2941                self.write(")");
2942            }
2943            TypedFunction::Split { expr, delimiter } => {
2944                if is_tsql {
2945                    self.write_keyword("STRING_SPLIT(");
2946                } else {
2947                    self.write_keyword("SPLIT(");
2948                }
2949                self.gen_expr(expr);
2950                self.write(", ");
2951                self.gen_expr(delimiter);
2952                self.write(")");
2953            }
2954            TypedFunction::Initcap { expr } => {
2955                self.write_keyword("INITCAP(");
2956                self.gen_expr(expr);
2957                self.write(")");
2958            }
2959            TypedFunction::Length { expr } => {
2960                let name = if is_tsql || is_bigquery || is_snowflake {
2961                    "LEN"
2962                } else {
2963                    "LENGTH"
2964                };
2965                self.write_keyword(name);
2966                self.write("(");
2967                self.gen_expr(expr);
2968                self.write(")");
2969            }
2970            TypedFunction::Replace { expr, from, to } => {
2971                self.write_keyword("REPLACE(");
2972                self.gen_expr(expr);
2973                self.write(", ");
2974                self.gen_expr(from);
2975                self.write(", ");
2976                self.gen_expr(to);
2977                self.write(")");
2978            }
2979            TypedFunction::Reverse { expr } => {
2980                self.write_keyword("REVERSE(");
2981                self.gen_expr(expr);
2982                self.write(")");
2983            }
2984            TypedFunction::Left { expr, n } => {
2985                self.write_keyword("LEFT(");
2986                self.gen_expr(expr);
2987                self.write(", ");
2988                self.gen_expr(n);
2989                self.write(")");
2990            }
2991            TypedFunction::Right { expr, n } => {
2992                self.write_keyword("RIGHT(");
2993                self.gen_expr(expr);
2994                self.write(", ");
2995                self.gen_expr(n);
2996                self.write(")");
2997            }
2998            TypedFunction::Lpad { expr, length, pad } => {
2999                self.write_keyword("LPAD(");
3000                self.gen_expr(expr);
3001                self.write(", ");
3002                self.gen_expr(length);
3003                if let Some(p) = pad {
3004                    self.write(", ");
3005                    self.gen_expr(p);
3006                }
3007                self.write(")");
3008            }
3009            TypedFunction::Rpad { expr, length, pad } => {
3010                self.write_keyword("RPAD(");
3011                self.gen_expr(expr);
3012                self.write(", ");
3013                self.gen_expr(length);
3014                if let Some(p) = pad {
3015                    self.write(", ");
3016                    self.gen_expr(p);
3017                }
3018                self.write(")");
3019            }
3020
3021            // ── Aggregate ──────────────────────────────────────────────
3022            TypedFunction::Count { expr, distinct } => {
3023                self.write_keyword("COUNT(");
3024                if *distinct {
3025                    self.write_keyword("DISTINCT ");
3026                }
3027                self.gen_expr(expr);
3028                self.write(")");
3029            }
3030            TypedFunction::Sum { expr, distinct } => {
3031                self.write_keyword("SUM(");
3032                if *distinct {
3033                    self.write_keyword("DISTINCT ");
3034                }
3035                self.gen_expr(expr);
3036                self.write(")");
3037            }
3038            TypedFunction::Avg { expr, distinct } => {
3039                self.write_keyword("AVG(");
3040                if *distinct {
3041                    self.write_keyword("DISTINCT ");
3042                }
3043                self.gen_expr(expr);
3044                self.write(")");
3045            }
3046            TypedFunction::Min { expr } => {
3047                self.write_keyword("MIN(");
3048                self.gen_expr(expr);
3049                self.write(")");
3050            }
3051            TypedFunction::Max { expr } => {
3052                self.write_keyword("MAX(");
3053                self.gen_expr(expr);
3054                self.write(")");
3055            }
3056            TypedFunction::ArrayAgg { expr, distinct } => {
3057                let name = if matches!(dialect, Some(Dialect::DuckDb)) {
3058                    "LIST"
3059                } else if is_hive_family {
3060                    "COLLECT_LIST"
3061                } else {
3062                    "ARRAY_AGG"
3063                };
3064                self.write_keyword(name);
3065                self.write("(");
3066                if *distinct {
3067                    self.write_keyword("DISTINCT ");
3068                }
3069                self.gen_expr(expr);
3070                self.write(")");
3071            }
3072            TypedFunction::ApproxDistinct { expr } => {
3073                let name = if is_hive_family
3074                    || matches!(
3075                        dialect,
3076                        Some(Dialect::Presto) | Some(Dialect::Trino) | Some(Dialect::Athena)
3077                    ) {
3078                    "APPROX_DISTINCT"
3079                } else {
3080                    "APPROX_COUNT_DISTINCT"
3081                };
3082                self.write_keyword(name);
3083                self.write("(");
3084                self.gen_expr(expr);
3085                self.write(")");
3086            }
3087            TypedFunction::Variance { expr } => {
3088                let name = if is_tsql || is_oracle {
3089                    "VAR"
3090                } else {
3091                    "VARIANCE"
3092                };
3093                self.write_keyword(name);
3094                self.write("(");
3095                self.gen_expr(expr);
3096                self.write(")");
3097            }
3098            TypedFunction::VariancePop { expr } => {
3099                // Population variance: PG VAR_POP -> T-SQL VARP.
3100                let name = if is_tsql { "VARP" } else { "VAR_POP" };
3101                self.write_keyword(name);
3102                self.write("(");
3103                self.gen_expr(expr);
3104                self.write(")");
3105            }
3106            TypedFunction::Stddev { expr } => {
3107                // Sample std-dev: PG STDDEV/STDDEV_SAMP -> T-SQL STDEV.
3108                // (Oracle natively supports STDDEV, so scope to T-SQL only.)
3109                let name = if is_tsql { "STDEV" } else { "STDDEV" };
3110                self.write_keyword(name);
3111                self.write("(");
3112                self.gen_expr(expr);
3113                self.write(")");
3114            }
3115            TypedFunction::StddevPop { expr } => {
3116                // Population std-dev: PG STDDEV_POP -> T-SQL STDEVP.
3117                // (Oracle natively supports STDDEV_POP, so scope to T-SQL only.)
3118                let name = if is_tsql { "STDEVP" } else { "STDDEV_POP" };
3119                self.write_keyword(name);
3120                self.write("(");
3121                self.gen_expr(expr);
3122                self.write(")");
3123            }
3124            TypedFunction::GroupConcat {
3125                exprs,
3126                separator,
3127                order_by,
3128                distinct,
3129            } => {
3130                self.gen_group_concat(exprs, separator.as_deref(), order_by, *distinct);
3131            }
3132
3133            // ── Array ──────────────────────────────────────────────────
3134            TypedFunction::ArrayConcat { arrays } => {
3135                let name = if matches!(
3136                    dialect,
3137                    Some(Dialect::Postgres) | Some(Dialect::Redshift) | Some(Dialect::DuckDb)
3138                ) {
3139                    "ARRAY_CAT"
3140                } else {
3141                    "ARRAY_CONCAT"
3142                };
3143                self.write_keyword(name);
3144                self.write("(");
3145                self.gen_expr_list(arrays);
3146                self.write(")");
3147            }
3148            TypedFunction::ArrayContains { array, element } => {
3149                self.write_keyword("ARRAY_CONTAINS(");
3150                self.gen_expr(array);
3151                self.write(", ");
3152                self.gen_expr(element);
3153                self.write(")");
3154            }
3155            TypedFunction::ArraySize { expr } => {
3156                let name = if matches!(dialect, Some(Dialect::Postgres) | Some(Dialect::Redshift)) {
3157                    "ARRAY_LENGTH"
3158                } else if is_hive_family {
3159                    "SIZE"
3160                } else {
3161                    "ARRAY_SIZE"
3162                };
3163                self.write_keyword(name);
3164                self.write("(");
3165                self.gen_expr(expr);
3166                self.write(")");
3167            }
3168            TypedFunction::Explode { expr } => {
3169                self.write_keyword("EXPLODE(");
3170                self.gen_expr(expr);
3171                self.write(")");
3172            }
3173            TypedFunction::GenerateSeries { start, stop, step } => {
3174                self.write_keyword("GENERATE_SERIES(");
3175                self.gen_expr(start);
3176                self.write(", ");
3177                self.gen_expr(stop);
3178                if let Some(s) = step {
3179                    self.write(", ");
3180                    self.gen_expr(s);
3181                }
3182                self.write(")");
3183            }
3184            TypedFunction::Flatten { expr } => {
3185                self.write_keyword("FLATTEN(");
3186                self.gen_expr(expr);
3187                self.write(")");
3188            }
3189
3190            // ── JSON ───────────────────────────────────────────────────
3191            TypedFunction::JSONExtract { expr, path } => {
3192                if is_tsql {
3193                    self.write_keyword("JSON_VALUE(");
3194                } else {
3195                    self.write_keyword("JSON_EXTRACT(");
3196                }
3197                self.gen_expr(expr);
3198                self.write(", ");
3199                self.gen_expr(path);
3200                self.write(")");
3201            }
3202            TypedFunction::JSONExtractScalar { expr, path } => {
3203                if is_bigquery {
3204                    self.write_keyword("JSON_EXTRACT_SCALAR(");
3205                } else if is_tsql {
3206                    self.write_keyword("JSON_VALUE(");
3207                } else {
3208                    self.write_keyword("JSON_EXTRACT_SCALAR(");
3209                }
3210                self.gen_expr(expr);
3211                self.write(", ");
3212                self.gen_expr(path);
3213                self.write(")");
3214            }
3215            TypedFunction::ParseJSON { expr } => {
3216                if is_snowflake {
3217                    self.write_keyword("PARSE_JSON(");
3218                } else if is_bigquery {
3219                    self.write_keyword("JSON_PARSE(");
3220                } else {
3221                    self.write_keyword("PARSE_JSON(");
3222                }
3223                self.gen_expr(expr);
3224                self.write(")");
3225            }
3226            TypedFunction::JSONFormat { expr } => {
3227                if is_bigquery {
3228                    self.write_keyword("TO_JSON_STRING(");
3229                } else {
3230                    self.write_keyword("JSON_FORMAT(");
3231                }
3232                self.gen_expr(expr);
3233                self.write(")");
3234            }
3235
3236            // ── Window ─────────────────────────────────────────────────
3237            TypedFunction::RowNumber => self.write_keyword("ROW_NUMBER()"),
3238            TypedFunction::Rank => self.write_keyword("RANK()"),
3239            TypedFunction::DenseRank => self.write_keyword("DENSE_RANK()"),
3240            TypedFunction::NTile { n } => {
3241                self.write_keyword("NTILE(");
3242                self.gen_expr(n);
3243                self.write(")");
3244            }
3245            TypedFunction::Lead {
3246                expr,
3247                offset,
3248                default,
3249            } => {
3250                self.write_keyword("LEAD(");
3251                self.gen_expr(expr);
3252                if let Some(o) = offset {
3253                    self.write(", ");
3254                    self.gen_expr(o);
3255                }
3256                if let Some(d) = default {
3257                    self.write(", ");
3258                    self.gen_expr(d);
3259                }
3260                self.write(")");
3261            }
3262            TypedFunction::Lag {
3263                expr,
3264                offset,
3265                default,
3266            } => {
3267                self.write_keyword("LAG(");
3268                self.gen_expr(expr);
3269                if let Some(o) = offset {
3270                    self.write(", ");
3271                    self.gen_expr(o);
3272                }
3273                if let Some(d) = default {
3274                    self.write(", ");
3275                    self.gen_expr(d);
3276                }
3277                self.write(")");
3278            }
3279            TypedFunction::FirstValue { expr } => {
3280                self.write_keyword("FIRST_VALUE(");
3281                self.gen_expr(expr);
3282                self.write(")");
3283            }
3284            TypedFunction::LastValue { expr } => {
3285                self.write_keyword("LAST_VALUE(");
3286                self.gen_expr(expr);
3287                self.write(")");
3288            }
3289
3290            // ── Math ───────────────────────────────────────────────────
3291            TypedFunction::Abs { expr } => {
3292                self.write_keyword("ABS(");
3293                self.gen_expr(expr);
3294                self.write(")");
3295            }
3296            TypedFunction::Ceil { expr } => {
3297                let name = if is_tsql { "CEILING" } else { "CEIL" };
3298                self.write_keyword(name);
3299                self.write("(");
3300                self.gen_expr(expr);
3301                self.write(")");
3302            }
3303            TypedFunction::Floor { expr } => {
3304                self.write_keyword("FLOOR(");
3305                self.gen_expr(expr);
3306                self.write(")");
3307            }
3308            TypedFunction::Round { expr, decimals } => {
3309                self.write_keyword("ROUND(");
3310                self.gen_expr(expr);
3311                if let Some(d) = decimals {
3312                    self.write(", ");
3313                    self.gen_expr(d);
3314                }
3315                self.write(")");
3316            }
3317            TypedFunction::Log { expr, base } => {
3318                if let Some(b) = base {
3319                    self.write_keyword("LOG(");
3320                    if matches!(dialect, Some(Dialect::Postgres) | Some(Dialect::DuckDb)) {
3321                        // Postgres: LOG(base, expr)
3322                        self.gen_expr(b);
3323                        self.write(", ");
3324                        self.gen_expr(expr);
3325                    } else {
3326                        // Most: LOG(expr, base)
3327                        self.gen_expr(expr);
3328                        self.write(", ");
3329                        self.gen_expr(b);
3330                    }
3331                    self.write(")");
3332                } else {
3333                    // LOG(expr) — ln in Postgres, log10 in most others
3334                    self.write_keyword("LOG(");
3335                    self.gen_expr(expr);
3336                    self.write(")");
3337                }
3338            }
3339            TypedFunction::Ln { expr } => {
3340                self.write_keyword("LN(");
3341                self.gen_expr(expr);
3342                self.write(")");
3343            }
3344            TypedFunction::Pow { base, exponent } => {
3345                let name = if is_tsql || is_oracle { "POWER" } else { "POW" };
3346                self.write_keyword(name);
3347                self.write("(");
3348                self.gen_expr(base);
3349                self.write(", ");
3350                self.gen_expr(exponent);
3351                self.write(")");
3352            }
3353            TypedFunction::Sqrt { expr } => {
3354                self.write_keyword("SQRT(");
3355                self.gen_expr(expr);
3356                self.write(")");
3357            }
3358            TypedFunction::Greatest { exprs } => {
3359                self.write_keyword("GREATEST(");
3360                self.gen_expr_list(exprs);
3361                self.write(")");
3362            }
3363            TypedFunction::Least { exprs } => {
3364                self.write_keyword("LEAST(");
3365                self.gen_expr_list(exprs);
3366                self.write(")");
3367            }
3368            TypedFunction::Mod { left, right } => {
3369                self.write_keyword("MOD(");
3370                self.gen_expr(left);
3371                self.write(", ");
3372                self.gen_expr(right);
3373                self.write(")");
3374            }
3375
3376            // ── Conversion ─────────────────────────────────────────────
3377            TypedFunction::Hex { expr } => {
3378                let name = if matches!(
3379                    dialect,
3380                    Some(Dialect::Presto) | Some(Dialect::Trino) | Some(Dialect::Athena)
3381                ) {
3382                    "TO_HEX"
3383                } else {
3384                    "HEX"
3385                };
3386                self.write_keyword(name);
3387                self.write("(");
3388                self.gen_expr(expr);
3389                self.write(")");
3390            }
3391            TypedFunction::Unhex { expr } => {
3392                let name = if matches!(
3393                    dialect,
3394                    Some(Dialect::Presto) | Some(Dialect::Trino) | Some(Dialect::Athena)
3395                ) {
3396                    "FROM_HEX"
3397                } else {
3398                    "UNHEX"
3399                };
3400                self.write_keyword(name);
3401                self.write("(");
3402                self.gen_expr(expr);
3403                self.write(")");
3404            }
3405            TypedFunction::Md5 { expr } => {
3406                self.write_keyword("MD5(");
3407                self.gen_expr(expr);
3408                self.write(")");
3409            }
3410            TypedFunction::Sha { expr } => {
3411                let name = if is_mysql { "SHA1" } else { "SHA" };
3412                self.write_keyword(name);
3413                self.write("(");
3414                self.gen_expr(expr);
3415                self.write(")");
3416            }
3417            TypedFunction::Sha2 { expr, bit_length } => {
3418                self.write_keyword("SHA2(");
3419                self.gen_expr(expr);
3420                self.write(", ");
3421                self.gen_expr(bit_length);
3422                self.write(")");
3423            }
3424        }
3425    }
3426
3427    /// Emit a `GROUP_CONCAT` / `STRING_AGG` / `LISTAGG` expression
3428    /// appropriately for the active dialect.
3429    fn gen_group_concat(
3430        &mut self,
3431        exprs: &[Expr],
3432        separator: Option<&Expr>,
3433        order_by: &[OrderByItem],
3434        distinct: bool,
3435    ) {
3436        let dialect = self.dialect;
3437        let is_sqlite = matches!(dialect, Some(Dialect::Sqlite));
3438        let is_string_agg = matches!(
3439            dialect,
3440            Some(Dialect::Postgres)
3441                | Some(Dialect::Redshift)
3442                | Some(Dialect::BigQuery)
3443                | Some(Dialect::Tsql)
3444                | Some(Dialect::Fabric)
3445                | Some(Dialect::DuckDb)
3446        );
3447        let is_listagg = matches!(dialect, Some(Dialect::Oracle) | Some(Dialect::Snowflake));
3448
3449        if is_string_agg {
3450            // STRING_AGG(expr, sep [ORDER BY ...])
3451            self.write_keyword("STRING_AGG(");
3452            if distinct {
3453                self.write_keyword("DISTINCT ");
3454            }
3455            self.gen_group_concat_exprs(exprs);
3456            self.write(", ");
3457            match separator {
3458                Some(s) => self.gen_expr(s),
3459                None => self.write("','"),
3460            }
3461            if !order_by.is_empty() {
3462                self.write(" ");
3463                self.gen_group_concat_order_by(order_by);
3464            }
3465            self.write(")");
3466        } else if is_listagg {
3467            // LISTAGG(expr, sep) WITHIN GROUP (ORDER BY ...)
3468            self.write_keyword("LISTAGG(");
3469            if distinct {
3470                self.write_keyword("DISTINCT ");
3471            }
3472            self.gen_group_concat_exprs(exprs);
3473            self.write(", ");
3474            match separator {
3475                Some(s) => self.gen_expr(s),
3476                None => self.write("','"),
3477            }
3478            self.write(")");
3479            if !order_by.is_empty() {
3480                self.write(" ");
3481                self.write_keyword("WITHIN GROUP");
3482                self.write(" (");
3483                self.gen_group_concat_order_by(order_by);
3484                self.write(")");
3485            }
3486        } else if is_sqlite {
3487            // SQLite: GROUP_CONCAT(expr[, sep]). No DISTINCT/ORDER BY support;
3488            // they are dropped on output since the target dialect lacks them.
3489            self.write_keyword("GROUP_CONCAT(");
3490            self.gen_group_concat_exprs(exprs);
3491            if let Some(s) = separator {
3492                self.write(", ");
3493                self.gen_expr(s);
3494            }
3495            self.write(")");
3496        } else {
3497            // MySQL family (and default): full GROUP_CONCAT grammar.
3498            self.write_keyword("GROUP_CONCAT(");
3499            if distinct {
3500                self.write_keyword("DISTINCT ");
3501            }
3502            self.gen_group_concat_exprs(exprs);
3503            if !order_by.is_empty() {
3504                self.write(" ");
3505                self.gen_group_concat_order_by(order_by);
3506            }
3507            if let Some(s) = separator {
3508                self.write(" ");
3509                self.write_keyword("SEPARATOR");
3510                self.write(" ");
3511                self.gen_expr(s);
3512            }
3513            self.write(")");
3514        }
3515    }
3516
3517    fn gen_group_concat_exprs(&mut self, exprs: &[Expr]) {
3518        for (i, e) in exprs.iter().enumerate() {
3519            if i > 0 {
3520                self.write(", ");
3521            }
3522            self.gen_expr(e);
3523        }
3524    }
3525
3526    fn gen_group_concat_order_by(&mut self, order_by: &[OrderByItem]) {
3527        self.write_keyword("ORDER BY");
3528        self.write(" ");
3529        for (i, item) in order_by.iter().enumerate() {
3530            if i > 0 {
3531                self.write(", ");
3532            }
3533            self.gen_expr(&item.expr);
3534            if !item.ascending {
3535                self.write(" ");
3536                self.write_keyword("DESC");
3537            }
3538            if let Some(nulls_first) = item.nulls_first {
3539                self.write(" ");
3540                self.write_keyword(if nulls_first {
3541                    "NULLS FIRST"
3542                } else {
3543                    "NULLS LAST"
3544                });
3545            }
3546        }
3547    }
3548}
3549
3550impl Default for Generator {
3551    fn default() -> Self {
3552        Self::new()
3553    }
3554}
3555
3556#[cfg(test)]
3557mod tests {
3558    use super::*;
3559    use crate::parser::Parser;
3560
3561    fn roundtrip(sql: &str) -> String {
3562        let stmt = Parser::new(sql).unwrap().parse_statement().unwrap();
3563        let mut g = Generator::new();
3564        g.generate(&stmt)
3565    }
3566
3567    #[test]
3568    fn test_select_roundtrip() {
3569        assert_eq!(roundtrip("SELECT a, b FROM t"), "SELECT a, b FROM t");
3570    }
3571
3572    #[test]
3573    fn test_select_where() {
3574        assert_eq!(
3575            roundtrip("SELECT x FROM t WHERE x > 10"),
3576            "SELECT x FROM t WHERE x > 10"
3577        );
3578    }
3579
3580    #[test]
3581    fn test_select_wildcard() {
3582        assert_eq!(roundtrip("SELECT * FROM users"), "SELECT * FROM users");
3583    }
3584
3585    #[test]
3586    fn test_insert_values() {
3587        assert_eq!(
3588            roundtrip("INSERT INTO t (a, b) VALUES (1, 'hello')"),
3589            "INSERT INTO t (a, b) VALUES (1, 'hello')"
3590        );
3591    }
3592
3593    #[test]
3594    fn test_delete() {
3595        assert_eq!(
3596            roundtrip("DELETE FROM users WHERE id = 1"),
3597            "DELETE FROM users WHERE id = 1"
3598        );
3599    }
3600
3601    #[test]
3602    fn test_join() {
3603        assert_eq!(
3604            roundtrip("SELECT a.id, b.name FROM a INNER JOIN b ON a.id = b.a_id"),
3605            "SELECT a.id, b.name FROM a INNER JOIN b ON a.id = b.a_id"
3606        );
3607    }
3608
3609    #[test]
3610    fn test_create_table() {
3611        assert_eq!(
3612            roundtrip("CREATE TABLE users (id INT NOT NULL, name VARCHAR(255), email TEXT)"),
3613            "CREATE TABLE users (id INT NOT NULL, name VARCHAR(255), email TEXT)"
3614        );
3615    }
3616
3617    #[test]
3618    fn test_cte_roundtrip() {
3619        let sql = "WITH cte AS (SELECT 1 AS x) SELECT x FROM cte";
3620        assert_eq!(
3621            roundtrip(sql),
3622            "WITH cte AS (SELECT 1 AS x) SELECT x FROM cte"
3623        );
3624    }
3625
3626    #[test]
3627    fn test_union_roundtrip() {
3628        let sql = "SELECT 1 UNION ALL SELECT 2";
3629        assert_eq!(roundtrip(sql), "SELECT 1 UNION ALL SELECT 2");
3630    }
3631
3632    #[test]
3633    fn test_cast_roundtrip() {
3634        assert_eq!(
3635            roundtrip("SELECT CAST(x AS INT) FROM t"),
3636            "SELECT CAST(x AS INT) FROM t"
3637        );
3638    }
3639
3640    #[test]
3641    fn test_exists_roundtrip() {
3642        assert_eq!(
3643            roundtrip("SELECT * FROM t WHERE EXISTS (SELECT 1 FROM t2)"),
3644            "SELECT * FROM t WHERE EXISTS (SELECT 1 FROM t2)"
3645        );
3646    }
3647
3648    #[test]
3649    fn test_extract_roundtrip() {
3650        assert_eq!(
3651            roundtrip("SELECT EXTRACT(YEAR FROM created_at) FROM t"),
3652            "SELECT EXTRACT(YEAR FROM created_at) FROM t"
3653        );
3654    }
3655
3656    #[test]
3657    fn test_window_function_roundtrip() {
3658        assert_eq!(
3659            roundtrip("SELECT ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) FROM emp"),
3660            "SELECT ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) FROM emp"
3661        );
3662    }
3663
3664    #[test]
3665    fn test_subquery_from_roundtrip() {
3666        assert_eq!(
3667            roundtrip("SELECT * FROM (SELECT 1 AS x) AS sub"),
3668            "SELECT * FROM (SELECT 1 AS x) AS sub"
3669        );
3670    }
3671
3672    #[test]
3673    fn test_in_subquery_roundtrip() {
3674        assert_eq!(
3675            roundtrip("SELECT * FROM t WHERE id IN (SELECT id FROM t2)"),
3676            "SELECT * FROM t WHERE id IN (SELECT id FROM t2)"
3677        );
3678    }
3679
3680    // ═══════════════════════════════════════════════════════════════
3681    // Pretty-print tests
3682    // ═══════════════════════════════════════════════════════════════
3683
3684    fn pretty_print(sql: &str) -> String {
3685        let stmt = Parser::new(sql).unwrap().parse_statement().unwrap();
3686        let mut g = Generator::pretty();
3687        g.generate(&stmt)
3688    }
3689
3690    #[test]
3691    fn test_pretty_simple_select() {
3692        assert_eq!(
3693            pretty_print("SELECT a, b, c FROM t"),
3694            "SELECT\n  a,\n  b,\n  c\nFROM\n  t"
3695        );
3696    }
3697
3698    #[test]
3699    fn test_pretty_select_where() {
3700        assert_eq!(
3701            pretty_print("SELECT a FROM t WHERE a > 1"),
3702            "SELECT\n  a\nFROM\n  t\nWHERE\n  a > 1"
3703        );
3704    }
3705
3706    #[test]
3707    fn test_pretty_select_group_by_having() {
3708        assert_eq!(
3709            pretty_print("SELECT a, COUNT(*) FROM t GROUP BY a HAVING COUNT(*) > 1"),
3710            "SELECT\n  a,\n  COUNT(*)\nFROM\n  t\nGROUP BY\n  a\nHAVING\n  COUNT(*) > 1"
3711        );
3712    }
3713
3714    #[test]
3715    fn test_pretty_select_order_by_limit() {
3716        assert_eq!(
3717            pretty_print("SELECT a FROM t ORDER BY a DESC LIMIT 10"),
3718            "SELECT\n  a\nFROM\n  t\nORDER BY\n  a DESC\nLIMIT 10"
3719        );
3720    }
3721
3722    #[test]
3723    fn test_pretty_join() {
3724        assert_eq!(
3725            pretty_print("SELECT a.id, b.name FROM a INNER JOIN b ON a.id = b.a_id"),
3726            "SELECT\n  a.id,\n  b.name\nFROM\n  a\nINNER JOIN\n  b\n  ON a.id = b.a_id"
3727        );
3728    }
3729
3730    #[test]
3731    fn test_pretty_cte() {
3732        assert_eq!(
3733            pretty_print("WITH cte AS (SELECT 1 AS x) SELECT x FROM cte"),
3734            "WITH cte AS (\n  SELECT\n    1 AS x\n)\nSELECT\n  x\nFROM\n  cte"
3735        );
3736    }
3737
3738    #[test]
3739    fn test_pretty_union() {
3740        assert_eq!(
3741            pretty_print("SELECT 1 UNION ALL SELECT 2"),
3742            "SELECT\n  1\nUNION ALL\nSELECT\n  2"
3743        );
3744    }
3745
3746    #[test]
3747    fn test_pretty_insert() {
3748        assert_eq!(
3749            pretty_print("INSERT INTO t (a, b) VALUES (1, 'hello'), (2, 'world')"),
3750            "INSERT INTO t (a, b)\nVALUES\n  (1, 'hello'),\n  (2, 'world')"
3751        );
3752    }
3753
3754    #[test]
3755    fn test_pretty_update() {
3756        assert_eq!(
3757            pretty_print("UPDATE t SET a = 1, b = 2 WHERE c = 3"),
3758            "UPDATE t\nSET\n  a = 1,\n  b = 2\nWHERE\n  c = 3"
3759        );
3760    }
3761
3762    #[test]
3763    fn test_pretty_delete() {
3764        assert_eq!(
3765            pretty_print("DELETE FROM t WHERE id = 1"),
3766            "DELETE FROM t\nWHERE\n  id = 1"
3767        );
3768    }
3769
3770    #[test]
3771    fn test_pretty_create_table() {
3772        assert_eq!(
3773            pretty_print("CREATE TABLE t (id INT NOT NULL, name VARCHAR(255), email TEXT)"),
3774            "CREATE TABLE t (\n  id INT NOT NULL,\n  name VARCHAR(255),\n  email TEXT\n)"
3775        );
3776    }
3777
3778    #[test]
3779    fn test_pretty_complex_query() {
3780        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";
3781        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";
3782        assert_eq!(pretty_print(sql), expected);
3783    }
3784
3785    #[test]
3786    fn test_pretty_select_distinct() {
3787        assert_eq!(
3788            pretty_print("SELECT DISTINCT a, b FROM t"),
3789            "SELECT DISTINCT\n  a,\n  b\nFROM\n  t"
3790        );
3791    }
3792}