utopia-query 0.1.0

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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
//! A builder as a syntax tree and back: [`Builder::to_ast`] and [`Builder::from_ast`].

use crate::ast::{
    Aliased, Between, Binary, Column, Cte, Expression, Func, In, InList, JoinClause, Literal, OrderByItem, Parser, Raw,
    Select, Serializer, Star, Table, TableSource, Unary,
};
use crate::builder::AstDialect;
use crate::builder::core::{Builder, Dialect, assert_join_on_predicate, first, on_parts};
use crate::builder::steps::{Arg, Ret, Step};
use crate::builder::types::{Condition, CteClause};
use crate::enums::OrderDirection;
use crate::error::{Error, Result};
use crate::method::Method;
use crate::query::{ParsedQuery, Query};
use crate::value::{self, Array, Object, Value};

/// The serializer a dialect converts expressions with.
///
/// PHP: `Builder::createAstSerializer()`.
fn serializer(dialect: AstDialect) -> Serializer {
    match dialect {
        AstDialect::Standard => Serializer::new(),
        AstDialect::MySql => Serializer::mysql(),
        AstDialect::MariaDb => Serializer::mariadb(),
        AstDialect::ClickHouse => Serializer::clickhouse(),
        AstDialect::PostgreSql => Serializer::postgresql(),
        AstDialect::Sqlite => Serializer::sqlite(),
    }
}

/// `new Literal($value)` of a scalar, else of `(string) $value`.
fn literal(value: Option<&Value>) -> Expression {
    let value = match value {
        None => Value::Null,
        Some(v @ (Value::Null | Value::Str(_) | Value::Int(_) | Value::Float(_) | Value::Bool(_))) => v.clone(),
        Some(other) => value::string(value::to_php_string(other)),
    };
    Literal { value }.into()
}

/// `(string)` of a scalar, `''` for anything else.
fn scalar(value: Option<&Value>) -> String {
    match value {
        Some(v @ (Value::Str(_) | Value::Int(_) | Value::Float(_) | Value::Bool(_))) => value::to_php_string(v),
        _ => String::new(),
    }
}

/// `string|int|float` kept, anything else as `(string)`.
fn comparable(value: &Value) -> Value {
    match value {
        Value::Str(_) | Value::Int(_) | Value::Float(_) => value.clone(),
        other => value::string(value::to_php_string(other)),
    }
}

/// PHP's `(int)` of a literal value.
fn to_int(value: &Value) -> i64 {
    match value {
        Value::Int(i) => *i,
        Value::Float(f) => php_std::format::dval_to_lval(*f),
        Value::Bool(b) => i64::from(*b),
        Value::Str(s) => php_std::format::str_to_int(s.as_bytes()),
        _ => 0,
    }
}

fn column(name: &str) -> Expression {
    Column::new(name).into()
}

fn combine(mut expressions: Vec<Expression>, operator: &str) -> Expression {
    let rest = expressions.split_off(1);
    let mut result = expressions.pop().unwrap_or_else(|| Raw::new("1 = 1").into());
    for expression in rest {
        result = Binary::new(result, operator, expression).into();
    }
    result
}

/// `schema.table.name` of a column reference.
fn column_string(reference: &Column) -> String {
    let mut parts: Vec<&str> = Vec::with_capacity(3);
    if let Some(schema) = &reference.schema {
        parts.push(schema);
    }
    if let Some(table) = &reference.table {
        parts.push(table);
    }
    parts.push(&reference.name);
    parts.join(".")
}

/// What `fromAst()` reads a statement with: the dialect's serializer, for what stays raw SQL, and
/// the character its `LIKE` escapes with when a pattern names none.
struct Reading<'w> {
    serializer: &'w dyn AstWriter,
    /// PHP: `IMPLICIT_LIKE_ESCAPE`.
    implicit: Option<u8>,
}

impl Reading<'_> {
    fn serialize(&self, statement: &Select) -> Result<String> {
        self.serializer.serialize(statement)
    }

    fn serialize_expression(&self, expression: &Expression) -> Result<String> {
        self.serializer.serialize_expression(expression)
    }
}

