utopia-query 0.1.1

Queries as data, compiled to SQL (MySQL, MariaDB, PostgreSQL, SQLite, ClickHouse) and MongoDB commands; schema builders; a SQL tokenizer, parser, serializer and statement classifier.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! [`Serializer`]: a [`Select`] back to SQL.

use crate::StringLiteral;
use std::fmt::Write as _;

use super::node::{
    Binary, Column, Conditional, Cte, Expression, Func, InList, JoinClause, Literal, OrderByItem, Select, Star, Table,
    TableSource, Window, WindowSpecification,
};
use crate::error::{Error, Result};
use crate::value::Value;

/// Writes a syntax tree as SQL, quoting identifiers the way one dialect
/// does: backticks (MySQL, MariaDB, ClickHouse, and the base serializer) or
/// double quotes (PostgreSQL, SQLite), with the quote doubled inside.
///
/// PHP: `Utopia\Query\AST\Serializer` and its dialect subclasses.
///
/// ```
/// use utopia_query::ast::{Parser, Serializer};
///
/// let select = Parser::new().parse_sql("select id, name from users where id = 1")?;
/// assert_eq!(Serializer::new().serialize(&select)?, "SELECT `id`, `name` FROM `users` WHERE `id` = 1");
/// assert_eq!(Serializer::postgresql().serialize(&select)?, r#"SELECT "id", "name" FROM "users" WHERE "id" = 1"#);
/// # Ok::<(), utopia_query::Error>(())
/// ```
///
/// ```php
/// use Utopia\Query\AST\Parser;
/// use Utopia\Query\AST\Serializer;
/// use Utopia\Query\Tokenizer\Tokenizer;
///
/// $select = (new Parser())->parse(Tokenizer::filter((new Tokenizer())->tokenize('select id, name from users where id = 1')));
/// echo (new Serializer())->serialize($select), "\n"; // SELECT `id`, `name` FROM `users` WHERE `id` = 1
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Serializer {
    quote: char,
    literal: StringLiteral,
}

impl Default for Serializer {
    /// [`Serializer::new`].
    fn default() -> Self {
        Serializer::new()
    }
}

/// The binding strength of a binary operator (0 for unknown operators).
fn precedence(operator: &str) -> u8 {
    const LEVELS: &[(&str, u8)] = &[
        ("OR", 1),
        ("AND", 2),
        ("=", 3),
        ("!=", 3),
        ("<>", 3),
        ("<", 3),
        (">", 3),
        ("<=", 3),
        (">=", 3),
        ("LIKE", 3),
        ("ILIKE", 3),
        ("NOT LIKE", 3),
        ("NOT ILIKE", 3),
        ("+", 4),
        ("-", 4),
        ("||", 4),
        ("*", 5),
        ("/", 5),
        ("%", 5),
    ];
    LEVELS.iter().find(|(op, _)| op.eq_ignore_ascii_case(operator)).map_or(0, |(_, level)| *level)
}

impl Serializer {
    /// The base serializer: identifiers in backticks.
    ///
    /// PHP: `new Serializer()`.
    pub const fn new() -> Self {
        Serializer { quote: '`', literal: StringLiteral::Backslash }
    }

    /// MySQL: identifiers in backticks.
    ///
    /// PHP: `new Serializer\MySQL()`.
    pub const fn mysql() -> Self {
        Self::new()
    }

    /// MariaDB: identifiers in backticks.
    ///
    /// PHP: `new Serializer\MariaDB()`.
    pub const fn mariadb() -> Self {
        Self::new()
    }

    /// ClickHouse: identifiers in backticks.
    ///
    /// PHP: `new Serializer\ClickHouse()`.
    pub const fn clickhouse() -> Self {
        Self::new().with_literal(StringLiteral::BackslashUtf8)
    }

    /// PostgreSQL: identifiers in double quotes.
    ///
    /// PHP: `new Serializer\PostgreSQL()`.
    pub const fn postgresql() -> Self {
        Serializer { quote: '"', literal: StringLiteral::Extended }
    }

    /// SQLite: identifiers in double quotes.
    ///
    /// PHP: `new Serializer\SQLite()`.
    pub const fn sqlite() -> Self {
        Self::postgresql().with_literal(StringLiteral::Standard)
    }

    /// The serializer writing string literals by `literal`'s rules.
    ///
    /// PHP: `new Serializer($literal)`.
    #[must_use]
    pub const fn with_literal(mut self, literal: StringLiteral) -> Self {
        self.literal = literal;
        self
    }

    /// A serializer quoting identifiers with `quote` (doubled inside them).
    ///
    /// PHP: a subclass overriding `quoteIdentifier()`.
    pub const fn with_quote(quote: char) -> Self {
        Serializer { quote, literal: StringLiteral::Backslash }
    }

