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