Skip to main content

sqlglot_rust/generator/
sql_generator.rs

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