Skip to main content

utopia_query/ast/
serializer.rs

1//! [`Serializer`]: a [`Select`] back to SQL.
2
3use crate::StringLiteral;
4use std::fmt::Write as _;
5
6use super::node::{
7    Binary, Column, Conditional, Cte, Expression, Func, InList, JoinClause, Literal, OrderByItem, Select, Star, Table,
8    TableSource, Window, WindowSpecification,
9};
10use crate::error::{Error, Result};
11use crate::value::Value;
12
13/// Writes a syntax tree as SQL, quoting identifiers the way one dialect
14/// does: backticks (MySQL, MariaDB, ClickHouse, and the base serializer) or
15/// double quotes (PostgreSQL, SQLite), with the quote doubled inside.
16///
17/// PHP: `Utopia\Query\AST\Serializer` and its dialect subclasses.
18///
19/// ```
20/// use utopia_query::ast::{Parser, Serializer};
21///
22/// let select = Parser::new().parse_sql("select id, name from users where id = 1")?;
23/// assert_eq!(Serializer::new().serialize(&select)?, "SELECT `id`, `name` FROM `users` WHERE `id` = 1");
24/// assert_eq!(Serializer::postgresql().serialize(&select)?, r#"SELECT "id", "name" FROM "users" WHERE "id" = 1"#);
25/// # Ok::<(), utopia_query::Error>(())
26/// ```
27///
28/// ```php
29/// use Utopia\Query\AST\Parser;
30/// use Utopia\Query\AST\Serializer;
31/// use Utopia\Query\Tokenizer\Tokenizer;
32///
33/// $select = (new Parser())->parse(Tokenizer::filter((new Tokenizer())->tokenize('select id, name from users where id = 1')));
34/// echo (new Serializer())->serialize($select), "\n"; // SELECT `id`, `name` FROM `users` WHERE `id` = 1
35/// ```
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub struct Serializer {
38    quote: char,
39    literal: StringLiteral,
40}
41
42impl Default for Serializer {
43    /// [`Serializer::new`].
44    fn default() -> Self {
45        Serializer::new()
46    }
47}
48
49/// The binding strength of a binary operator (0 for unknown operators).
50fn precedence(operator: &str) -> u8 {
51    const LEVELS: &[(&str, u8)] = &[
52        ("OR", 1),
53        ("AND", 2),
54        ("=", 3),
55        ("!=", 3),
56        ("<>", 3),
57        ("<", 3),
58        (">", 3),
59        ("<=", 3),
60        (">=", 3),
61        ("LIKE", 3),
62        ("ILIKE", 3),
63        ("NOT LIKE", 3),
64        ("NOT ILIKE", 3),
65        ("+", 4),
66        ("-", 4),
67        ("||", 4),
68        ("*", 5),
69        ("/", 5),
70        ("%", 5),
71    ];
72    LEVELS.iter().find(|(op, _)| op.eq_ignore_ascii_case(operator)).map_or(0, |(_, level)| *level)
73}
74
75impl Serializer {
76    /// The base serializer: identifiers in backticks.
77    ///
78    /// PHP: `new Serializer()`.
79    pub const fn new() -> Self {
80        Serializer { quote: '`', literal: StringLiteral::Backslash }
81    }
82
83    /// MySQL: identifiers in backticks.
84    ///
85    /// PHP: `new Serializer\MySQL()`.
86    pub const fn mysql() -> Self {
87        Self::new()
88    }
89
90    /// MariaDB: identifiers in backticks.
91    ///
92    /// PHP: `new Serializer\MariaDB()`.
93    pub const fn mariadb() -> Self {
94        Self::new()
95    }
96
97    /// ClickHouse: identifiers in backticks.
98    ///
99    /// PHP: `new Serializer\ClickHouse()`.
100    pub const fn clickhouse() -> Self {
101        Self::new().with_literal(StringLiteral::BackslashUtf8)
102    }
103
104    /// PostgreSQL: identifiers in double quotes.
105    ///
106    /// PHP: `new Serializer\PostgreSQL()`.
107    pub const fn postgresql() -> Self {
108        Serializer { quote: '"', literal: StringLiteral::Extended }
109    }
110
111    /// SQLite: identifiers in double quotes.
112    ///
113    /// PHP: `new Serializer\SQLite()`.
114    pub const fn sqlite() -> Self {
115        Self::postgresql().with_literal(StringLiteral::Standard)
116    }
117
118    /// The serializer writing string literals by `literal`'s rules.
119    ///
120    /// PHP: `new Serializer($literal)`.
121    #[must_use]
122    pub const fn with_literal(mut self, literal: StringLiteral) -> Self {
123        self.literal = literal;
124        self
125    }
126
127    /// A serializer quoting identifiers with `quote` (doubled inside them).
128    ///
129    /// PHP: a subclass overriding `quoteIdentifier()`.
130    pub const fn with_quote(quote: char) -> Self {
131        Serializer { quote, literal: StringLiteral::Backslash }
132    }
133
134    /// `statement` as SQL. Fails with [`Error::Query`] on a node no SQL
135    /// position takes (a [`CaseWhen`](super::CaseWhen) outside a `CASE`).
136    ///
137    /// PHP: `Serializer::serialize()`.
138    pub fn serialize(&self, statement: &Select) -> Result<String> {
139        let mut out = String::with_capacity(64);
140        self.select(&mut out, statement)?;
141        Ok(out)
142    }
143
144    /// `expression` as SQL.
145    ///
146    /// PHP: `Serializer::serializeExpression()`.
147    pub fn serialize_expression(&self, expression: &Expression) -> Result<String> {
148        let mut out = String::with_capacity(32);
149        self.expression(&mut out, expression)?;
150        Ok(out)
151    }
152
153    /// `name` quoted as an identifier.
154    ///
155    /// PHP: `Serializer::quoteIdentifier()` (protected).
156    pub fn quote_identifier(&self, name: &str) -> String {
157        let mut out = String::with_capacity(name.len() + 2);
158        self.quote(&mut out, name);
159        out
160    }
161
162    fn quote(&self, out: &mut String, name: &str) {
163        out.push(self.quote);
164        for c in name.chars() {
165            if c == self.quote {
166                out.push(c);
167            }
168            out.push(c);
169        }
170        out.push(self.quote);
171    }
172
173    fn list<T>(
174        &self,
175        out: &mut String,
176        items: &[T],
177        mut each: impl FnMut(&Self, &mut String, &T) -> Result<()>,
178    ) -> Result<()> {
179        for (i, item) in items.iter().enumerate() {
180            if i > 0 {
181                out.push_str(", ");
182            }
183            each(self, out, item)?;
184        }
185        Ok(())
186    }
187
188    fn expressions(&self, out: &mut String, items: &[Expression]) -> Result<()> {
189        self.list(out, items, |s, out, e| s.expression(out, e))
190    }
191
192    fn order_by_items(&self, out: &mut String, items: &[OrderByItem]) -> Result<()> {
193        self.list(out, items, |s, out, item| s.order_by_item(out, item))
194    }
195
196    fn select(&self, out: &mut String, statement: &Select) -> Result<()> {
197        if !statement.ctes.is_empty() {
198            self.ctes(out, &statement.ctes)?;
199            out.push(' ');
200        }
201
202        out.push_str("SELECT");
203        if statement.distinct {
204            out.push_str(" DISTINCT");
205        }
206        out.push(' ');
207        self.expressions(out, &statement.columns)?;
208
209        if let Some(from) = &statement.from {
210            out.push_str(" FROM ");
211            self.table_source(out, from)?;
212        }
213        for join in &statement.joins {
214            out.push(' ');
215            self.join(out, join)?;
216        }
217        if let Some(condition) = &statement.where_clause {
218            out.push_str(" WHERE ");
219            self.expression(out, condition)?;
220        }
221        if !statement.group_by.is_empty() {
222            out.push_str(" GROUP BY ");
223            self.expressions(out, &statement.group_by)?;
224        }
225        if let Some(having) = &statement.having {
226            out.push_str(" HAVING ");
227            self.expression(out, having)?;
228        }
229        if !statement.windows.is_empty() {
230            out.push_str(" WINDOW ");
231            self.list(out, &statement.windows, |s, out, window| {
232                s.quote(out, &window.name);
233                out.push_str(" AS (");
234                s.window_specification(out, &window.specification)?;
235                out.push(')');
236                Ok(())
237            })?;
238        }
239        if !statement.order_by.is_empty() {
240            out.push_str(" ORDER BY ");
241            self.order_by_items(out, &statement.order_by)?;
242        }
243        if let Some(limit) = &statement.limit {
244            out.push_str(" LIMIT ");
245            self.expression(out, limit)?;
246        }
247        if let Some(offset) = &statement.offset {
248            out.push_str(" OFFSET ");
249            self.expression(out, offset)?;
250        }
251        Ok(())
252    }
253
254    fn expression(&self, out: &mut String, expression: &Expression) -> Result<()> {
255        match expression {
256            Expression::Aliased(a) => {
257                self.expression(out, &a.expression)?;
258                out.push_str(" AS ");
259                self.quote(out, &a.alias);
260            }
261            Expression::Window(w) => self.window(out, w)?,
262            Expression::Binary(b) => self.binary(out, b, None)?,
263            Expression::Unary(u) => {
264                if u.prefix {
265                    // Always parenthesise the operand so a negative literal or
266                    // a nested unary cannot produce `--`, a MySQL comment.
267                    out.push_str(&u.operator);
268                    out.push_str(" (");
269                    self.expression(out, &u.operand)?;
270                    out.push(')');
271                } else {
272                    self.expression(out, &u.operand)?;
273                    out.push(' ');
274                    out.push_str(&u.operator);
275                }
276            }
277            Expression::Column(c) => self.column(out, c),
278            Expression::Literal(l) => literal(out, l, self.literal)?,
279            Expression::Star(s) => self.star(out, s),
280            Expression::Placeholder(p) => out.push_str(&p.value),
281            Expression::Raw(r) => out.push_str(&r.sql),
282            Expression::Func(f) => self.func(out, f)?,
283            Expression::In(i) => {
284                self.expression(out, &i.expression)?;
285                out.push_str(if i.negated { " NOT IN (" } else { " IN (" });
286                match &i.list {
287                    InList::Subquery(query) => self.select(out, query)?,
288                    InList::Values(items) => self.expressions(out, items)?,
289                }
290                out.push(')');
291            }
292            Expression::Between(b) => {
293                self.expression(out, &b.expression)?;
294                out.push_str(if b.negated { " NOT BETWEEN " } else { " BETWEEN " });
295                self.expression(out, &b.low)?;
296                out.push_str(" AND ");
297                self.expression(out, &b.high)?;
298            }
299            Expression::Exists(e) => {
300                out.push_str(if e.negated { "NOT EXISTS (" } else { "EXISTS (" });
301                self.select(out, &e.subquery)?;
302                out.push(')');
303            }
304            Expression::Conditional(c) => self.conditional(out, c)?,
305            Expression::Cast(c) => {
306                out.push_str("CAST(");
307                self.expression(out, &c.expression)?;
308                out.push_str(" AS ");
309                out.push_str(&c.data_type);
310                out.push(')');
311            }
312            Expression::Subquery(s) => {
313                out.push('(');
314                self.select(out, &s.query)?;
315                out.push(')');
316            }
317            Expression::CaseWhen(_) => {
318                return Err(Error::query(format!(
319                    "Unsupported expression type: Utopia\\Query\\AST\\{}",
320                    expression.php_class()
321                )));
322            }
323        }
324        Ok(())
325    }
326
327    fn binary(&self, out: &mut String, binary: &Binary, parent: Option<u8>) -> Result<()> {
328        let level = precedence(&binary.operator);
329        // Operators are left-associative, so an equal-precedence right subtree
330        // keeps its grouping: `a * (b / c)` is not `a * b / c` under integer
331        // division, nor `a - (b - c)` `a - b - c`. Only the same associative
332        // operator may drop it: `a + (b + c)` is `a + b + c`. Raw SQL is not
333        // regrouped; it takes the operator's own precedence, which is how
334        // binary_child() knows to enclose it as an operand of AND.
335        let associative = matches!(&*binary.right, Expression::Binary(r)
336            if r.operator.eq_ignore_ascii_case(&binary.operator)
337                && ["+", "*", "||", "AND", "OR"].iter().any(|o| o.eq_ignore_ascii_case(&binary.operator)));
338        let raw = matches!(&*binary.right, Expression::Raw(_));
339        let right_level = if associative || raw { level } else { level + 1 };
340        let parens = parent.is_some_and(|p| level < p);
341        if parens {
342            out.push('(');
343        }
344        self.binary_child(out, &binary.left, level)?;
345        out.push(' ');
346        out.push_str(&binary.operator);
347        out.push(' ');
348        self.binary_child(out, &binary.right, right_level)?;
349        if let Some(escape) = &binary.escape {
350            out.push_str(" ESCAPE ");
351            self.binary_child(out, escape, right_level)?;
352        }
353        if parens {
354            out.push(')');
355        }
356        Ok(())
357    }
358
359    fn binary_child(&self, out: &mut String, child: &Expression, parent: u8) -> Result<()> {
360        match child {
361            Expression::Binary(b) => self.binary(out, b, Some(parent)),
362            // Raw SQL hides its operators, so as an operand of AND it is
363            // enclosed: an OR inside it must not escape the condition it is
364            // ANDed with.
365            Expression::Raw(r) if parent == precedence("AND") => {
366                out.push('(');
367                out.push_str(&r.sql);
368                out.push(')');
369                Ok(())
370            }
371            other => self.expression(out, other),
372        }
373    }
374
375    fn column(&self, out: &mut String, column: &Column) {
376        if let Some(schema) = &column.schema {
377            self.quote(out, schema);
378            out.push('.');
379        }
380        if let Some(table) = &column.table {
381            self.quote(out, table);
382            out.push('.');
383        }
384        self.quote(out, &column.name);
385    }
386
387    fn star(&self, out: &mut String, star: &Star) {
388        if let Some(table) = &star.table {
389            if let Some(schema) = &star.schema {
390                self.quote(out, schema);
391                out.push('.');
392            }
393            self.quote(out, table);
394            out.push('.');
395        }
396        out.push('*');
397    }
398
399    fn func(&self, out: &mut String, func: &Func) -> Result<()> {
400        out.push_str(&func.name);
401        match func.arguments.as_slice() {
402            [Expression::Star(_)] => {
403                out.push_str("(*)");
404                return Ok(());
405            }
406            [] => {
407                out.push_str("()");
408                return Ok(());
409            }
410            arguments => {
411                out.push_str(if func.distinct { "(DISTINCT " } else { "(" });
412                self.expressions(out, arguments)?;
413                out.push(')');
414            }
415        }
416        if let Some(filter) = &func.filter {
417            out.push_str(" FILTER (WHERE ");
418            self.expression(out, filter)?;
419            out.push(')');
420        }
421        Ok(())
422    }
423
424    fn conditional(&self, out: &mut String, conditional: &Conditional) -> Result<()> {
425        out.push_str("CASE");
426        if let Some(operand) = &conditional.operand {
427            out.push(' ');
428            self.expression(out, operand)?;
429        }
430        for when in &conditional.whens {
431            out.push_str(" WHEN ");
432            self.expression(out, &when.condition)?;
433            out.push_str(" THEN ");
434            self.expression(out, &when.result)?;
435        }
436        if let Some(else_result) = &conditional.else_result {
437            out.push_str(" ELSE ");
438            self.expression(out, else_result)?;
439        }
440        out.push_str(" END");
441        Ok(())
442    }
443
444    fn window(&self, out: &mut String, window: &Window) -> Result<()> {
445        self.expression(out, &window.function)?;
446        if let Some(name) = &window.window_name {
447            out.push_str(" OVER ");
448            self.quote(out, name);
449        } else if let Some(specification) = &window.specification {
450            out.push_str(" OVER (");
451            self.window_specification(out, specification)?;
452            out.push(')');
453        } else {
454            out.push_str(" OVER ()");
455        }
456        Ok(())
457    }
458
459    fn window_specification(&self, out: &mut String, specification: &WindowSpecification) -> Result<()> {
460        let mut first = true;
461        let mut separate = |out: &mut String| {
462            if !std::mem::take(&mut first) {
463                out.push(' ');
464            }
465        };
466        if !specification.partition_by.is_empty() {
467            separate(out);
468            out.push_str("PARTITION BY ");
469            self.expressions(out, &specification.partition_by)?;
470        }
471        if !specification.order_by.is_empty() {
472            separate(out);
473            out.push_str("ORDER BY ");
474            self.order_by_items(out, &specification.order_by)?;
475        }
476        if let Some(frame_type) = &specification.frame_type {
477            separate(out);
478            out.push_str(frame_type);
479            let start = specification.frame_start.as_deref().unwrap_or("");
480            match &specification.frame_end {
481                Some(end) => {
482                    let _ = write!(out, " BETWEEN {start} AND {end}");
483                }
484                None => {
485                    out.push(' ');
486                    out.push_str(start);
487                }
488            }
489        }
490        Ok(())
491    }
492
493    fn order_by_item(&self, out: &mut String, item: &OrderByItem) -> Result<()> {
494        self.expression(out, &item.expression)?;
495        out.push(' ');
496        out.push_str(item.direction.as_str());
497        if let Some(nulls) = item.nulls {
498            out.push_str(" NULLS ");
499            out.push_str(nulls.as_str());
500        }
501        Ok(())
502    }
503
504    fn table_source(&self, out: &mut String, source: &TableSource) -> Result<()> {
505        match source {
506            TableSource::Subquery(s) => {
507                out.push('(');
508                self.select(out, &s.query)?;
509                out.push_str(") AS ");
510                self.quote(out, &s.alias);
511            }
512            TableSource::Table(t) => self.table(out, t),
513        }
514        Ok(())
515    }
516
517    fn table(&self, out: &mut String, table: &Table) {
518        if let Some(schema) = &table.schema {
519            self.quote(out, schema);
520            out.push('.');
521        }
522        self.quote(out, &table.name);
523        if let Some(alias) = &table.alias {
524            out.push_str(" AS ");
525            self.quote(out, alias);
526        }
527    }
528
529    fn join(&self, out: &mut String, join: &JoinClause) -> Result<()> {
530        out.push_str(&join.kind);
531        out.push(' ');
532        self.table_source(out, &join.table)?;
533        if let Some(condition) = &join.condition {
534            out.push_str(" ON ");
535            self.expression(out, condition)?;
536        }
537        Ok(())
538    }
539
540    fn ctes(&self, out: &mut String, ctes: &[Cte]) -> Result<()> {
541        out.push_str(if ctes.iter().any(|c| c.recursive) { "WITH RECURSIVE " } else { "WITH " });
542        self.list(out, ctes, |s, out, cte| {
543            s.quote(out, &cte.name);
544            if !cte.columns.is_empty() {
545                out.push_str(" (");
546                for (i, column) in cte.columns.iter().enumerate() {
547                    if i > 0 {
548                        out.push_str(", ");
549                    }
550                    s.quote(out, column);
551                }
552                out.push(')');
553            }
554            out.push_str(" AS (");
555            s.select(out, &cte.query)?;
556            out.push(')');
557            Ok(())
558        })
559    }
560}
561
562/// A literal as SQL: `NULL`, `TRUE` / `FALSE`, a number as PHP prints it, or
563/// a string quoted by the dialect's rules.
564fn literal(out: &mut String, literal: &Literal, rules: StringLiteral) -> Result<()> {
565    match &literal.value {
566        Value::Null => out.push_str("NULL"),
567        Value::Bool(b) => out.push_str(if *b { "TRUE" } else { "FALSE" }),
568        Value::Int(i) => {
569            let _ = write!(out, "{i}");
570        }
571        Value::Float(f) => out.push_str(&php_std::number::to_string(*f)),
572        other => {
573            let text = match other {
574                Value::Str(s) => String::from_utf8_lossy(s.as_bytes()),
575                other => std::borrow::Cow::Owned(crate::value::to_php_string(other)),
576            };
577            out.push_str(&rules.quote(&text)?);
578        }
579    }
580    Ok(())
581}