/// What writes the SQL `fromAst()` keeps raw: the dialect's [`Serializer`], or the one a
/// subclass's `createAstSerializer()` returns.
pub trait AstWriter {
    /// A statement as SQL.
    fn serialize(&self, statement: &Select) -> Result<String>;
    /// An expression as SQL.
    fn serialize_expression(&self, expression: &Expression) -> Result<String>;
}

impl AstWriter for Serializer {
    fn serialize(&self, statement: &Select) -> Result<String> {
        Serializer::serialize(self, statement)
    }

    fn serialize_expression(&self, expression: &Expression) -> Result<String> {
        Serializer::serialize_expression(self, expression)
    }
}

/// `value` with the escape character, `%` and `_` escaped, for a `LIKE` pattern.
///
/// PHP: `escapeLikeValue()`.
fn escape_like(value: &str, escape: u8) -> String {
    let escape = char::from(escape);
    let mut out = String::with_capacity(value.len());
    for character in value.chars() {
        if character == escape || character == '%' || character == '_' {
            out.push(escape);
        }
        out.push(character);
    }
    out
}

/// A `LIKE` pattern as whether it starts with a wildcard, the text it matches and whether it ends
/// with one. `None` when it holds a wildcard anywhere else, ends in its escape, or matches nothing.
///
/// PHP: `decodeLikePattern()`.
fn decode_like(pattern: &str, escape: Option<char>) -> Option<(bool, String, bool)> {
    let characters: Vec<char> = pattern.chars().collect();
    let leading = characters.first() == Some(&'%');
    let mut value = String::new();
    let mut trailing = false;
    let mut index = usize::from(leading);
    while index < characters.len() {
        let character = characters[index];
        if Some(character) == escape {
            index += 1;
            value.push(*characters.get(index)?);
        } else if character == '%' && index == characters.len() - 1 {
            trailing = true;
        } else if character == '%' || character == '_' {
            return None;
        } else {
            value.push(character);
        }
        index += 1;
    }
    (!value.is_empty()).then_some((leading, value, trailing))
}

/// A `LIKE` as the query that writes it: `contains`, `startsWith` or `endsWith` when the pattern is
/// one of theirs, raw SQL when it is not, and `None` when its escape is not a single character or
/// is a wildcard.
///
/// PHP: `likeToQuery()`.
fn like_to_query(
    attribute: String,
    pattern: &str,
    escape: Option<&Expression>,
    negated: bool,
    reading: &Reading<'_>,
) -> Result<Option<Query>> {
    let character = match escape {
        None => reading.implicit.map(char::from),
        Some(Expression::Literal(Literal { value: Value::Str(text) })) if text.as_bytes().len() == 1 => {
            Some(char::from(text.as_bytes()[0]))
        }
        Some(_) => return Ok(None),
    };
    if matches!(character, Some('%' | '_')) {
        return Ok(None);
    }
    let Some((leading, value, trailing)) = decode_like(pattern, character).filter(|decoded| decoded.0 || decoded.2)
    else {
        let clause = match escape {
            Some(escape) => format!(" ESCAPE {}", reading.serialize_expression(escape)?),
            None => String::new(),
        };
        let keyword = if negated { " NOT LIKE ?" } else { " LIKE ?" };
        return Ok(Some(Query::raw(
            format!("{attribute}{keyword}{clause}"),
            value::list(vec![value::string(pattern)]),
        )));
    };
    Ok(Some(match (leading, trailing, negated) {
        (true, true, _) => {
            let method = if negated { Method::NotContains } else { Method::Contains };
            Query::new(method, attribute, value::list(vec![value::string(value)]), "")
        }
        (_, true, true) => Query::not_starts_with(attribute, value),
        (_, true, false) => Query::starts_with(attribute, value),
        (_, false, true) => Query::not_ends_with(attribute, value),
        (_, false, false) => Query::ends_with(attribute, value),
    }))
}