    /// `statement` as SQL. Fails with [`Error::Query`] on a node no SQL
    /// position takes (a [`CaseWhen`](super::CaseWhen) outside a `CASE`).
    ///
    /// PHP: `Serializer::serialize()`.
    pub fn serialize(&self, statement: &Select) -> Result<String> {
        let mut out = String::with_capacity(64);
        self.select(&mut out, statement)?;
        Ok(out)
    }

    /// `expression` as SQL.
    ///
    /// PHP: `Serializer::serializeExpression()`.
    pub fn serialize_expression(&self, expression: &Expression) -> Result<String> {
        let mut out = String::with_capacity(32);
        self.expression(&mut out, expression)?;
        Ok(out)
    }

    /// `name` quoted as an identifier.
    ///
    /// PHP: `Serializer::quoteIdentifier()` (protected).
    pub fn quote_identifier(&self, name: &str) -> String {
        let mut out = String::with_capacity(name.len() + 2);
        self.quote(&mut out, name);
        out
    }

    fn quote(&self, out: &mut String, name: &str) {
        out.push(self.quote);
        for c in name.chars() {
            if c == self.quote {
                out.push(c);
            }
            out.push(c);
        }
        out.push(self.quote);
    }

    fn list<T>(
        &self,
        out: &mut String,
        items: &[T],
        mut each: impl FnMut(&Self, &mut String, &T) -> Result<()>,
    ) -> Result<()> {
        for (i, item) in items.iter().enumerate() {
            if i > 0 {
                out.push_str(", ");
            }
            each(self, out, item)?;
        }
        Ok(())
    }

    fn expressions(&self, out: &mut String, items: &[Expression]) -> Result<()> {
        self.list(out, items, |s, out, e| s.expression(out, e))
    }

    fn order_by_items(&self, out: &mut String, items: &[OrderByItem]) -> Result<()> {
        self.list(out, items, |s, out, item| s.order_by_item(out, item))
    }

    fn select(&self, out: &mut String, statement: &Select) -> Result<()> {
        if !statement.ctes.is_empty() {
            self.ctes(out, &statement.ctes)?;
            out.push(' ');
        }

        out.push_str("SELECT");
        if statement.distinct {
            out.push_str(" DISTINCT");
        }
        out.push(' ');
        self.expressions(out, &statement.columns)?;

        if let Some(from) = &statement.from {
            out.push_str(" FROM ");
            self.table_source(out, from)?;
        }
        for join in &statement.joins {
            out.push(' ');
            self.join(out, join)?;
        }
        if let Some(condition) = &statement.where_clause {
            out.push_str(" WHERE ");
            self.expression(out, condition)?;
        }
        if !statement.group_by.is_empty() {
            out.push_str(" GROUP BY ");
            self.expressions(out, &statement.group_by)?;
        }
        if let Some(having) = &statement.having {
            out.push_str(" HAVING ");
            self.expression(out, having)?;
        }
        if !statement.windows.is_empty() {
            out.push_str(" WINDOW ");
            self.list(out, &statement.windows, |s, out, window| {
                s.quote(out, &window.name);
                out.push_str(" AS (");
                s.window_specification(out, &window.specification)?;
                out.push(')');
                Ok(())
            })?;
        }
        if !statement.order_by.is_empty() {
            out.push_str(" ORDER BY ");
            self.order_by_items(out, &statement.order_by)?;
        }
        if let Some(limit) = &statement.limit {
            out.push_str(" LIMIT ");
            self.expression(out, limit)?;
        }
        if let Some(offset) = &statement.offset {
            out.push_str(" OFFSET ");
            self.expression(out, offset)?;
        }
        Ok(())
    }

