Skip to main content

kumosql_sql/
printer.rs

1//! Deterministic SQL printer for the syntax tree.
2//!
3//! [`to_sql`] and [`query_to_sql`] print clause per line with two-space indentation;
4//! [`to_sql_compact`] and [`expr_to_sql`] print on one line. Parsing printed SQL gives back an
5//! equal tree: parentheses are added only where precedence needs them, and every parenthesis the
6//! source had is kept as an [`Expr::Nested`].
7
8use crate::ast::*;
9use crate::token::{escape_identifier, escape_string, is_reserved_keyword, QuoteStyle};
10
11/// A statement, laid out clause per line.
12pub fn to_sql(statement: &Statement) -> String {
13    Printer { pretty: true }.statement(statement, 0)
14}
15
16/// A statement on one line.
17pub fn to_sql_compact(statement: &Statement) -> String {
18    Printer { pretty: false }.statement(statement, 0)
19}
20
21/// Statements separated by `;` and a blank line, ending with `;`.
22pub fn statements_to_sql(statements: &[Statement]) -> String {
23    let printer = Printer { pretty: true };
24    statements
25        .iter()
26        .map(|s| format!("{};", printer.statement(s, 0)))
27        .collect::<Vec<_>>()
28        .join("\n\n")
29}
30
31/// A query, laid out clause per line.
32pub fn query_to_sql(query: &Query) -> String {
33    Printer { pretty: true }.query(query, 0)
34}
35
36/// A query on one line.
37pub fn query_to_sql_compact(query: &Query) -> String {
38    Printer { pretty: false }.query(query, 0)
39}
40
41/// An expression on one line.
42pub fn expr_to_sql(expr: &Expr) -> String {
43    Printer { pretty: false }.expr(expr, 0)
44}
45
46/// A data type (`ARRAY<STRUCT<a INT64>>`).
47pub fn data_type_to_sql(data_type: &DataType) -> String {
48    Printer { pretty: false }.data_type(data_type)
49}
50
51/// A table factor on one line (`` `p.d.t` AS x ``).
52pub fn table_factor_to_sql(factor: &TableFactor) -> String {
53    Printer { pretty: false }.table_factor(factor, 0)
54}
55
56fn is_plain_word(value: &str) -> bool {
57    let mut chars = value.chars();
58    matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')
59        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
60}
61
62/// An identifier as GoogleSQL needs it written: quoted when it was, or when it must be.
63pub fn ident_to_sql(ident: &Ident) -> String {
64    if ident.quoted || !is_plain_word(&ident.value) || is_reserved_keyword(&ident.value) {
65        format!("`{}`", escape_identifier(&ident.value))
66    } else {
67        ident.value.clone()
68    }
69}
70
71fn path_part(ident: &Ident) -> String {
72    if ident.quoted
73        || ident.value.is_empty()
74        || !ident
75            .value
76            .chars()
77            .all(|c| c.is_ascii_alphanumeric() || c == '_')
78    {
79        format!("`{}`", escape_identifier(&ident.value))
80    } else {
81        ident.value.clone()
82    }
83}
84
85fn table_first_part(ident: &Ident) -> String {
86    let dashed = !ident.quoted
87        && ident.value.contains('-')
88        && ident
89            .value
90            .chars()
91            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
92        && ident.value.starts_with(|c: char| c.is_ascii_alphabetic());
93    if dashed {
94        ident.value.clone()
95    } else {
96        ident_to_sql(ident)
97    }
98}
99
100/// A dotted name.
101pub fn object_name_to_sql(name: &ObjectName) -> String {
102    name.0
103        .iter()
104        .enumerate()
105        .map(|(i, part)| {
106            if i == 0 {
107                table_first_part(part)
108            } else {
109                path_part(part)
110            }
111        })
112        .collect::<Vec<_>>()
113        .join(".")
114}
115
116fn function_name(name: &ObjectName) -> String {
117    name.0
118        .iter()
119        .map(|part| {
120            if part.quoted
121                || !part
122                    .value
123                    .chars()
124                    .all(|c| c.is_ascii_alphanumeric() || c == '_')
125            {
126                format!("`{}`", escape_identifier(&part.value))
127            } else {
128                part.value.clone()
129            }
130        })
131        .collect::<Vec<_>>()
132        .join(".")
133}
134
135fn quote_string(value: &str) -> String {
136    format!("'{}'", escape_string(value, QuoteStyle::Single))
137}
138
139fn raw_ok(value: &str, quote: QuoteStyle) -> bool {
140    if !quote.is_triple() && (value.contains('\n') || value.contains('\r')) {
141        return false;
142    }
143    if quote.is_triple() && value.ends_with(quote.quote_char()) {
144        return false;
145    }
146    // an odd run of backslashes at the end would escape the closing quote
147    let trailing = value.chars().rev().take_while(|c| *c == '\\').count();
148    if trailing % 2 == 1 {
149        return false;
150    }
151    let delimiter = quote.delimiter().as_bytes();
152    let bytes = value.as_bytes();
153    let mut index = 0;
154    while index < bytes.len() {
155        if bytes[index] == b'\\' {
156            index += 2;
157            continue;
158        }
159        if bytes[index..].starts_with(delimiter) {
160            return false;
161        }
162        index += 1;
163    }
164    true
165}
166
167/// Escape bytes for a `b'...'` literal.
168fn escape_bytes(value: &[u8]) -> String {
169    let mut out = String::new();
170    for &b in value {
171        match b {
172            b'\\' => out.push_str("\\\\"),
173            b'\'' => out.push_str("\\'"),
174            b'\n' => out.push_str("\\n"),
175            b'\t' => out.push_str("\\t"),
176            b'\r' => out.push_str("\\r"),
177            0x20..=0x7e => out.push(b as char),
178            _ => out.push_str(&format!("\\x{b:02x}")),
179        }
180    }
181    out
182}
183
184/// Precedence of an expression as an operand: 255 for anything that never needs parentheses.
185fn precedence(expr: &Expr) -> u8 {
186    match expr {
187        Expr::BinaryOp { op, .. } => op.precedence(),
188        Expr::IsNull { .. }
189        | Expr::IsBool { .. }
190        | Expr::IsDistinctFrom { .. }
191        | Expr::InList { .. }
192        | Expr::InSubquery { .. }
193        | Expr::InUnnest { .. }
194        | Expr::Between { .. }
195        | Expr::Like { .. }
196        | Expr::LikeQuantified { .. } => COMPARISON_PRECEDENCE,
197        Expr::UnaryOp {
198            op: UnaryOperator::Not,
199            ..
200        } => NOT_PRECEDENCE,
201        Expr::UnaryOp { .. } => UNARY_PRECEDENCE,
202        Expr::Lambda { .. } | Expr::NamedArg { .. } => 0,
203        _ => 255,
204    }
205}
206
207struct Printer {
208    pretty: bool,
209}
210
211impl Printer {
212    fn nl(&self, indent: usize) -> String {
213        if self.pretty {
214            format!("\n{}", "  ".repeat(indent))
215        } else {
216            " ".to_string()
217        }
218    }
219
220    /// `(query)` with the query indented one level deeper.
221    fn subquery(&self, query: &Query, indent: usize) -> String {
222        if self.pretty {
223            format!(
224                "({}{}{})",
225                self.nl(indent + 1),
226                self.query(query, indent + 1),
227                self.nl(indent)
228            )
229        } else {
230            format!("({})", self.query(query, indent))
231        }
232    }
233
234    fn list<T>(&self, items: &[T], f: impl Fn(&T) -> String) -> String {
235        items.iter().map(f).collect::<Vec<_>>().join(", ")
236    }
237
238    // ------------------------------------------------------------------ statements
239
240    fn block(&self, statements: &[Statement], indent: usize) -> String {
241        let mut out = String::new();
242        for s in statements {
243            out.push_str(&self.nl(indent + 1));
244            out.push_str(&self.statement(s, indent + 1));
245            out.push(';');
246        }
247        out
248    }
249
250    fn label(&self, label: &Option<Ident>) -> String {
251        label
252            .as_ref()
253            .map(|l| format!("{}: ", ident_to_sql(l)))
254            .unwrap_or_default()
255    }
256
257    fn end_label(&self, label: &Option<Ident>) -> String {
258        label
259            .as_ref()
260            .map(|l| format!(" {}", ident_to_sql(l)))
261            .unwrap_or_default()
262    }
263
264    fn options(&self, options: &[SqlOption], indent: usize) -> String {
265        format!(
266            "OPTIONS({})",
267            self.list(options, |o| format!(
268                "{} = {}",
269                path_part(&o.name),
270                self.expr(&o.value, indent)
271            ))
272        )
273    }
274
275    fn statement(&self, statement: &Statement, i: usize) -> String {
276        match statement {
277            Statement::Query(q) => self.query(q, i),
278            Statement::CreateTable(c) => self.create_table(c, i),
279            Statement::CreateView(c) => {
280                let mut out = String::from("CREATE ");
281                if c.or_replace {
282                    out.push_str("OR REPLACE ");
283                }
284                out.push_str(if c.materialized {
285                    "MATERIALIZED VIEW "
286                } else {
287                    "VIEW "
288                });
289                if c.if_not_exists {
290                    out.push_str("IF NOT EXISTS ");
291                }
292                out.push_str(&object_name_to_sql(&c.name));
293                if !c.columns.is_empty() {
294                    out.push_str(&format!(
295                        " ({})",
296                        self.list(&c.columns, |col| {
297                            let mut s = ident_to_sql(&col.name);
298                            if !col.options.is_empty() {
299                                s.push(' ');
300                                s.push_str(&self.options(&col.options, i));
301                            }
302                            s
303                        })
304                    ));
305                }
306                if let Some(p) = &c.partition_by {
307                    out.push_str(&format!("{}PARTITION BY {}", self.nl(i), self.expr(p, i)));
308                }
309                if !c.cluster_by.is_empty() {
310                    out.push_str(&format!(
311                        "{}CLUSTER BY {}",
312                        self.nl(i),
313                        self.list(&c.cluster_by, |e| self.expr(e, i))
314                    ));
315                }
316                if !c.options.is_empty() {
317                    out.push_str(&self.nl(i));
318                    out.push_str(&self.options(&c.options, i));
319                }
320                out.push_str(&format!(" AS{}{}", self.nl(i), self.query(&c.query, i)));
321                out
322            }
323            Statement::CreateFunction(f) => self.create_function(f, i),
324            Statement::CreateTableFunction(f) => {
325                let mut out = String::from("CREATE ");
326                if f.or_replace {
327                    out.push_str("OR REPLACE ");
328                }
329                if f.temporary {
330                    out.push_str("TEMP ");
331                }
332                out.push_str("TABLE FUNCTION ");
333                if f.if_not_exists {
334                    out.push_str("IF NOT EXISTS ");
335                }
336                out.push_str(&object_name_to_sql(&f.name));
337                out.push_str(&self.function_params(&f.params));
338                if let Some(returns) = &f.returns {
339                    out.push_str(&format!(" RETURNS TABLE<{}>", self.struct_fields(returns)));
340                }
341                if !f.options.is_empty() {
342                    out.push(' ');
343                    out.push_str(&self.options(&f.options, i));
344                }
345                out.push_str(&format!(" AS{}{}", self.nl(i), self.query(&f.query, i)));
346                out
347            }
348            Statement::CreateProcedure(p) => {
349                let mut out = String::from("CREATE ");
350                if p.or_replace {
351                    out.push_str("OR REPLACE ");
352                }
353                out.push_str("PROCEDURE ");
354                if p.if_not_exists {
355                    out.push_str("IF NOT EXISTS ");
356                }
357                out.push_str(&object_name_to_sql(&p.name));
358                out.push_str(&format!(
359                    "({})",
360                    self.list(&p.params, |param| {
361                        let mode = match param.mode {
362                            Some(ParamMode::In) => "IN ",
363                            Some(ParamMode::Out) => "OUT ",
364                            Some(ParamMode::InOut) => "INOUT ",
365                            None => "",
366                        };
367                        format!(
368                            "{mode}{} {}",
369                            ident_to_sql(&param.name),
370                            self.param_type(&param.param_type)
371                        )
372                    })
373                ));
374                if !p.options.is_empty() {
375                    out.push(' ');
376                    out.push_str(&self.options(&p.options, i));
377                }
378                out.push_str(&format!("{}BEGIN", self.nl(i)));
379                out.push_str(&self.block(&p.body, i));
380                if let Some(handler) = &p.exception {
381                    out.push_str(&format!("{}EXCEPTION WHEN ERROR THEN", self.nl(i)));
382                    out.push_str(&self.block(handler, i));
383                }
384                out.push_str(&format!("{}END", self.nl(i)));
385                out
386            }
387            Statement::CreateSchema(s) => {
388                let mut out = String::from("CREATE SCHEMA ");
389                if s.if_not_exists {
390                    out.push_str("IF NOT EXISTS ");
391                }
392                out.push_str(&object_name_to_sql(&s.name));
393                if let Some(c) = &s.default_collate {
394                    out.push_str(&format!(" DEFAULT COLLATE {}", self.expr(c, i)));
395                }
396                if !s.options.is_empty() {
397                    out.push(' ');
398                    out.push_str(&self.options(&s.options, i));
399                }
400                out
401            }
402            Statement::Insert(ins) => {
403                let mut out = format!("INSERT INTO {}", object_name_to_sql(&ins.table));
404                if !ins.columns.is_empty() {
405                    out.push_str(&format!(" ({})", self.list(&ins.columns, ident_to_sql)));
406                }
407                match &ins.source {
408                    InsertSource::Values(rows) => {
409                        out.push_str(&format!("{}VALUES ", self.nl(i)));
410                        out.push_str(&self.list(rows, |row| {
411                            format!("({})", self.list(row, |e| self.expr(e, i)))
412                        }));
413                    }
414                    InsertSource::Query(q) => {
415                        out.push_str(&self.nl(i));
416                        out.push_str(&self.query(q, i));
417                    }
418                }
419                out
420            }
421            Statement::Update(u) => {
422                let mut out = format!("UPDATE {}", object_name_to_sql(&u.table));
423                if let Some(a) = &u.alias {
424                    out.push_str(&format!(" AS {}", ident_to_sql(a)));
425                }
426                out.push_str(&format!(
427                    "{}SET {}",
428                    self.nl(i),
429                    self.assignments(&u.assignments, i)
430                ));
431                if !u.from.is_empty() {
432                    out.push_str(&format!(
433                        "{}FROM {}",
434                        self.nl(i),
435                        self.table_list(&u.from, i)
436                    ));
437                }
438                if let Some(w) = &u.selection {
439                    out.push_str(&format!("{}WHERE {}", self.nl(i), self.expr(w, i)));
440                }
441                out
442            }
443            Statement::Delete(d) => {
444                let mut out = format!("DELETE FROM {}", object_name_to_sql(&d.table));
445                if let Some(a) = &d.alias {
446                    out.push_str(&format!(" AS {}", ident_to_sql(a)));
447                }
448                if let Some(w) = &d.selection {
449                    out.push_str(&format!("{}WHERE {}", self.nl(i), self.expr(w, i)));
450                }
451                out
452            }
453            Statement::Merge(m) => {
454                let mut out = format!("MERGE INTO {}", object_name_to_sql(&m.target));
455                if let Some(a) = &m.target_alias {
456                    out.push_str(&format!(" AS {}", ident_to_sql(a)));
457                }
458                out.push_str(&format!(
459                    "{}USING {}",
460                    self.nl(i),
461                    self.table_factor(&m.source, i)
462                ));
463                out.push_str(&format!("{}ON {}", self.nl(i), self.expr(&m.on, i)));
464                for clause in &m.clauses {
465                    out.push_str(&self.nl(i));
466                    out.push_str(match clause.kind {
467                        MergeMatch::Matched => "WHEN MATCHED",
468                        MergeMatch::NotMatchedByTarget if clause.explicit_by_target => {
469                            "WHEN NOT MATCHED BY TARGET"
470                        }
471                        MergeMatch::NotMatchedByTarget => "WHEN NOT MATCHED",
472                        MergeMatch::NotMatchedBySource => "WHEN NOT MATCHED BY SOURCE",
473                    });
474                    if let Some(c) = &clause.condition {
475                        out.push_str(&format!(" AND {}", self.expr(c, i)));
476                    }
477                    out.push_str(" THEN ");
478                    match &clause.action {
479                        MergeAction::Update(a) => {
480                            out.push_str(&format!("UPDATE SET {}", self.assignments(a, i)))
481                        }
482                        MergeAction::Delete => out.push_str("DELETE"),
483                        MergeAction::Insert {
484                            columns,
485                            values,
486                            row,
487                        } => {
488                            out.push_str("INSERT");
489                            if !columns.is_empty() {
490                                out.push_str(&format!(" ({})", self.list(columns, ident_to_sql)));
491                            }
492                            if *row {
493                                out.push_str(" ROW");
494                            } else {
495                                out.push_str(&format!(
496                                    " VALUES ({})",
497                                    self.list(values, |e| self.expr(e, i))
498                                ));
499                            }
500                        }
501                    }
502                }
503                out
504            }
505            Statement::Drop(d) => {
506                let mut out = format!("DROP {} ", d.object_type.keyword());
507                if d.if_exists {
508                    out.push_str("IF EXISTS ");
509                }
510                out.push_str(&object_name_to_sql(&d.name));
511                match d.cascade {
512                    Some(true) => out.push_str(" CASCADE"),
513                    Some(false) => out.push_str(" RESTRICT"),
514                    None => {}
515                }
516                out
517            }
518            Statement::AlterTable(a) => {
519                let mut out = format!("ALTER {} ", a.object_type.keyword());
520                if a.if_exists {
521                    out.push_str("IF EXISTS ");
522                }
523                out.push_str(&object_name_to_sql(&a.name));
524                out.push(' ');
525                out.push_str(&self.list(&a.actions, |action| self.alter_action(action, i)));
526                out
527            }
528            Statement::Truncate { name } => format!("TRUNCATE TABLE {}", object_name_to_sql(name)),
529            Statement::Declare {
530                names,
531                data_type,
532                default,
533            } => {
534                let mut out = format!("DECLARE {}", self.list(names, ident_to_sql));
535                if let Some(t) = data_type {
536                    out.push(' ');
537                    out.push_str(&self.data_type(t));
538                }
539                if let Some(d) = default {
540                    out.push_str(&format!(" DEFAULT {}", self.expr(d, i)));
541                }
542                out
543            }
544            Statement::Set { targets, value } => {
545                let target = if targets.len() == 1 {
546                    self.expr(&targets[0], i)
547                } else {
548                    format!("({})", self.list(targets, |e| self.expr(e, i)))
549                };
550                format!("SET {target} = {}", self.expr(value, i))
551            }
552            Statement::BeginEnd {
553                label,
554                body,
555                exception,
556            } => {
557                let mut out = format!("{}BEGIN", self.label(label));
558                out.push_str(&self.block(body, i));
559                if let Some(handler) = exception {
560                    out.push_str(&format!("{}EXCEPTION WHEN ERROR THEN", self.nl(i)));
561                    out.push_str(&self.block(handler, i));
562                }
563                out.push_str(&format!("{}END{}", self.nl(i), self.end_label(label)));
564                out
565            }
566            Statement::If {
567                branches,
568                else_branch,
569            } => {
570                let mut out = String::new();
571                for (index, branch) in branches.iter().enumerate() {
572                    if index == 0 {
573                        out.push_str("IF ");
574                    } else {
575                        out.push_str(&format!("{}ELSEIF ", self.nl(i)));
576                    }
577                    out.push_str(&format!("{} THEN", self.expr(&branch.condition, i)));
578                    out.push_str(&self.block(&branch.body, i));
579                }
580                if let Some(e) = else_branch {
581                    out.push_str(&format!("{}ELSE", self.nl(i)));
582                    out.push_str(&self.block(e, i));
583                }
584                out.push_str(&format!("{}END IF", self.nl(i)));
585                out
586            }
587            Statement::Case {
588                operand,
589                branches,
590                else_branch,
591            } => {
592                let mut out = String::from("CASE");
593                if let Some(o) = operand {
594                    out.push_str(&format!(" {}", self.expr(o, i)));
595                }
596                for branch in branches {
597                    out.push_str(&format!(
598                        "{}WHEN {} THEN",
599                        self.nl(i),
600                        self.expr(&branch.condition, i)
601                    ));
602                    out.push_str(&self.block(&branch.body, i));
603                }
604                if let Some(e) = else_branch {
605                    out.push_str(&format!("{}ELSE", self.nl(i)));
606                    out.push_str(&self.block(e, i));
607                }
608                out.push_str(&format!("{}END CASE", self.nl(i)));
609                out
610            }
611            Statement::Loop { label, body } => format!(
612                "{}LOOP{}{}END LOOP{}",
613                self.label(label),
614                self.block(body, i),
615                self.nl(i),
616                self.end_label(label)
617            ),
618            Statement::While {
619                label,
620                condition,
621                body,
622            } => format!(
623                "{}WHILE {} DO{}{}END WHILE{}",
624                self.label(label),
625                self.expr(condition, i),
626                self.block(body, i),
627                self.nl(i),
628                self.end_label(label)
629            ),
630            Statement::ForIn {
631                label,
632                variable,
633                query,
634                body,
635            } => format!(
636                "{}FOR {} IN {} DO{}{}END FOR{}",
637                self.label(label),
638                ident_to_sql(variable),
639                self.subquery(query, i),
640                self.block(body, i),
641                self.nl(i),
642                self.end_label(label)
643            ),
644            Statement::Repeat { label, body, until } => format!(
645                "{}REPEAT{}{}UNTIL {}{}END REPEAT{}",
646                self.label(label),
647                self.block(body, i),
648                self.nl(i),
649                self.expr(until, i),
650                self.nl(i),
651                self.end_label(label)
652            ),
653            Statement::Control { kind, label } => {
654                let word = match kind {
655                    ControlKind::Break => "BREAK",
656                    ControlKind::Leave => "LEAVE",
657                    ControlKind::Continue => "CONTINUE",
658                    ControlKind::Iterate => "ITERATE",
659                };
660                format!("{word}{}", self.end_label(label))
661            }
662            Statement::Return => "RETURN".to_string(),
663            Statement::Raise { message } => match message {
664                Some(m) => format!("RAISE USING MESSAGE = {}", self.expr(m, i)),
665                None => "RAISE".to_string(),
666            },
667            Statement::Call { procedure, args } => {
668                format!(
669                    "CALL {}({})",
670                    object_name_to_sql(procedure),
671                    self.list(args, |e| self.expr(e, i))
672                )
673            }
674            Statement::ExecuteImmediate { sql, into, using } => {
675                let mut out = format!("EXECUTE IMMEDIATE {}", self.expr(sql, i));
676                if !into.is_empty() {
677                    out.push_str(&format!(" INTO {}", self.list(into, ident_to_sql)));
678                }
679                if !using.is_empty() {
680                    out.push_str(&format!(
681                        " USING {}",
682                        self.list(using, |u| match &u.alias {
683                            Some(a) => format!("{} AS {}", self.expr(&u.expr, i), ident_to_sql(a)),
684                            None => self.expr(&u.expr, i),
685                        })
686                    ));
687                }
688                out
689            }
690            Statement::Assert {
691                condition,
692                description,
693            } => {
694                let mut out = format!("ASSERT {}", self.expr(condition, i));
695                if let Some(d) = description {
696                    out.push_str(&format!(" AS {}", self.expr(d, i)));
697                }
698                out
699            }
700            Statement::Transaction(kind) => match kind {
701                TransactionKind::Begin => "BEGIN TRANSACTION".to_string(),
702                TransactionKind::Commit => "COMMIT TRANSACTION".to_string(),
703                TransactionKind::Rollback => "ROLLBACK TRANSACTION".to_string(),
704            },
705            Statement::ExportData(e) => {
706                let mut out = String::from("EXPORT DATA");
707                if let Some(c) = &e.connection {
708                    out.push_str(&format!(" WITH CONNECTION {}", object_name_to_sql(c)));
709                }
710                if !e.options.is_empty() {
711                    out.push(' ');
712                    out.push_str(&self.options(&e.options, i));
713                }
714                out.push_str(&format!(" AS{}{}", self.nl(i), self.query(&e.query, i)));
715                out
716            }
717            Statement::LoadData(l) => {
718                let mut out = format!(
719                    "LOAD DATA {} ",
720                    if l.overwrite { "OVERWRITE" } else { "INTO" }
721                );
722                if l.temporary {
723                    out.push_str("TEMP TABLE ");
724                }
725                out.push_str(&object_name_to_sql(&l.table));
726                if !l.rest.is_empty() {
727                    out.push(' ');
728                    out.push_str(&l.rest);
729                }
730                out
731            }
732            Statement::Raw(text) => text.clone(),
733        }
734    }
735
736    fn assignments(&self, assignments: &[Assignment], i: usize) -> String {
737        self.list(assignments, |a| {
738            let target = a
739                .target
740                .iter()
741                .enumerate()
742                .map(|(n, p)| {
743                    if n == 0 {
744                        ident_to_sql(p)
745                    } else {
746                        path_part(p)
747                    }
748                })
749                .collect::<Vec<_>>()
750                .join(".");
751            format!("{target} = {}", self.expr(&a.value, i))
752        })
753    }
754
755    fn create_table(&self, c: &CreateTable, i: usize) -> String {
756        let mut out = String::from("CREATE ");
757        if c.or_replace {
758            out.push_str("OR REPLACE ");
759        }
760        if c.temporary {
761            out.push_str("TEMP ");
762        }
763        out.push_str(match c.kind {
764            TableKind::Table => "TABLE ",
765            TableKind::External => "EXTERNAL TABLE ",
766            TableKind::Snapshot => "SNAPSHOT TABLE ",
767        });
768        if c.if_not_exists {
769            out.push_str("IF NOT EXISTS ");
770        }
771        out.push_str(&object_name_to_sql(&c.name));
772        if !c.columns.is_empty() || !c.constraints.is_empty() {
773            let mut parts: Vec<String> = c
774                .columns
775                .iter()
776                .map(|col| self.column_def(col, i))
777                .collect();
778            parts.extend(c.constraints.iter().map(|k| self.constraint(k)));
779            if self.pretty {
780                out.push_str(" (");
781                for (n, part) in parts.iter().enumerate() {
782                    out.push_str(&self.nl(i + 1));
783                    out.push_str(part);
784                    if n + 1 < parts.len() {
785                        out.push(',');
786                    }
787                }
788                out.push_str(&format!("{})", self.nl(i)));
789            } else {
790                out.push_str(&format!(" ({})", parts.join(", ")));
791            }
792        }
793        if let Some(copy) = &c.copy {
794            let word = match copy.kind {
795                CopyKind::Like => "LIKE",
796                CopyKind::Copy => "COPY",
797                CopyKind::Clone => "CLONE",
798            };
799            out.push_str(&format!(" {word} {}", object_name_to_sql(&copy.source)));
800            if let Some(t) = &copy.system_time {
801                out.push_str(&format!(" FOR SYSTEM_TIME AS OF {}", self.expr(t, i)));
802            }
803        }
804        if let Some(c) = &c.default_collate {
805            out.push_str(&format!(
806                "{}DEFAULT COLLATE {}",
807                self.nl(i),
808                self.expr(c, i)
809            ));
810        }
811        if let Some(p) = &c.partition_by {
812            out.push_str(&format!("{}PARTITION BY {}", self.nl(i), self.expr(p, i)));
813        }
814        if !c.cluster_by.is_empty() {
815            out.push_str(&format!(
816                "{}CLUSTER BY {}",
817                self.nl(i),
818                self.list(&c.cluster_by, |e| self.expr(e, i))
819            ));
820        }
821        if let Some(conn) = &c.with_connection {
822            out.push_str(&format!(
823                "{}WITH CONNECTION {}",
824                self.nl(i),
825                object_name_to_sql(conn)
826            ));
827        }
828        if !c.options.is_empty() {
829            out.push_str(&self.nl(i));
830            out.push_str(&self.options(&c.options, i));
831        }
832        if let Some(q) = &c.query {
833            out.push_str(&format!(" AS{}{}", self.nl(i), self.query(q, i)));
834        }
835        out
836    }
837
838    fn column_def(&self, col: &ColumnDef, i: usize) -> String {
839        let mut out = format!(
840            "{} {}",
841            ident_to_sql(&col.name),
842            self.data_type(&col.data_type)
843        );
844        if let Some(c) = &col.collate {
845            out.push_str(&format!(" COLLATE {}", self.expr(c, i)));
846        }
847        if let Some(d) = &col.default {
848            out.push_str(&format!(" DEFAULT {}", self.expr(d, i)));
849        }
850        if col.not_null {
851            out.push_str(" NOT NULL");
852        }
853        if col.primary_key {
854            out.push_str(" PRIMARY KEY NOT ENFORCED");
855        }
856        if !col.options.is_empty() {
857            out.push(' ');
858            out.push_str(&self.options(&col.options, i));
859        }
860        out
861    }
862
863    fn constraint(&self, constraint: &TableConstraint) -> String {
864        match constraint {
865            TableConstraint::PrimaryKey {
866                columns,
867                not_enforced,
868            } => format!(
869                "PRIMARY KEY ({}){}",
870                self.list(columns, ident_to_sql),
871                if *not_enforced { " NOT ENFORCED" } else { "" }
872            ),
873            TableConstraint::ForeignKey {
874                name,
875                columns,
876                foreign_table,
877                referred_columns,
878                not_enforced,
879            } => {
880                let mut out = String::new();
881                if let Some(n) = name {
882                    out.push_str(&format!("CONSTRAINT {} ", ident_to_sql(n)));
883                }
884                out.push_str(&format!(
885                    "FOREIGN KEY ({}) REFERENCES {}({}){}",
886                    self.list(columns, ident_to_sql),
887                    object_name_to_sql(foreign_table),
888                    self.list(referred_columns, ident_to_sql),
889                    if *not_enforced { " NOT ENFORCED" } else { "" }
890                ));
891                out
892            }
893        }
894    }
895
896    fn alter_action(&self, action: &AlterAction, i: usize) -> String {
897        match action {
898            AlterAction::AddColumn {
899                if_not_exists,
900                column,
901            } => format!(
902                "ADD COLUMN {}{}",
903                if *if_not_exists { "IF NOT EXISTS " } else { "" },
904                self.column_def(column, i)
905            ),
906            AlterAction::DropColumn { if_exists, name } => {
907                format!(
908                    "DROP COLUMN {}{}",
909                    if *if_exists { "IF EXISTS " } else { "" },
910                    ident_to_sql(name)
911                )
912            }
913            AlterAction::RenameTo(name) => format!("RENAME TO {}", object_name_to_sql(name)),
914            AlterAction::RenameColumn {
915                if_exists,
916                from,
917                to,
918            } => format!(
919                "RENAME COLUMN {}{} TO {}",
920                if *if_exists { "IF EXISTS " } else { "" },
921                ident_to_sql(from),
922                ident_to_sql(to)
923            ),
924            AlterAction::SetOptions(o) => format!("SET {}", self.options(o, i)),
925            AlterAction::SetDefaultCollate(e) => format!("SET DEFAULT COLLATE {}", self.expr(e, i)),
926            AlterAction::AlterColumn {
927                if_exists,
928                name,
929                action,
930            } => {
931                let what = match action {
932                    AlterColumnAction::SetOptions(o) => format!("SET {}", self.options(o, i)),
933                    AlterColumnAction::DropNotNull => "DROP NOT NULL".to_string(),
934                    AlterColumnAction::SetDataType(t) => {
935                        format!("SET DATA TYPE {}", self.data_type(t))
936                    }
937                    AlterColumnAction::SetDefault(e) => format!("SET DEFAULT {}", self.expr(e, i)),
938                    AlterColumnAction::DropDefault => "DROP DEFAULT".to_string(),
939                };
940                format!(
941                    "ALTER COLUMN {}{} {what}",
942                    if *if_exists { "IF EXISTS " } else { "" },
943                    ident_to_sql(name)
944                )
945            }
946        }
947    }
948
949    fn param_type(&self, param_type: &ParamType) -> String {
950        match param_type {
951            ParamType::Type(t) => self.data_type(t),
952            ParamType::AnyType => "ANY TYPE".to_string(),
953            ParamType::Table(fields) => format!("TABLE<{}>", self.struct_fields(fields)),
954            ParamType::AnyTable => "ANY TABLE".to_string(),
955        }
956    }
957
958    fn function_params(&self, params: &[FunctionParam]) -> String {
959        format!(
960            "({})",
961            self.list(params, |p| {
962                let mut s = format!(
963                    "{} {}",
964                    ident_to_sql(&p.name),
965                    self.param_type(&p.param_type)
966                );
967                if p.not_aggregate {
968                    s.push_str(" NOT AGGREGATE");
969                }
970                s
971            })
972        )
973    }
974
975    fn create_function(&self, f: &CreateFunction, i: usize) -> String {
976        let mut out = String::from("CREATE ");
977        if f.or_replace {
978            out.push_str("OR REPLACE ");
979        }
980        if f.temporary {
981            out.push_str("TEMP ");
982        }
983        if f.aggregate {
984            out.push_str("AGGREGATE ");
985        }
986        out.push_str("FUNCTION ");
987        if f.if_not_exists {
988            out.push_str("IF NOT EXISTS ");
989        }
990        out.push_str(&object_name_to_sql(&f.name));
991        out.push_str(&self.function_params(&f.params));
992        if let Some(r) = &f.returns {
993            out.push_str(&format!(" RETURNS {}", self.data_type(r)));
994        }
995        match f.determinism {
996            Some(true) => out.push_str(" DETERMINISTIC"),
997            Some(false) => out.push_str(" NOT DETERMINISTIC"),
998            None => {}
999        }
1000        if let Some(l) = &f.language {
1001            out.push_str(&format!(" LANGUAGE {}", ident_to_sql(l)));
1002        }
1003        if let FunctionBody::Remote(c) = &f.body {
1004            out.push_str(&format!(
1005                " REMOTE WITH CONNECTION {}",
1006                object_name_to_sql(c)
1007            ));
1008        }
1009        if !f.options.is_empty() {
1010            out.push(' ');
1011            out.push_str(&self.options(&f.options, i));
1012        }
1013        match &f.body {
1014            FunctionBody::Expr(e) => out.push_str(&format!(" AS ({})", self.expr(e, i))),
1015            FunctionBody::Code(code) => out.push_str(&format!(" AS {}", self.literal(code, i))),
1016            FunctionBody::Remote(_) | FunctionBody::None => {}
1017        }
1018        out
1019    }
1020
1021    // ------------------------------------------------------------------ queries
1022
1023    fn query(&self, q: &Query, i: usize) -> String {
1024        let mut out = String::new();
1025        if let Some(with) = &q.with {
1026            out.push_str("WITH ");
1027            if with.recursive {
1028                out.push_str("RECURSIVE ");
1029            }
1030            let ctes: Vec<String> = with
1031                .ctes
1032                .iter()
1033                .map(|cte| {
1034                    format!(
1035                        "{} AS {}",
1036                        ident_to_sql(&cte.name),
1037                        self.subquery(&cte.query, i)
1038                    )
1039                })
1040                .collect();
1041            out.push_str(&ctes.join(&format!(",{}", self.nl(i))));
1042            out.push_str(&self.nl(i));
1043        }
1044        out.push_str(&self.set_expr(&q.body, i));
1045        if !q.order_by.is_empty() {
1046            out.push_str(&format!(
1047                "{}ORDER BY {}",
1048                self.nl(i),
1049                self.order_by(&q.order_by, i)
1050            ));
1051        }
1052        if let Some(limit) = &q.limit {
1053            out.push_str(&self.nl(i));
1054            out.push_str(&self.limit(limit, i));
1055        }
1056        for pipe in &q.pipes {
1057            out.push_str(&format!("{}|> {}", self.nl(i), self.pipe(pipe, i)));
1058        }
1059        out
1060    }
1061
1062    fn limit(&self, limit: &Limit, i: usize) -> String {
1063        let mut out = format!("LIMIT {}", self.expr(&limit.count, i));
1064        if let Some(o) = &limit.offset {
1065            out.push_str(&format!(" OFFSET {}", self.expr(o, i)));
1066        }
1067        out
1068    }
1069
1070    fn set_op_keyword(
1071        &self,
1072        op: SetOperator,
1073        quantifier: SetQuantifier,
1074        mode: Option<SetOpMode>,
1075        corresponding: &Option<Corresponding>,
1076    ) -> String {
1077        let mut out = String::new();
1078        match mode {
1079            Some(SetOpMode::Full) => out.push_str("FULL "),
1080            Some(SetOpMode::Left) => out.push_str("LEFT "),
1081            Some(SetOpMode::Inner) => out.push_str("INNER "),
1082            None => {}
1083        }
1084        out.push_str(op.keyword());
1085        match quantifier {
1086            SetQuantifier::All => out.push_str(" ALL"),
1087            SetQuantifier::Distinct => out.push_str(" DISTINCT"),
1088            SetQuantifier::None => {}
1089        }
1090        match corresponding {
1091            Some(Corresponding::ByName(on)) => {
1092                out.push_str(" BY NAME");
1093                if !on.is_empty() {
1094                    out.push_str(&format!(" ON ({})", self.list(on, ident_to_sql)));
1095                }
1096            }
1097            Some(Corresponding::Corresponding { strict, by }) => {
1098                if *strict {
1099                    out.push_str(" STRICT");
1100                }
1101                out.push_str(" CORRESPONDING");
1102                if !by.is_empty() {
1103                    out.push_str(&format!(" BY ({})", self.list(by, ident_to_sql)));
1104                }
1105            }
1106            None => {}
1107        }
1108        out
1109    }
1110
1111    fn set_expr(&self, body: &SetExpr, i: usize) -> String {
1112        match body {
1113            SetExpr::Select(s) => self.select(s, i),
1114            SetExpr::Query(q) => self.subquery(q, i),
1115            SetExpr::SetOperation {
1116                op,
1117                quantifier,
1118                mode,
1119                corresponding,
1120                left,
1121                right,
1122            } => {
1123                let right_text = match right.as_ref() {
1124                    // a set operation on the right was parenthesized in the source
1125                    SetExpr::SetOperation { .. } => format!("({})", self.set_expr(right, i)),
1126                    other => self.set_expr(other, i),
1127                };
1128                format!(
1129                    "{}{}{}{}{}",
1130                    self.set_expr(left, i),
1131                    self.nl(i),
1132                    self.set_op_keyword(*op, *quantifier, *mode, corresponding),
1133                    self.nl(i),
1134                    right_text
1135                )
1136            }
1137            SetExpr::From(from) => format!("FROM {}", self.table_list(from, i)),
1138        }
1139    }
1140
1141    fn select(&self, s: &Select, i: usize) -> String {
1142        let mut out = String::from("SELECT");
1143        if s.distinct {
1144            out.push_str(" DISTINCT");
1145        }
1146        match s.select_as {
1147            Some(SelectAs::Struct) => out.push_str(" AS STRUCT"),
1148            Some(SelectAs::Value) => out.push_str(" AS VALUE"),
1149            None => {}
1150        }
1151        out.push(' ');
1152        out.push_str(&self.select_items(&s.projection, i));
1153        if !s.from.is_empty() {
1154            out.push_str(&format!(
1155                "{}FROM {}",
1156                self.nl(i),
1157                self.table_list(&s.from, i)
1158            ));
1159        }
1160        if let Some(w) = &s.where_clause {
1161            out.push_str(&format!("{}WHERE {}", self.nl(i), self.expr(w, i)));
1162        }
1163        if let Some(g) = &s.group_by {
1164            out.push_str(&format!("{}GROUP BY ", self.nl(i)));
1165            match g {
1166                GroupBy::All => out.push_str("ALL"),
1167                GroupBy::Items(items) => {
1168                    out.push_str(&self.list(items, |item| self.group_by_item(item, i)))
1169                }
1170            }
1171        }
1172        if let Some(h) = &s.having {
1173            out.push_str(&format!("{}HAVING {}", self.nl(i), self.expr(h, i)));
1174        }
1175        if let Some(q) = &s.qualify {
1176            out.push_str(&format!("{}QUALIFY {}", self.nl(i), self.expr(q, i)));
1177        }
1178        if !s.window.is_empty() {
1179            out.push_str(&format!(
1180                "{}WINDOW {}",
1181                self.nl(i),
1182                self.list(&s.window, |w| format!(
1183                    "{} AS {}",
1184                    ident_to_sql(&w.name),
1185                    self.window_spec(&w.spec, i)
1186                ))
1187            ));
1188        }
1189        out
1190    }
1191
1192    fn select_items(&self, items: &[SelectItem], i: usize) -> String {
1193        self.list(items, |item| self.select_item(item, i))
1194    }
1195
1196    fn select_item(&self, item: &SelectItem, i: usize) -> String {
1197        match item {
1198            SelectItem::Expr { expr, alias } => match alias {
1199                Some(a) => format!("{} AS {}", self.expr(expr, i), ident_to_sql(a)),
1200                None => self.expr(expr, i),
1201            },
1202            SelectItem::Wildcard(o) => format!("*{}", self.wildcard_options(o, i)),
1203            SelectItem::QualifiedWildcard { qualifier, options } => {
1204                let q = self.expr(qualifier, i);
1205                let q = if precedence(qualifier) < 255 {
1206                    format!("({q})")
1207                } else {
1208                    q
1209                };
1210                format!("{q}.*{}", self.wildcard_options(options, i))
1211            }
1212        }
1213    }
1214
1215    fn wildcard_options(&self, o: &WildcardOptions, i: usize) -> String {
1216        let mut out = String::new();
1217        if !o.except.is_empty() {
1218            out.push_str(&format!(" EXCEPT ({})", self.list(&o.except, ident_to_sql)));
1219        }
1220        if !o.replace.is_empty() {
1221            out.push_str(&format!(
1222                " REPLACE ({})",
1223                self.list(&o.replace, |r| {
1224                    let alias = r.alias.as_ref().map(ident_to_sql).unwrap_or_default();
1225                    format!("{} AS {alias}", self.expr(&r.expr, i))
1226                })
1227            ));
1228        }
1229        out
1230    }
1231
1232    fn group_by_item(&self, item: &GroupByItem, i: usize) -> String {
1233        match item {
1234            GroupByItem::Expr(e) => self.expr(e, i),
1235            GroupByItem::Rollup(es) => format!("ROLLUP({})", self.list(es, |e| self.expr(e, i))),
1236            GroupByItem::Cube(es) => format!("CUBE({})", self.list(es, |e| self.expr(e, i))),
1237            GroupByItem::GroupingSets(items) => {
1238                format!(
1239                    "GROUPING SETS({})",
1240                    self.list(items, |item| self.group_by_item(item, i))
1241                )
1242            }
1243            GroupByItem::Empty => "()".to_string(),
1244        }
1245    }
1246
1247    fn order_by(&self, items: &[OrderByExpr], i: usize) -> String {
1248        self.list(items, |o| {
1249            let mut s = self.expr(&o.expr, i);
1250            if let Some(c) = &o.collate {
1251                s.push_str(&format!(" COLLATE {}", self.expr(c, i)));
1252            }
1253            s.push_str(&order_suffix(o.asc, o.nulls_first));
1254            s
1255        })
1256    }
1257
1258    fn table_list(&self, items: &[TableWithJoins], i: usize) -> String {
1259        self.list(items, |t| self.table_with_joins(t, i))
1260    }
1261
1262    fn table_with_joins(&self, t: &TableWithJoins, i: usize) -> String {
1263        let mut out = self.table_factor(&t.relation, i);
1264        for join in &t.joins {
1265            out.push_str(&self.nl(i));
1266            out.push_str(&self.join(join, i));
1267        }
1268        out
1269    }
1270
1271    fn join(&self, join: &Join, i: usize) -> String {
1272        let mut out = String::new();
1273        if join.natural {
1274            out.push_str("NATURAL ");
1275        }
1276        out.push_str(match join.kind {
1277            JoinKind::Inner => "JOIN ",
1278            JoinKind::Left => "LEFT JOIN ",
1279            JoinKind::Right => "RIGHT JOIN ",
1280            JoinKind::Full => "FULL JOIN ",
1281            JoinKind::Cross => "CROSS JOIN ",
1282        });
1283        out.push_str(&self.table_factor(&join.relation, i));
1284        match &join.constraint {
1285            JoinConstraint::On(e) => out.push_str(&format!(" ON {}", self.expr(e, i))),
1286            JoinConstraint::Using(cols) => {
1287                out.push_str(&format!(" USING ({})", self.list(cols, ident_to_sql)))
1288            }
1289            JoinConstraint::None => {}
1290        }
1291        out
1292    }
1293
1294    fn alias(&self, alias: &Option<Ident>) -> String {
1295        alias
1296            .as_ref()
1297            .map(|a| format!(" AS {}", ident_to_sql(a)))
1298            .unwrap_or_default()
1299    }
1300
1301    fn sample(&self, sample: &Option<TableSample>, i: usize) -> String {
1302        match sample {
1303            Some(s) => format!(
1304                " TABLESAMPLE {} ({} {})",
1305                ident_to_sql(&s.method),
1306                self.expr(&s.size, i),
1307                match s.unit {
1308                    SampleUnit::Percent => "PERCENT",
1309                    SampleUnit::Rows => "ROWS",
1310                }
1311            ),
1312            None => String::new(),
1313        }
1314    }
1315
1316    fn table_factor(&self, factor: &TableFactor, i: usize) -> String {
1317        match factor {
1318            TableFactor::Table {
1319                name,
1320                alias,
1321                system_time,
1322                sample,
1323            } => {
1324                let mut out = object_name_to_sql(name);
1325                out.push_str(&self.alias(alias));
1326                if let Some(t) = system_time {
1327                    out.push_str(&format!(" FOR SYSTEM_TIME AS OF {}", self.expr(t, i)));
1328                }
1329                out.push_str(&self.sample(sample, i));
1330                out
1331            }
1332            TableFactor::Derived {
1333                subquery,
1334                alias,
1335                sample,
1336            } => {
1337                format!(
1338                    "{}{}{}",
1339                    self.subquery(subquery, i),
1340                    self.alias(alias),
1341                    self.sample(sample, i)
1342                )
1343            }
1344            TableFactor::Unnest {
1345                array,
1346                alias,
1347                with_offset,
1348            } => {
1349                let mut out = format!("UNNEST({}){}", self.expr(array, i), self.alias(alias));
1350                if let Some(offset) = with_offset {
1351                    out.push_str(" WITH OFFSET");
1352                    out.push_str(&self.alias(offset));
1353                }
1354                out
1355            }
1356            TableFactor::TableFunction { function, alias } => {
1357                format!("{}{}", self.function(function, i), self.alias(alias))
1358            }
1359            TableFactor::NestedJoin { table, alias } => {
1360                format!("({}){}", self.table_with_joins(table, i), self.alias(alias))
1361            }
1362            TableFactor::Pivot {
1363                table,
1364                aggregates,
1365                value_column,
1366                values,
1367                alias,
1368            } => format!(
1369                "{} PIVOT({}){}",
1370                self.table_factor(table, i),
1371                self.pivot_body(aggregates, value_column, values, i),
1372                self.alias(alias)
1373            ),
1374            TableFactor::Unpivot {
1375                table,
1376                include_nulls,
1377                value_columns,
1378                name_column,
1379                columns,
1380                alias,
1381            } => format!(
1382                "{} {}{}",
1383                self.table_factor(table, i),
1384                self.unpivot_body(*include_nulls, value_columns, name_column, columns, i),
1385                self.alias(alias)
1386            ),
1387            TableFactor::MatchRecognize { table, spec, alias } => format!(
1388                "{} {}{}",
1389                self.table_factor(table, i),
1390                self.match_recognize(spec, i),
1391                self.alias(alias)
1392            ),
1393            TableFactor::Align { table, spec, alias } => format!(
1394                "{} {}{}",
1395                self.table_factor(table, i),
1396                self.align(spec, i),
1397                self.alias(alias)
1398            ),
1399        }
1400    }
1401
1402    fn match_recognize(&self, m: &MatchRecognize, i: usize) -> String {
1403        let mut parts = Vec::new();
1404        if !m.partition_by.is_empty() {
1405            parts.push(format!(
1406                "PARTITION BY {}",
1407                self.list(&m.partition_by, |e| self.expr(e, i))
1408            ));
1409        }
1410        parts.push(format!("ORDER BY {}", self.order_by(&m.order_by, i)));
1411        parts.push(format!(
1412            "MEASURES {}",
1413            self.list(&m.measures, |(e, a)| format!(
1414                "{} AS {}",
1415                self.expr(e, i),
1416                ident_to_sql(a)
1417            ))
1418        ));
1419        match m.after_match {
1420            Some(AfterMatchSkip::PastLastRow) => {
1421                parts.push("AFTER MATCH SKIP PAST LAST ROW".into())
1422            }
1423            Some(AfterMatchSkip::ToNextRow) => parts.push("AFTER MATCH SKIP TO NEXT ROW".into()),
1424            None => {}
1425        }
1426        parts.push(format!("PATTERN ({})", row_pattern(&m.pattern)));
1427        if !m.define.is_empty() {
1428            parts.push(format!(
1429                "DEFINE {}",
1430                self.list(&m.define, |(s, e)| format!(
1431                    "{} AS {}",
1432                    ident_to_sql(s),
1433                    self.expr(e, i)
1434                ))
1435            ));
1436        }
1437        if !m.options.is_empty() {
1438            parts.push(self.options(&m.options, i));
1439        }
1440        format!("MATCH_RECOGNIZE ({})", parts.join(" "))
1441    }
1442
1443    fn align(&self, a: &Align, i: usize) -> String {
1444        let mut parts = Vec::new();
1445        if let Some(t) = &a.timestamp {
1446            let mut s = format!("TIMESTAMP {}", ident_to_sql(t));
1447            if let Some(alias) = &a.timestamp_alias {
1448                s.push_str(&format!(" AS {}", ident_to_sql(alias)));
1449            }
1450            parts.push(s);
1451        }
1452        parts.push(format!("PERIOD {}", self.expr(&a.period, i)));
1453        if let Some(o) = &a.origin {
1454            parts.push(format!("ORIGIN {}", self.expr(o, i)));
1455        }
1456        if let Some(o) = &a.output {
1457            parts.push(format!("OUTPUT {o}"));
1458        }
1459        if !a.partition_by.is_empty() {
1460            parts.push(format!(
1461                "PARTITION BY {}",
1462                self.expr_alias_list(&a.partition_by, i)
1463            ));
1464        }
1465        if !a.metrics.is_empty() {
1466            parts.push(format!(
1467                "METRICS {}",
1468                self.list(&a.metrics, |m| {
1469                    let mut s = self.expr(&m.expr, i);
1470                    if let Some(w) = &m.within {
1471                        s.push_str(&format!(" WITHIN ({w})"));
1472                    }
1473                    if let Some(alias) = &m.alias {
1474                        s.push_str(&format!(" AS {}", ident_to_sql(alias)));
1475                    }
1476                    s
1477                })
1478            ));
1479        }
1480        format!("ALIGN ({})", parts.join(" "))
1481    }
1482
1483    fn expr_alias_list(&self, items: &[ExprWithAlias], i: usize) -> String {
1484        self.list(items, |item| match &item.alias {
1485            Some(a) => format!("{} AS {}", self.expr(&item.expr, i), ident_to_sql(a)),
1486            None => self.expr(&item.expr, i),
1487        })
1488    }
1489
1490    fn pivot_body(
1491        &self,
1492        aggregates: &[ExprWithAlias],
1493        value_column: &Expr,
1494        values: &[ExprWithAlias],
1495        i: usize,
1496    ) -> String {
1497        format!(
1498            "{} FOR {} IN ({})",
1499            self.expr_alias_list(aggregates, i),
1500            self.operand(value_column, COMPARISON_PRECEDENCE, true, i),
1501            self.expr_alias_list(values, i)
1502        )
1503    }
1504
1505    fn unpivot_body(
1506        &self,
1507        include_nulls: Option<bool>,
1508        value_columns: &[Ident],
1509        name_column: &Ident,
1510        columns: &[UnpivotColumns],
1511        i: usize,
1512    ) -> String {
1513        let nulls = match include_nulls {
1514            Some(true) => "INCLUDE NULLS ",
1515            Some(false) => "EXCLUDE NULLS ",
1516            None => "",
1517        };
1518        let values = if value_columns.len() == 1 {
1519            ident_to_sql(&value_columns[0])
1520        } else {
1521            format!("({})", self.list(value_columns, ident_to_sql))
1522        };
1523        let cols = self.list(columns, |c| {
1524            let names = if c.columns.len() == 1 {
1525                ident_to_sql(&c.columns[0])
1526            } else {
1527                format!("({})", self.list(&c.columns, ident_to_sql))
1528            };
1529            match &c.alias {
1530                Some(a) => format!("{names} AS {}", self.expr(a, i)),
1531                None => names,
1532            }
1533        });
1534        format!(
1535            "UNPIVOT {nulls}({values} FOR {} IN ({cols}))",
1536            ident_to_sql(name_column)
1537        )
1538    }
1539
1540    fn pipe_items(&self, items: &[PipeExprItem], i: usize) -> String {
1541        self.list(items, |item| {
1542            let mut s = self.expr(&item.expr, i);
1543            if let Some(a) = &item.alias {
1544                s.push_str(&format!(" AS {}", ident_to_sql(a)));
1545            }
1546            s.push_str(&order_suffix(item.asc, item.nulls_first));
1547            s
1548        })
1549    }
1550
1551    fn pipe(&self, pipe: &PipeOperator, i: usize) -> String {
1552        match pipe {
1553            PipeOperator::Where(e) => format!("WHERE {}", self.expr(e, i)),
1554            PipeOperator::Select {
1555                distinct,
1556                select_as,
1557                items,
1558            } => {
1559                let mut out = String::from("SELECT ");
1560                if *distinct {
1561                    out.push_str("DISTINCT ");
1562                }
1563                match select_as {
1564                    Some(SelectAs::Struct) => out.push_str("AS STRUCT "),
1565                    Some(SelectAs::Value) => out.push_str("AS VALUE "),
1566                    None => {}
1567                }
1568                out.push_str(&self.select_items(items, i));
1569                out
1570            }
1571            PipeOperator::Extend(items) => format!("EXTEND {}", self.select_items(items, i)),
1572            PipeOperator::Window(items) => format!("WINDOW {}", self.select_items(items, i)),
1573            PipeOperator::Set(a) => format!("SET {}", self.assignments(a, i)),
1574            PipeOperator::Drop(cols) => format!("DROP {}", self.list(cols, ident_to_sql)),
1575            PipeOperator::Rename(pairs) => format!(
1576                "RENAME {}",
1577                self.list(pairs, |(a, b)| format!(
1578                    "{} AS {}",
1579                    ident_to_sql(a),
1580                    ident_to_sql(b)
1581                ))
1582            ),
1583            PipeOperator::As(a) => format!("AS {}", ident_to_sql(a)),
1584            PipeOperator::Aggregate {
1585                items,
1586                group_by,
1587                group_and_order,
1588            } => {
1589                let mut out = String::from("AGGREGATE");
1590                if !items.is_empty() {
1591                    out.push(' ');
1592                    out.push_str(&self.pipe_items(items, i));
1593                }
1594                if !group_by.is_empty() {
1595                    out.push_str(if *group_and_order {
1596                        " GROUP AND ORDER BY "
1597                    } else {
1598                        " GROUP BY "
1599                    });
1600                    out.push_str(&self.pipe_items(group_by, i));
1601                }
1602                out
1603            }
1604            PipeOperator::Join(j) => self.join(j, i),
1605            PipeOperator::OrderBy(items) => format!("ORDER BY {}", self.order_by(items, i)),
1606            PipeOperator::Limit(l) => self.limit(l, i),
1607            PipeOperator::SetOperation {
1608                op,
1609                quantifier,
1610                mode,
1611                corresponding,
1612                queries,
1613            } => format!(
1614                "{} {}",
1615                self.set_op_keyword(*op, *quantifier, *mode, corresponding),
1616                self.list(queries, |q| self.subquery(q, i))
1617            ),
1618            PipeOperator::Call { function, alias } => {
1619                format!("CALL {}{}", self.function(function, i), self.alias(alias))
1620            }
1621            PipeOperator::Distinct => "DISTINCT".to_string(),
1622            PipeOperator::TableSample(s) => {
1623                self.sample(&Some(s.clone()), i).trim_start().to_string()
1624            }
1625            PipeOperator::Pivot {
1626                aggregates,
1627                value_column,
1628                values,
1629                alias,
1630            } => format!(
1631                "PIVOT({}){}",
1632                self.pivot_body(aggregates, value_column, values, i),
1633                self.alias(alias)
1634            ),
1635            PipeOperator::Unpivot {
1636                include_nulls,
1637                value_columns,
1638                name_column,
1639                columns,
1640                alias,
1641            } => format!(
1642                "{}{}",
1643                self.unpivot_body(*include_nulls, value_columns, name_column, columns, i),
1644                self.alias(alias)
1645            ),
1646            PipeOperator::Assert { condition, payload } => {
1647                let mut out = format!("ASSERT {}", self.expr(condition, i));
1648                for p in payload {
1649                    out.push_str(&format!(", {}", self.expr(p, i)));
1650                }
1651                out
1652            }
1653            PipeOperator::MatchRecognize { spec, alias } => {
1654                format!("{}{}", self.match_recognize(spec, i), self.alias(alias))
1655            }
1656            PipeOperator::Align { spec, alias } => {
1657                format!("{}{}", self.align(spec, i), self.alias(alias))
1658            }
1659        }
1660    }
1661
1662    // ------------------------------------------------------------------ expressions
1663
1664    /// `expr`, parenthesized when its precedence is below `min` (or equal, with `strict`).
1665    fn operand(&self, expr: &Expr, min: u8, strict: bool, i: usize) -> String {
1666        let p = precedence(expr);
1667        let text = self.expr(expr, i);
1668        if p < min || (strict && p == min) {
1669            format!("({text})")
1670        } else {
1671            text
1672        }
1673    }
1674
1675    fn expr(&self, expr: &Expr, i: usize) -> String {
1676        match expr {
1677            Expr::Identifier(ident) => ident_to_sql(ident),
1678            Expr::CompoundIdentifier(parts) => parts
1679                .iter()
1680                .enumerate()
1681                .map(|(n, p)| {
1682                    if n == 0 {
1683                        ident_to_sql(p)
1684                    } else {
1685                        path_part(p)
1686                    }
1687                })
1688                .collect::<Vec<_>>()
1689                .join("."),
1690            Expr::Literal(lit) => self.literal(lit, i),
1691            Expr::Parameter(p) => match p {
1692                Parameter::Named(name) if is_plain_word(name) => format!("@{name}"),
1693                Parameter::Named(name) => format!("@`{}`", escape_identifier(name)),
1694                Parameter::Positional => "?".to_string(),
1695                Parameter::System(name) => format!("@@{name}"),
1696            },
1697            Expr::UnaryOp { op, expr: inner } => match op {
1698                UnaryOperator::Not => {
1699                    format!("NOT {}", self.operand(inner, NOT_PRECEDENCE, false, i))
1700                }
1701                _ => {
1702                    let symbol = match op {
1703                        UnaryOperator::Minus => "-",
1704                        UnaryOperator::Plus => "+",
1705                        _ => "~",
1706                    };
1707                    let operand = self.operand(inner, UNARY_PRECEDENCE, false, i);
1708                    let space = if operand.starts_with('-') || operand.starts_with('+') {
1709                        " "
1710                    } else {
1711                        ""
1712                    };
1713                    format!("{symbol}{space}{operand}")
1714                }
1715            },
1716            Expr::BinaryOp { left, op, right } => {
1717                let p = op.precedence();
1718                format!(
1719                    "{} {} {}",
1720                    self.operand(left, p, false, i),
1721                    op.as_str(),
1722                    self.operand(right, p, true, i)
1723                )
1724            }
1725            Expr::IsNull { expr: e, negated } => format!(
1726                "{} IS {}NULL",
1727                self.operand(e, COMPARISON_PRECEDENCE, false, i),
1728                if *negated { "NOT " } else { "" }
1729            ),
1730            Expr::IsBool {
1731                expr: e,
1732                value,
1733                negated,
1734            } => format!(
1735                "{} IS {}{}",
1736                self.operand(e, COMPARISON_PRECEDENCE, false, i),
1737                if *negated { "NOT " } else { "" },
1738                match value {
1739                    Some(true) => "TRUE",
1740                    Some(false) => "FALSE",
1741                    None => "UNKNOWN",
1742                }
1743            ),
1744            Expr::IsDistinctFrom {
1745                left,
1746                right,
1747                negated,
1748            } => format!(
1749                "{} IS {}DISTINCT FROM {}",
1750                self.operand(left, COMPARISON_PRECEDENCE, false, i),
1751                if *negated { "NOT " } else { "" },
1752                self.operand(right, COMPARISON_PRECEDENCE, true, i)
1753            ),
1754            Expr::InList {
1755                expr: e,
1756                list,
1757                negated,
1758            } => format!(
1759                "{} {}IN ({})",
1760                self.operand(e, COMPARISON_PRECEDENCE, false, i),
1761                not(*negated),
1762                self.list(list, |x| self.expr(x, i))
1763            ),
1764            Expr::InSubquery {
1765                expr: e,
1766                subquery,
1767                negated,
1768            } => format!(
1769                "{} {}IN {}",
1770                self.operand(e, COMPARISON_PRECEDENCE, false, i),
1771                not(*negated),
1772                self.subquery(subquery, i)
1773            ),
1774            Expr::InUnnest {
1775                expr: e,
1776                array,
1777                negated,
1778            } => format!(
1779                "{} {}IN UNNEST({})",
1780                self.operand(e, COMPARISON_PRECEDENCE, false, i),
1781                not(*negated),
1782                self.expr(array, i)
1783            ),
1784            Expr::Between {
1785                expr: e,
1786                negated,
1787                low,
1788                high,
1789            } => format!(
1790                "{} {}BETWEEN {} AND {}",
1791                self.operand(e, COMPARISON_PRECEDENCE, false, i),
1792                not(*negated),
1793                self.operand(low, COMPARISON_PRECEDENCE, true, i),
1794                self.operand(high, COMPARISON_PRECEDENCE, true, i)
1795            ),
1796            Expr::Like {
1797                expr: e,
1798                negated,
1799                pattern,
1800            } => format!(
1801                "{} {}LIKE {}",
1802                self.operand(e, COMPARISON_PRECEDENCE, false, i),
1803                not(*negated),
1804                self.operand(pattern, COMPARISON_PRECEDENCE, true, i)
1805            ),
1806            Expr::LikeQuantified {
1807                expr: e,
1808                negated,
1809                quantifier,
1810                patterns,
1811            } => {
1812                let q = match quantifier {
1813                    LikeQuantifier::Any => "ANY",
1814                    LikeQuantifier::Some => "SOME",
1815                    LikeQuantifier::All => "ALL",
1816                };
1817                let p = match patterns {
1818                    LikePatterns::List(list) => {
1819                        format!("({})", self.list(list, |x| self.expr(x, i)))
1820                    }
1821                    LikePatterns::Unnest(a) => format!("UNNEST({})", self.expr(a, i)),
1822                    LikePatterns::Subquery(q) => self.subquery(q, i),
1823                };
1824                format!(
1825                    "{} {}LIKE {q} {p}",
1826                    self.operand(e, COMPARISON_PRECEDENCE, false, i),
1827                    not(*negated)
1828                )
1829            }
1830            Expr::Case {
1831                operand,
1832                branches,
1833                else_result,
1834            } => {
1835                let mut out = String::from("CASE");
1836                if let Some(o) = operand {
1837                    out.push_str(&format!(" {}", self.expr(o, i)));
1838                }
1839                for b in branches {
1840                    out.push_str(&format!(
1841                        " WHEN {} THEN {}",
1842                        self.expr(&b.condition, i),
1843                        self.expr(&b.result, i)
1844                    ));
1845                }
1846                if let Some(e) = else_result {
1847                    out.push_str(&format!(" ELSE {}", self.expr(e, i)));
1848                }
1849                out.push_str(" END");
1850                out
1851            }
1852            Expr::Cast {
1853                expr: e,
1854                data_type,
1855                safe,
1856                format,
1857                time_zone,
1858            } => {
1859                let mut out = format!(
1860                    "{}({} AS {}",
1861                    if *safe { "SAFE_CAST" } else { "CAST" },
1862                    self.expr(e, i),
1863                    self.data_type(data_type)
1864                );
1865                if let Some(f) = format {
1866                    out.push_str(&format!(" FORMAT {}", self.expr(f, i)));
1867                }
1868                if let Some(t) = time_zone {
1869                    out.push_str(&format!(" AT TIME ZONE {}", self.expr(t, i)));
1870                }
1871                out.push(')');
1872                out
1873            }
1874            Expr::Extract {
1875                part,
1876                expr: e,
1877                time_zone,
1878            } => {
1879                let mut out = format!("EXTRACT({} FROM {}", self.expr(part, i), self.expr(e, i));
1880                if let Some(t) = time_zone {
1881                    out.push_str(&format!(" AT TIME ZONE {}", self.expr(t, i)));
1882                }
1883                out.push(')');
1884                out
1885            }
1886            Expr::Struct { fields, typed } => {
1887                let mut out = String::from("STRUCT");
1888                if let Some(t) = typed {
1889                    out.push_str(&format!("<{}>", self.struct_fields(t)));
1890                }
1891                out.push_str(&format!(
1892                    "({})",
1893                    self.list(fields, |f| match &f.alias {
1894                        Some(a) => format!("{} AS {}", self.expr(&f.expr, i), ident_to_sql(a)),
1895                        None => self.expr(&f.expr, i),
1896                    })
1897                ));
1898                out
1899            }
1900            Expr::Tuple(items) => format!("({})", self.list(items, |x| self.expr(x, i))),
1901            Expr::Array {
1902                elements,
1903                element_type,
1904                keyword,
1905            } => {
1906                let mut out = String::new();
1907                if *keyword || element_type.is_some() {
1908                    out.push_str("ARRAY");
1909                }
1910                if let Some(t) = element_type {
1911                    out.push_str(&format!("<{}>", self.data_type(t)));
1912                }
1913                out.push_str(&format!("[{}]", self.list(elements, |x| self.expr(x, i))));
1914                out
1915            }
1916            Expr::ArraySubquery(q) => format!("ARRAY{}", self.subquery(q, i)),
1917            Expr::Subscript {
1918                expr: e,
1919                kind,
1920                index,
1921            } => {
1922                let base = self.operand(e, 255, false, i);
1923                match kind.keyword() {
1924                    Some(word) => format!("{base}[{word}({})]", self.expr(index, i)),
1925                    None => format!("{base}[{}]", self.expr(index, i)),
1926                }
1927            }
1928            Expr::FieldAccess { expr: e, field } => {
1929                format!("{}.{}", self.operand(e, 255, false, i), path_part(field))
1930            }
1931            Expr::Function(f) => self.function(f, i),
1932            Expr::Subquery(q) => self.subquery(q, i),
1933            Expr::Exists(q) => format!("EXISTS {}", self.subquery(q, i)),
1934            Expr::ScalarWith { bindings, body } => {
1935                let mut parts: Vec<String> = bindings
1936                    .iter()
1937                    .map(|(name, value)| {
1938                        format!("{} AS {}", ident_to_sql(name), self.expr(value, i))
1939                    })
1940                    .collect();
1941                parts.push(self.expr(body, i));
1942                format!("WITH({})", parts.join(", "))
1943            }
1944            Expr::Lambda { params, body } => {
1945                let head = if params.len() == 1 {
1946                    ident_to_sql(&params[0])
1947                } else {
1948                    format!("({})", self.list(params, ident_to_sql))
1949                };
1950                format!("{head} -> {}", self.expr(body, i))
1951            }
1952            Expr::NamedArg { name, value } => {
1953                format!("{} => {}", ident_to_sql(name), self.expr(value, i))
1954            }
1955            Expr::Nested(inner) => format!("({})", self.expr(inner, i)),
1956            Expr::Default => "DEFAULT".to_string(),
1957        }
1958    }
1959
1960    fn literal(&self, lit: &Literal, i: usize) -> String {
1961        match lit {
1962            Literal::Null => "NULL".to_string(),
1963            Literal::Bool(true) => "TRUE".to_string(),
1964            Literal::Bool(false) => "FALSE".to_string(),
1965            Literal::Int(text) | Literal::Float(text) => text.clone(),
1966            Literal::Numeric(v) => format!("NUMERIC {}", quote_string(v)),
1967            Literal::BigNumeric(v) => format!("BIGNUMERIC {}", quote_string(v)),
1968            Literal::String(s) => {
1969                if s.raw && raw_ok(&s.value, s.quote) {
1970                    format!("r{q}{}{q}", s.value, q = s.quote.delimiter())
1971                } else {
1972                    let quote = if s.raw { QuoteStyle::Single } else { s.quote };
1973                    format!(
1974                        "{q}{}{q}",
1975                        escape_string(&s.value, quote),
1976                        q = quote.delimiter()
1977                    )
1978                }
1979            }
1980            Literal::Bytes(b) => format!("b'{}'", escape_bytes(&b.value)),
1981            Literal::Date(v) => format!("DATE {}", quote_string(v)),
1982            Literal::Datetime(v) => format!("DATETIME {}", quote_string(v)),
1983            Literal::Time(v) => format!("TIME {}", quote_string(v)),
1984            Literal::Timestamp(v) => format!("TIMESTAMP {}", quote_string(v)),
1985            Literal::Json(v) => format!("JSON {}", quote_string(v)),
1986            Literal::Range { element, value } => {
1987                format!("RANGE<{}> {}", self.data_type(element), quote_string(value))
1988            }
1989            Literal::Interval(interval) => {
1990                let mut out = format!(
1991                    "INTERVAL {} {}",
1992                    self.operand(&interval.value, UNARY_PRECEDENCE, false, i),
1993                    interval.leading
1994                );
1995                if let Some(t) = &interval.trailing {
1996                    out.push_str(&format!(" TO {t}"));
1997                }
1998                out
1999            }
2000        }
2001    }
2002
2003    fn function(&self, f: &Function, i: usize) -> String {
2004        let name = function_name(&f.name);
2005        if f.no_parens {
2006            return name;
2007        }
2008        let mut out = format!("{name}(");
2009        if f.distinct {
2010            out.push_str("DISTINCT ");
2011        }
2012        out.push_str(&self.list(&f.args, |arg| match arg {
2013            FunctionArg::Expr(e) => self.expr(e, i),
2014            FunctionArg::Wildcard => "*".to_string(),
2015            FunctionArg::Table(t) => format!("TABLE {}", object_name_to_sql(t)),
2016            FunctionArg::Model(m) => format!("MODEL {}", object_name_to_sql(m)),
2017        }));
2018        match f.null_treatment {
2019            Some(NullTreatment::IgnoreNulls) => out.push_str(" IGNORE NULLS"),
2020            Some(NullTreatment::RespectNulls) => out.push_str(" RESPECT NULLS"),
2021            None => {}
2022        }
2023        if let Some(h) = &f.having {
2024            out.push_str(&format!(
2025                " HAVING {} {}",
2026                if h.max { "MAX" } else { "MIN" },
2027                self.expr(&h.expr, i)
2028            ));
2029        }
2030        if !f.order_by.is_empty() {
2031            out.push_str(&format!(" ORDER BY {}", self.order_by(&f.order_by, i)));
2032        }
2033        if let Some(l) = &f.limit {
2034            out.push_str(&format!(" LIMIT {}", self.expr(l, i)));
2035        }
2036        out.push(')');
2037        match &f.over {
2038            Some(WindowType::Named(name)) => out.push_str(&format!(" OVER {}", ident_to_sql(name))),
2039            Some(WindowType::Spec(spec)) => {
2040                out.push_str(&format!(" OVER {}", self.window_spec(spec, i)))
2041            }
2042            None => {}
2043        }
2044        out
2045    }
2046
2047    fn window_spec(&self, spec: &WindowSpec, i: usize) -> String {
2048        let mut parts = Vec::new();
2049        if let Some(b) = &spec.base {
2050            parts.push(ident_to_sql(b));
2051        }
2052        if !spec.partition_by.is_empty() {
2053            parts.push(format!(
2054                "PARTITION BY {}",
2055                self.list(&spec.partition_by, |e| self.expr(e, i))
2056            ));
2057        }
2058        if !spec.order_by.is_empty() {
2059            parts.push(format!("ORDER BY {}", self.order_by(&spec.order_by, i)));
2060        }
2061        if let Some(frame) = &spec.frame {
2062            let units = match frame.units {
2063                FrameUnits::Rows => "ROWS",
2064                FrameUnits::Range => "RANGE",
2065            };
2066            parts.push(match &frame.end {
2067                Some(end) => format!(
2068                    "{units} BETWEEN {} AND {}",
2069                    self.frame_bound(&frame.start, i),
2070                    self.frame_bound(end, i)
2071                ),
2072                None => format!("{units} {}", self.frame_bound(&frame.start, i)),
2073            });
2074        }
2075        format!("({})", parts.join(" "))
2076    }
2077
2078    fn frame_bound(&self, bound: &FrameBound, i: usize) -> String {
2079        match bound {
2080            FrameBound::UnboundedPreceding => "UNBOUNDED PRECEDING".to_string(),
2081            FrameBound::UnboundedFollowing => "UNBOUNDED FOLLOWING".to_string(),
2082            FrameBound::CurrentRow => "CURRENT ROW".to_string(),
2083            FrameBound::Preceding(e) => format!(
2084                "{} PRECEDING",
2085                self.operand(e, COMPARISON_PRECEDENCE, true, i)
2086            ),
2087            FrameBound::Following(e) => format!(
2088                "{} FOLLOWING",
2089                self.operand(e, COMPARISON_PRECEDENCE, true, i)
2090            ),
2091        }
2092    }
2093
2094    // ------------------------------------------------------------------ types
2095
2096    fn struct_fields(&self, fields: &[StructField]) -> String {
2097        self.list(fields, |f| {
2098            let mut s = match &f.name {
2099                Some(n) => format!("{} {}", path_part(n), self.data_type(&f.data_type)),
2100                None => self.data_type(&f.data_type),
2101            };
2102            if f.not_null {
2103                s.push_str(" NOT NULL");
2104            }
2105            if !f.options.is_empty() {
2106                s.push(' ');
2107                s.push_str(&self.options(&f.options, 0));
2108            }
2109            s
2110        })
2111    }
2112
2113    fn data_type(&self, t: &DataType) -> String {
2114        match t {
2115            DataType::Int64 => "INT64".into(),
2116            DataType::Float64 => "FLOAT64".into(),
2117            DataType::Numeric(p) => format!("NUMERIC{}", precision(p)),
2118            DataType::BigNumeric(p) => format!("BIGNUMERIC{}", precision(p)),
2119            DataType::Bool => "BOOL".into(),
2120            DataType::String(n) => n.map_or("STRING".into(), |n| format!("STRING({n})")),
2121            DataType::Bytes(n) => n.map_or("BYTES".into(), |n| format!("BYTES({n})")),
2122            DataType::Date => "DATE".into(),
2123            DataType::Datetime => "DATETIME".into(),
2124            DataType::Time => "TIME".into(),
2125            DataType::Timestamp => "TIMESTAMP".into(),
2126            DataType::Interval => "INTERVAL".into(),
2127            DataType::Json => "JSON".into(),
2128            DataType::Geography => "GEOGRAPHY".into(),
2129            DataType::Array(inner) => format!("ARRAY<{}>", self.data_type(inner)),
2130            DataType::Struct(fields) => format!("STRUCT<{}>", self.struct_fields(fields)),
2131            DataType::Range(inner) => format!("RANGE<{}>", self.data_type(inner)),
2132            DataType::Other(name) if is_plain_word(name) => name.clone(),
2133            DataType::Other(name) => format!("`{}`", escape_identifier(name)),
2134        }
2135    }
2136}
2137
2138fn precision(p: &Option<(u32, Option<u32>)>) -> String {
2139    match p {
2140        Some((precision, Some(scale))) => format!("({precision}, {scale})"),
2141        Some((precision, None)) => format!("({precision})"),
2142        None => String::new(),
2143    }
2144}
2145
2146fn not(negated: bool) -> &'static str {
2147    if negated {
2148        "NOT "
2149    } else {
2150        ""
2151    }
2152}
2153
2154fn order_suffix(asc: Option<bool>, nulls_first: Option<bool>) -> String {
2155    let mut s = String::new();
2156    match asc {
2157        Some(true) => s.push_str(" ASC"),
2158        Some(false) => s.push_str(" DESC"),
2159        None => {}
2160    }
2161    match nulls_first {
2162        Some(true) => s.push_str(" NULLS FIRST"),
2163        Some(false) => s.push_str(" NULLS LAST"),
2164        None => {}
2165    }
2166    s
2167}
2168
2169/// A `MATCH_RECOGNIZE` pattern as written: alternation binds loosest, then concatenation, then quantifiers.
2170pub fn row_pattern(p: &RowPattern) -> String {
2171    match p {
2172        RowPattern::Empty => "()".to_string(),
2173        RowPattern::Symbol(s) => ident_to_sql(s),
2174        RowPattern::Start => "^".to_string(),
2175        RowPattern::Concat(items) => items
2176            .iter()
2177            .map(|item| match item {
2178                RowPattern::Alternation(_) => format!("({})", row_pattern(item)),
2179                _ => row_pattern(item),
2180            })
2181            .collect::<Vec<_>>()
2182            .join(" "),
2183        RowPattern::Alternation(items) => items
2184            .iter()
2185            .map(row_pattern)
2186            .collect::<Vec<_>>()
2187            .join(" | "),
2188        RowPattern::Group(inner) => match inner.as_ref() {
2189            RowPattern::Empty => "()".to_string(),
2190            other => format!("({})", row_pattern(other)),
2191        },
2192        RowPattern::Quantified {
2193            pattern,
2194            quantifier,
2195            reluctant,
2196        } => {
2197            let base = match pattern.as_ref() {
2198                RowPattern::Symbol(_)
2199                | RowPattern::Group(_)
2200                | RowPattern::Empty
2201                | RowPattern::Start => row_pattern(pattern),
2202                RowPattern::Quantified { .. } => row_pattern(pattern),
2203                other => format!("({})", row_pattern(other)),
2204            };
2205            let q = match quantifier {
2206                PatternQuantifier::ZeroOrMore => "*".to_string(),
2207                PatternQuantifier::OneOrMore => "+".to_string(),
2208                PatternQuantifier::ZeroOrOne => "?".to_string(),
2209                PatternQuantifier::Exactly(n) => format!("{{{n}}}"),
2210                PatternQuantifier::Range { min, max } => format!(
2211                    "{{{},{}}}",
2212                    min.map(|n| n.to_string()).unwrap_or_default(),
2213                    max.map(|n| n.to_string()).unwrap_or_default()
2214                ),
2215            };
2216            format!("{base}{q}{}", if *reluctant { "?" } else { "" })
2217        }
2218    }
2219}