impl<D: Dialect> Builder<D> {
    /// The builder's select as a syntax tree: columns and aggregates,
    /// table, joins, filters, grouping, `HAVING`, ordering, limit, offset,
    /// `DISTINCT` and CTEs (each CTE's SQL parsed with the standard tokenizer).
    ///
    /// PHP: `Builder::toAst()`.
    pub fn to_ast(&mut self) -> Result<Select> {
        let grouped = Query::group_by_type(&self.core.pending);
        self.prepare_alias_qualification(&grouped);

        let columns = self.ast_columns(&grouped);
        let from = self.ast_from();
        let joins = self.ast_joins(&grouped)?;
        let where_clause = match grouped.filters.is_empty() {
            true => None,
            false => Some(combine(grouped.filters.iter().map(|f| self.query_to_ast(f)).collect::<Result<_>>()?, "AND")),
        };
        let column =
            value::Param::method("Utopia\\Query\\Builder::columnNameToAstExpression", 1, "col", "Builder.php", 2316);
        let group_by =
            grouped.group_by.iter().map(|c| Ok(self.column_to_ast(&column.string(c)?))).collect::<Result<Vec<_>>>()?;
        let having = self.ast_having(&grouped)?;
        let order_by = self.ast_order_by();
        let limit = grouped.limit.map(|l| Literal { value: Value::Int(l) }.into());
        let offset = grouped.offset.map(|o| Literal { value: Value::Int(o) }.into());
        let parser = Parser::new().with_literal(D::LITERAL);
        let mut ctes = Vec::with_capacity(self.core.ctes.len());
        for cte in self.core.ctes.clone() {
            // A subclass's `createTokenizer()` reads the CTE when it has one.
            let query = match self.overrides(Step::CreateTokenizer) {
                true => match self.step(Step::CreateTokenizer, &[Arg::Str(&cte.query)])? {
                    Ret::Select(read) => *read,
                    _ => parser.parse_sql(&cte.query)?,
                },
                false => parser.parse_sql(&cte.query)?,
            };
            ctes.push(Cte { name: cte.name, query, columns: cte.columns, recursive: cte.recursive });
        }

        Ok(Select {
            columns,
            from,
            joins,
            where_clause,
            group_by,
            having,
            order_by,
            limit,
            offset,
            distinct: grouped.distinct,
            ctes,
            windows: Vec::new(),
        })
    }

    fn ast_columns(&self, grouped: &ParsedQuery) -> Vec<Expression> {
        let mut columns = Vec::new();
        for aggregate in &grouped.aggregations {
            let method = aggregate.method();
            let name = method.sql_function().map_or_else(|| method.as_str().to_ascii_uppercase(), str::to_owned);
            let attribute = aggregate.attribute();
            let argument: Expression =
                if attribute == "*" || attribute.is_empty() { Star::default().into() } else { column(attribute) };
            let call =
                Func { name, arguments: vec![argument], distinct: method == Method::CountDistinct, filter: None };
            columns.push(if aggregate.alias().is_empty() {
                call.into()
            } else {
                Aliased::new(call, aggregate.alias()).into()
            });
        }
        if let Some(selection) = grouped.selections.first() {
            for value in selection.values().values() {
                columns.push(self.column_to_ast(&value::to_php_string(value)));
            }
        }
        if columns.is_empty() {
            columns.push(Star::default().into());
        }
        columns
    }

    /// PHP: `Builder::columnNameToAstExpression()`.
    fn column_to_ast(&self, name: &str) -> Expression {
        if name == "*" {
            return Star::default().into();
        }
        if name.contains('.') {
            let parts: Vec<&str> = name.splitn(3, '.').collect();
            if let [schema, table, last] = parts[..] {
                if last == "*" {
                    return Star { table: Some(table.into()), schema: Some(schema.into()) }.into();
                }
                return Column { name: last.into(), table: Some(table.into()), schema: Some(schema.into()) }.into();
            }
            if parts[1] == "*" {
                return Star { table: Some(parts[0].into()), schema: None }.into();
            }
            return Column::of(parts[0], parts[1]).into();
        }
        if self.core.qualify && !self.core.aggregation_aliases.contains(name) {
            return Column::of(self.core.alias.clone(), name).into();
        }
        column(name)
    }