    fn expression(&self, out: &mut String, expression: &Expression) -> Result<()> {
        match expression {
            Expression::Aliased(a) => {
                self.expression(out, &a.expression)?;
                out.push_str(" AS ");
                self.quote(out, &a.alias);
            }
            Expression::Window(w) => self.window(out, w)?,
            Expression::Binary(b) => self.binary(out, b, None)?,
            Expression::Unary(u) => {
                if u.prefix {
                    // Always parenthesise the operand so a negative literal or
                    // a nested unary cannot produce `--`, a MySQL comment.
                    out.push_str(&u.operator);
                    out.push_str(" (");
                    self.expression(out, &u.operand)?;
                    out.push(')');
                } else {
                    self.expression(out, &u.operand)?;
                    out.push(' ');
                    out.push_str(&u.operator);
                }
            }
            Expression::Column(c) => self.column(out, c),
            Expression::Literal(l) => literal(out, l, self.literal)?,
            Expression::Star(s) => self.star(out, s),
            Expression::Placeholder(p) => out.push_str(&p.value),
            Expression::Raw(r) => out.push_str(&r.sql),
            Expression::Func(f) => self.func(out, f)?,
            Expression::In(i) => {
                self.expression(out, &i.expression)?;
                out.push_str(if i.negated { " NOT IN (" } else { " IN (" });
                match &i.list {
                    InList::Subquery(query) => self.select(out, query)?,
                    InList::Values(items) => self.expressions(out, items)?,
                }
                out.push(')');
            }
            Expression::Between(b) => {
                self.expression(out, &b.expression)?;
                out.push_str(if b.negated { " NOT BETWEEN " } else { " BETWEEN " });
                self.expression(out, &b.low)?;
                out.push_str(" AND ");
                self.expression(out, &b.high)?;
            }
            Expression::Exists(e) => {
                out.push_str(if e.negated { "NOT EXISTS (" } else { "EXISTS (" });
                self.select(out, &e.subquery)?;
                out.push(')');
            }
            Expression::Conditional(c) => self.conditional(out, c)?,
            Expression::Cast(c) => {
                out.push_str("CAST(");
                self.expression(out, &c.expression)?;
                out.push_str(" AS ");
                out.push_str(&c.data_type);
                out.push(')');
            }
            Expression::Subquery(s) => {
                out.push('(');
                self.select(out, &s.query)?;
                out.push(')');
            }
            Expression::CaseWhen(_) => {
                return Err(Error::query(format!(
                    "Unsupported expression type: Utopia\\Query\\AST\\{}",
                    expression.php_class()
                )));
            }
        }
        Ok(())
    }

    fn binary(&self, out: &mut String, binary: &Binary, parent: Option<u8>) -> Result<()> {
        let level = precedence(&binary.operator);
        // Operators are left-associative, so an equal-precedence right subtree
        // keeps its grouping: `a * (b / c)` is not `a * b / c` under integer
        // division, nor `a - (b - c)` `a - b - c`. Only the same associative
        // operator may drop it: `a + (b + c)` is `a + b + c`. Raw SQL is not
        // regrouped; it takes the operator's own precedence, which is how
        // binary_child() knows to enclose it as an operand of AND.
        let associative = matches!(&*binary.right, Expression::Binary(r)
            if r.operator.eq_ignore_ascii_case(&binary.operator)
                && ["+", "*", "||", "AND", "OR"].iter().any(|o| o.eq_ignore_ascii_case(&binary.operator)));
        let raw = matches!(&*binary.right, Expression::Raw(_));
        let right_level = if associative || raw { level } else { level + 1 };
        let parens = parent.is_some_and(|p| level < p);
        if parens {
            out.push('(');
        }
        self.binary_child(out, &binary.left, level)?;
        out.push(' ');
        out.push_str(&binary.operator);
        out.push(' ');
        self.binary_child(out, &binary.right, right_level)?;
        if let Some(escape) = &binary.escape {
            out.push_str(" ESCAPE ");
            self.binary_child(out, escape, right_level)?;
        }
        if parens {
            out.push(')');
        }
        Ok(())
    }

    fn binary_child(&self, out: &mut String, child: &Expression, parent: u8) -> Result<()> {
        match child {
            Expression::Binary(b) => self.binary(out, b, Some(parent)),
            // Raw SQL hides its operators, so as an operand of AND it is
            // enclosed: an OR inside it must not escape the condition it is
            // ANDed with.
            Expression::Raw(r) if parent == precedence("AND") => {
                out.push('(');
                out.push_str(&r.sql);
                out.push(')');
                Ok(())
            }
            other => self.expression(out, other),
        }
    }

    fn column(&self, out: &mut String, column: &Column) {
        if let Some(schema) = &column.schema {
            self.quote(out, schema);
            out.push('.');
        }
        if let Some(table) = &column.table {
            self.quote(out, table);
            out.push('.');
        }
        self.quote(out, &column.name);
    }

    fn star(&self, out: &mut String, star: &Star) {
        if let Some(table) = &star.table {
            if let Some(schema) = &star.schema {
                self.quote(out, schema);
                out.push('.');
            }
            self.quote(out, table);
            out.push('.');
        }
        out.push('*');
    }

    fn func(&self, out: &mut String, func: &Func) -> Result<()> {
        out.push_str(&func.name);
        match func.arguments.as_slice() {
            [Expression::Star(_)] => {
                out.push_str("(*)");
                return Ok(());
            }
            [] => {
                out.push_str("()");
                return Ok(());
            }
            arguments => {
                out.push_str(if func.distinct { "(DISTINCT " } else { "(" });
                self.expressions(out, arguments)?;
                out.push(')');
            }
        }
        if let Some(filter) = &func.filter {
            out.push_str(" FILTER (WHERE ");
            self.expression(out, filter)?;
            out.push(')');
        }
        Ok(())
    }