    fn ast_from(&self) -> Option<TableSource> {
        if self.core.tableless || self.core.table.is_empty() {
            return None;
        }
        let alias = (!self.core.alias.is_empty()).then(|| self.core.alias.clone());
        Some(Table { name: self.core.table.clone(), alias, schema: None }.into())
    }

    fn ast_joins(&self, grouped: &ParsedQuery) -> Result<Vec<JoinClause>> {
        let mut joins = Vec::with_capacity(grouped.joins.len());
        for join in &grouped.joins {
            let kind = match join.method() {
                Method::LeftJoin => "LEFT JOIN",
                Method::RightJoin => "RIGHT JOIN",
                Method::CrossJoin => "CROSS JOIN",
                Method::FullOuterJoin => "FULL OUTER JOIN",
                Method::NaturalJoin => "NATURAL JOIN",
                _ => "JOIN",
            };
            let alias = (!join.alias().is_empty()).then(|| join.alias().to_owned());
            let table = Table { name: join.attribute().to_owned(), alias, schema: None };
            let on = join.join_on_queries();
            let condition = if on.is_empty() {
                None
            } else {
                let mut expressions = Vec::with_capacity(on.len());
                for query in on {
                    assert_join_on_predicate(query)?;
                    expressions.push(self.query_to_ast(query)?);
                }
                Some(combine(expressions, "AND"))
            };
            joins.push(JoinClause { kind: kind.to_owned(), table: table.into(), condition });
        }
        Ok(joins)
    }

    /// PHP: `Builder::queryToAstExpression()`.
    fn query_to_ast(&self, query: &Query) -> Result<Expression> {
        let attribute = query.attribute();
        let values = query.values();
        let at = |i: i64| values.get(&php_std::ArrayKey::Int(i)).filter(|v| !matches!(v, Value::Null));
        let compare = |op: &str| Binary::new(column(attribute), op, literal(at(0))).into();
        let like = |op: &str, text: String| self.like_to_ast(attribute, op, text).into();
        let escaped = |value: Option<&Value>| escape_like(&scalar(value), D::LIKE_ESCAPE);
        Ok(match query.method() {
            Method::Equal => self.equal_to_ast(attribute, values, false),
            Method::NotEqual => self.equal_to_ast(attribute, values, true),
            Method::GreaterThan => compare(">"),
            Method::GreaterThanEqual => compare(">="),
            Method::LessThan => compare("<"),
            Method::LessThanEqual => compare("<="),
            Method::Between | Method::NotBetween => {
                Between::new(column(attribute), literal(at(0)), literal(at(1)), query.method() == Method::NotBetween)
                    .into()
            }
            Method::IsNull => Unary::new("IS NULL", column(attribute), false).into(),
            Method::IsNotNull => Unary::new("IS NOT NULL", column(attribute), false).into(),
            Method::Contains | Method::ContainsAny => self.contains_to_ast(attribute, values, false),
            Method::NotContains => self.contains_to_ast(attribute, values, true),
            Method::StartsWith => like("LIKE", format!("{}%", escaped(at(0)))),
            Method::NotStartsWith => like("NOT LIKE", format!("{}%", escaped(at(0)))),
            Method::EndsWith => like("LIKE", format!("%{}", escaped(at(0)))),
            Method::NotEndsWith => like("NOT LIKE", format!("%{}", escaped(at(0)))),
            Method::And | Method::Or => {
                let operator = if query.method() == Method::Or { "OR" } else { "AND" };
                let parts = query.nested().map(|q| self.query_to_ast(q)).collect::<Result<Vec<_>>>()?;
                if parts.is_empty() {
                    Literal { value: Value::Bool(operator != "OR") }.into()
                } else {
                    combine(parts, operator)
                }
            }
            Method::On => {
                let (left, operator, right) = on_parts(query);
                if left.is_empty() || right.is_empty() {
                    return Err(Error::Validation("Join ON requires left and right columns".into()));
                }
                if !["=", "!=", "<", ">", "<=", ">=", "<>"].contains(&operator.as_str()) {
                    return Err(Error::Validation(format!("Invalid join operator: {operator}")));
                }
                Binary::new(self.column_to_ast(&left), operator, self.column_to_ast(&right)).into()
            }
            Method::Raw => Raw::new(attribute).into(),
            _ => return Err(Error::Unsupported(format!("Unsupported filter type: {}", query.method().as_str()))),
        })
    }

    fn equal_to_ast(&self, attribute: &str, values: &Array, negated: bool) -> Expression {
        if values.len() == 1 {
            let value = first(values);
            if matches!(value, Value::Null) {
                let operator = if negated { "IS NOT NULL" } else { "IS NULL" };
                return Unary::new(operator, column(attribute), false).into();
            }
            return Binary::new(column(attribute), if negated { "!=" } else { "=" }, literal(Some(&value))).into();
        }
        let items = values.values().map(|v| literal(Some(v))).collect();
        In::new(column(attribute), InList::Values(items), negated).into()
    }

    /// `attribute LIKE pattern`, with the escape the dialect declares.
    ///
    /// PHP: `buildLikeAstExpression()`.
    fn like_to_ast(&self, attribute: &str, operator: &str, pattern: String) -> Binary {
        let like = Binary::new(column(attribute), operator, Literal { value: value::string(pattern) });
        if D::DECLARES_LIKE_ESCAPE {
            like.with_escape(Literal { value: value::string(char::from(D::LIKE_ESCAPE).to_string()) })
        } else {
            like
        }
    }

    fn contains_to_ast(&self, attribute: &str, values: &Array, negated: bool) -> Expression {
        let operator = if negated { "NOT LIKE" } else { "LIKE" };
        let pattern = |v: Option<&Value>| {
            self.like_to_ast(attribute, operator, format!("%{}%", escape_like(&scalar(v), D::LIKE_ESCAPE)))
        };
        if values.len() == 1 {
            return pattern(Some(&first(values))).into();
        }
        let parts = values.values().map(|v| pattern(Some(v)).into()).collect();
        combine(parts, if negated { "AND" } else { "OR" })
    }

    fn ast_having(&self, grouped: &ParsedQuery) -> Result<Option<Expression>> {
        let mut parts = Vec::new();
        for having in &grouped.having {
            for query in having.nested() {
                parts.push(self.query_to_ast(query)?);
            }
        }
        Ok((!parts.is_empty()).then(|| combine(parts, "AND")))
    }

    fn ast_order_by(&self) -> Vec<OrderByItem> {
        Query::by_type(&self.core.pending, &[Method::OrderAsc, Method::OrderDesc, Method::OrderRandom])
            .into_iter()
            .map(|query| {
                if query.method() == Method::OrderRandom {
                    return OrderByItem::new(Raw::new("RAND()"), OrderDirection::Asc);
                }
                let direction =
                    if query.method() == Method::OrderAsc { OrderDirection::Asc } else { OrderDirection::Desc };
                let nulls = match query.value() {
                    Some(Value::Ext(Object::Nulls(n))) => Some(*n),
                    _ => None,
                };
                OrderByItem { expression: self.column_to_ast(query.attribute()), direction, nulls }
            })
            .collect()
    }

    /// A builder with the select `select` describes: its table, columns
    /// (aggregates become aggregate queries, other expressions raw selects),
    /// joins, filters, grouping, `HAVING`, ordering, limit, offset, CTEs and
    /// `DISTINCT`. Expressions without a query equivalent are kept as raw
    /// SQL, written by the dialect's serializer.
    ///
    /// PHP: `Builder::fromAst()`.
    pub fn from_ast(select: &Select) -> Result<Self> {
        Self::from_ast_with(select, &serializer(D::ast_dialect()).with_literal(D::LITERAL))
    }