    fn conditional(&self, out: &mut String, conditional: &Conditional) -> Result<()> {
        out.push_str("CASE");
        if let Some(operand) = &conditional.operand {
            out.push(' ');
            self.expression(out, operand)?;
        }
        for when in &conditional.whens {
            out.push_str(" WHEN ");
            self.expression(out, &when.condition)?;
            out.push_str(" THEN ");
            self.expression(out, &when.result)?;
        }
        if let Some(else_result) = &conditional.else_result {
            out.push_str(" ELSE ");
            self.expression(out, else_result)?;
        }
        out.push_str(" END");
        Ok(())
    }

    fn window(&self, out: &mut String, window: &Window) -> Result<()> {
        self.expression(out, &window.function)?;
        if let Some(name) = &window.window_name {
            out.push_str(" OVER ");
            self.quote(out, name);
        } else if let Some(specification) = &window.specification {
            out.push_str(" OVER (");
            self.window_specification(out, specification)?;
            out.push(')');
        } else {
            out.push_str(" OVER ()");
        }
        Ok(())
    }

    fn window_specification(&self, out: &mut String, specification: &WindowSpecification) -> Result<()> {
        let mut first = true;
        let mut separate = |out: &mut String| {
            if !std::mem::take(&mut first) {
                out.push(' ');
            }
        };
        if !specification.partition_by.is_empty() {
            separate(out);
            out.push_str("PARTITION BY ");
            self.expressions(out, &specification.partition_by)?;
        }
        if !specification.order_by.is_empty() {
            separate(out);
            out.push_str("ORDER BY ");
            self.order_by_items(out, &specification.order_by)?;
        }
        if let Some(frame_type) = &specification.frame_type {
            separate(out);
            out.push_str(frame_type);
            let start = specification.frame_start.as_deref().unwrap_or("");
            match &specification.frame_end {
                Some(end) => {
                    let _ = write!(out, " BETWEEN {start} AND {end}");
                }
                None => {
                    out.push(' ');
                    out.push_str(start);
                }
            }
        }
        Ok(())
    }

    fn order_by_item(&self, out: &mut String, item: &OrderByItem) -> Result<()> {
        self.expression(out, &item.expression)?;
        out.push(' ');
        out.push_str(item.direction.as_str());
        if let Some(nulls) = item.nulls {
            out.push_str(" NULLS ");
            out.push_str(nulls.as_str());
        }
        Ok(())
    }

    fn table_source(&self, out: &mut String, source: &TableSource) -> Result<()> {
        match source {
            TableSource::Subquery(s) => {
                out.push('(');
                self.select(out, &s.query)?;
                out.push_str(") AS ");
                self.quote(out, &s.alias);
            }
            TableSource::Table(t) => self.table(out, t),
        }
        Ok(())
    }

    fn table(&self, out: &mut String, table: &Table) {
        if let Some(schema) = &table.schema {
            self.quote(out, schema);
            out.push('.');
        }
        self.quote(out, &table.name);
        if let Some(alias) = &table.alias {
            out.push_str(" AS ");
            self.quote(out, alias);
        }
    }

    fn join(&self, out: &mut String, join: &JoinClause) -> Result<()> {
        out.push_str(&join.kind);
        out.push(' ');
        self.table_source(out, &join.table)?;
        if let Some(condition) = &join.condition {
            out.push_str(" ON ");
            self.expression(out, condition)?;
        }
        Ok(())
    }

    fn ctes(&self, out: &mut String, ctes: &[Cte]) -> Result<()> {
        out.push_str(if ctes.iter().any(|c| c.recursive) { "WITH RECURSIVE " } else { "WITH " });
        self.list(out, ctes, |s, out, cte| {
            s.quote(out, &cte.name);
            if !cte.columns.is_empty() {
                out.push_str(" (");
                for (i, column) in cte.columns.iter().enumerate() {
                    if i > 0 {
                        out.push_str(", ");
                    }
                    s.quote(out, column);
                }
                out.push(')');
            }
            out.push_str(" AS (");
            s.select(out, &cte.query)?;
            out.push(')');
            Ok(())
        })
    }
}

/// A literal as SQL: `NULL`, `TRUE` / `FALSE`, a number as PHP prints it, or
/// a string quoted by the dialect's rules.
fn literal(out: &mut String, literal: &Literal, rules: StringLiteral) -> Result<()> {
    match &literal.value {
        Value::Null => out.push_str("NULL"),
        Value::Bool(b) => out.push_str(if *b { "TRUE" } else { "FALSE" }),
        Value::Int(i) => {
            let _ = write!(out, "{i}");
        }
        Value::Float(f) => out.push_str(&php_std::number::to_string(*f)),
        other => {
            let text = match other {
                Value::Str(s) => String::from_utf8_lossy(s.as_bytes()),
                other => std::borrow::Cow::Owned(crate::value::to_php_string(other)),
            };
            out.push_str(&rules.quote(&text)?);
        }
    }
    Ok(())
}