    /// [`Self::from_ast`], writing what stays raw SQL with `writer`.
    ///
    /// PHP: `fromAst()` in a subclass that overrides `createAstSerializer()`.
    pub fn from_ast_with(select: &Select, writer: &dyn AstWriter) -> Result<Self> {
        let mut builder = Self::new();
        let serializer = Reading { serializer: writer, implicit: D::IMPLICIT_LIKE_ESCAPE };

        if let Some(TableSource::Table(table)) = &select.from {
            builder.from(table.name.clone(), table.alias.clone().unwrap_or_default());
        }
        builder.apply_ast_columns(select, &serializer)?;
        builder.apply_ast_joins(select, &serializer)?;
        if let Some(condition) = &select.where_clause {
            let queries = where_to_queries(condition, &serializer)?;
            builder.core.pending.extend(queries);
        }
        let group_by: Vec<String> = select
            .group_by
            .iter()
            .filter_map(|e| match e {
                Expression::Column(c) => Some(column_string(c)),
                _ => None,
            })
            .collect();
        if !group_by.is_empty() {
            builder.group_by(group_by);
        }
        if let Some(having) = &select.having {
            let queries = where_to_queries(having, &serializer)?;
            if !queries.is_empty() {
                builder.having(queries);
            }
        }
        for item in &select.order_by {
            match &item.expression {
                Expression::Column(c) => {
                    if item.direction == OrderDirection::Desc {
                        builder.sort_desc(column_string(c), item.nulls);
                    } else {
                        builder.sort_asc(column_string(c), item.nulls);
                    }
                }
                other => {
                    let direction = if item.direction == OrderDirection::Desc { " DESC" } else { " ASC" };
                    let sql = serializer.serialize_expression(other)?;
                    builder.core.raw_orders.push(Condition::new(sql + direction, Vec::new()));
                }
            }
        }
        if let Some(Expression::Literal(Literal { value })) = &select.limit
            && !matches!(value, Value::Null)
        {
            builder.limit(to_int(value));
        }
        if let Some(Expression::Literal(Literal { value })) = &select.offset
            && !matches!(value, Value::Null)
        {
            builder.offset(to_int(value));
        }
        for cte in &select.ctes {
            let sql = serializer.serialize(&cte.query)?;
            builder.core.ctes.push(CteClause::new(
                cte.name.clone(),
                sql,
                Vec::new(),
                cte.recursive,
                cte.columns.clone(),
            ));
        }
        if select.distinct {
            builder.distinct();
        }
        Ok(builder)
    }

    fn apply_ast_columns(&mut self, select: &Select, serializer: &Reading<'_>) -> Result<()> {
        let mut columns = Vec::new();
        for expression in &select.columns {
            match expression {
                Expression::Star(Star { table: None, .. }) => {}
                Expression::Aliased(a) if matches!(*a.expression, Expression::Func(_)) => {
                    let Expression::Func(f) = &*a.expression else { unreachable!() };
                    let name = f.name.to_ascii_uppercase();
                    let attribute = func_attribute(f);
                    if f.distinct && name == "COUNT" {
                        self.core.pending.push(Query::count_distinct(attribute, a.alias.clone()));
                        continue;
                    }
                    let method = match name.as_str() {
                        "COUNT" => Some(Method::Count),
                        "SUM" => Some(Method::Sum),
                        "AVG" => Some(Method::Avg),
                        "MIN" => Some(Method::Min),
                        "MAX" => Some(Method::Max),
                        "STDDEV" => Some(Method::Stddev),
                        "STDDEV_POP" => Some(Method::StddevPop),
                        "STDDEV_SAMP" => Some(Method::StddevSamp),
                        "VARIANCE" => Some(Method::Variance),
                        "VAR_POP" => Some(Method::VarPop),
                        "VAR_SAMP" => Some(Method::VarSamp),
                        "BIT_AND" => Some(Method::BitAnd),
                        "BIT_OR" => Some(Method::BitOr),
                        "BIT_XOR" => Some(Method::BitXor),
                        _ => None,
                    };
                    match method {
                        Some(m) => self.core.pending.push(Query::new(m, attribute, Array::default(), a.alias.clone())),
                        None => {
                            self.select_raw(serializer.serialize_expression(expression)?, Array::default());
                        }
                    }
                }
                Expression::Func(f) => {
                    let name = f.name.to_ascii_uppercase();
                    let attribute = func_attribute(f);
                    if f.distinct && name == "COUNT" {
                        self.core.pending.push(Query::count_distinct(attribute, ""));
                        continue;
                    }
                    let method = match name.as_str() {
                        "COUNT" => Some(Method::Count),
                        "SUM" => Some(Method::Sum),
                        "AVG" => Some(Method::Avg),
                        "MIN" => Some(Method::Min),
                        "MAX" => Some(Method::Max),
                        _ => None,
                    };
                    match method {
                        Some(m) => self.core.pending.push(Query::new(m, attribute, Array::default(), "")),
                        None => {
                            self.select_raw(serializer.serialize_expression(expression)?, Array::default());
                        }
                    }
                }
                Expression::Column(c) => columns.push(column_string(c)),
                Expression::Star(s) => columns.push(format!("{}.*", s.table.as_deref().unwrap_or(""))),
                Expression::Aliased(a) if matches!(*a.expression, Expression::Column(_)) => {
                    let Expression::Column(c) = &*a.expression else { unreachable!() };
                    let mut column = column_string(c);
                    if !a.alias.is_empty() {
                        column.push_str(" AS ");
                        column.push_str(&a.alias);
                    }
                    columns.push(column);
                }
                other => {
                    self.select_raw(serializer.serialize_expression(other)?, Array::default());
                }
            }
        }
        if !columns.is_empty() {
            self.select(columns);
        }
        Ok(())
    }

    fn apply_ast_joins(&mut self, select: &Select, serializer: &Reading<'_>) -> Result<()> {
        for join in &select.joins {
            let TableSource::Table(table) = &join.table else { continue };
            let method = match join.kind.to_ascii_uppercase().as_str() {
                "CROSS JOIN" => Method::CrossJoin,
                "NATURAL JOIN" => Method::NaturalJoin,
                "LEFT JOIN" | "LEFT OUTER JOIN" => Method::LeftJoin,
                "RIGHT JOIN" | "RIGHT OUTER JOIN" => Method::RightJoin,
                "FULL OUTER JOIN" | "FULL JOIN" => Method::FullOuterJoin,
                _ => Method::Join,
            };
            let unconditioned = method == Method::CrossJoin || method == Method::NaturalJoin;
            let on = match &join.condition {
                Some(condition) if !unconditioned => join_condition_to_queries(condition, serializer)?,
                _ => Vec::new(),
            };
            let on = value::list(on.into_iter().map(Value::from).collect::<Vec<_>>());
            self.core.pending.push(Query::new(method, table.name.clone(), on, table.alias.clone().unwrap_or_default()));
        }
        Ok(())
    }
}

/// The attribute an aggregate's first argument names (`*` otherwise).
fn func_attribute(func: &Func) -> String {
    match func.arguments.first() {
        Some(Expression::Column(c)) => column_string(c),
        _ => "*".to_owned(),
    }
}

/// PHP: `Builder::astJoinConditionToQueries()`.
fn join_condition_to_queries(condition: &Expression, serializer: &Reading<'_>) -> Result<Vec<Query>> {
    if let Expression::Binary(b) = condition {
        let operator = b.operator.to_ascii_uppercase();
        if operator == "AND" {
            let mut queries = join_condition_to_queries(&b.left, serializer)?;
            queries.extend(join_condition_to_queries(&b.right, serializer)?);
            return Ok(queries);
        }
        if operator == "OR" {
            return Ok(vec![Query::or([
                join_condition_to_query(&b.left, serializer)?,
                join_condition_to_query(&b.right, serializer)?,
            ])]);
        }
        if let (Expression::Column(left), Expression::Column(right)) = (&*b.left, &*b.right) {
            return Ok(vec![Query::on(column_string(left), column_string(right), b.operator.clone())]);
        }
    }
    match expression_to_query(condition, serializer)? {
        Some(query) if query.method().is_join_condition() => Ok(vec![query]),
        _ => Err(Error::Validation(format!(
            "Unsupported join ON condition: {}",
            serializer.serialize_expression(condition)?
        ))),
    }
}

fn join_condition_to_query(condition: &Expression, serializer: &Reading<'_>) -> Result<Query> {
    let mut queries = join_condition_to_queries(condition, serializer)?;
    Ok(if queries.len() == 1 { queries.remove(0) } else { Query::and(queries) })
}

/// PHP: `Builder::astWhereToQueries()`.
fn where_to_queries(expression: &Expression, serializer: &Reading<'_>) -> Result<Vec<Query>> {
    if let Expression::Binary(b) = expression
        && b.operator.eq_ignore_ascii_case("AND")
    {
        let mut queries = where_to_queries(&b.left, serializer)?;
        queries.extend(where_to_queries(&b.right, serializer)?);
        return Ok(queries);
    }
    if let Some(query) = expression_to_query(expression, serializer)? {
        return Ok(vec![query]);
    }
    Ok(vec![Query::raw(serializer.serialize_expression(expression)?, Array::default())])
}

/// PHP: `Builder::astExpressionToSingleQuery()`.
fn expression_to_query(expression: &Expression, serializer: &Reading<'_>) -> Result<Option<Query>> {
    match expression {
        Expression::Binary(b) => {
            let operator = b.operator.to_ascii_uppercase();
            if operator == "AND" {
                let mut queries = where_to_queries(&b.left, serializer)?;
                queries.extend(where_to_queries(&b.right, serializer)?);
                return Ok(Some(Query::and(queries)));
            }
            if operator == "OR" {
                // A side with no query of its own is kept as raw SQL, not dropped.
                let side = |side: &Expression| -> Result<Query> {
                    match expression_to_query(side, serializer)? {
                        Some(query) => Ok(query),
                        None => Ok(Query::raw(serializer.serialize_expression(side)?, Array::default())),
                    }
                };
                return Ok(Some(Query::or([side(&b.left)?, side(&b.right)?])));
            }
            if let (Expression::Column(left), Expression::Literal(Literal { value })) = (&*b.left, &*b.right) {
                let attribute = column_string(left);
                return Ok(match operator.as_str() {
                    "=" => Some(Query::equal(attribute, [value.clone()])),
                    "!=" | "<>" => Some(Query::not_equal(
                        attribute,
                        match value {
                            Value::Bool(v) => Value::Int(i64::from(*v)),
                            other => other.clone(),
                        },
                    )),
                    ">" => Some(Query::greater_than(attribute, comparable(value))),
                    ">=" => Some(Query::greater_than_equal(attribute, comparable(value))),
                    "<" => Some(Query::less_than(attribute, comparable(value))),
                    "<=" => Some(Query::less_than_equal(attribute, comparable(value))),
                    "LIKE" => {
                        like_to_query(attribute, &value::to_php_string(value), b.escape.as_deref(), false, serializer)?
                    }
                    "NOT LIKE" => {
                        like_to_query(attribute, &value::to_php_string(value), b.escape.as_deref(), true, serializer)?
                    }
                    _ => None,
                });
            }
            Ok(None)
        }
        Expression::In(i) => {
            let (Expression::Column(c), InList::Values(items)) = (&*i.expression, &i.list) else { return Ok(None) };
            let attribute = column_string(c);
            let values: Vec<Value> = items
                .iter()
                .map(|item| match item {
                    Expression::Literal(l) => l.value.clone(),
                    _ => Value::Null,
                })
                .collect();
            Ok(Some(if i.negated {
                Query::not_equal(attribute, Value::Array(value::list(values)))
            } else {
                Query::equal(attribute, values)
            }))
        }
        Expression::Between(b) => {
            let Expression::Column(c) = &*b.expression else { return Ok(None) };
            let bound = |e: &Expression| match e {
                Expression::Literal(l) => comparable(&l.value),
                _ => Value::Int(0),
            };
            let attribute = column_string(c);
            let (low, high) = (bound(&b.low), bound(&b.high));
            Ok(Some(if b.negated {
                Query::not_between(attribute, low, high)
            } else {
                Query::between(attribute, low, high)
            }))
        }
        Expression::Unary(u) => {
            let Expression::Column(c) = &*u.operand else { return Ok(None) };
            Ok(match u.operator.to_ascii_uppercase().as_str() {
                "IS NULL" => Some(Query::is_null(column_string(c))),
                "IS NOT NULL" => Some(Query::is_not_null(column_string(c))),
                _ => None,
            })
        }
        _ => Ok(None),
    }
}