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
811
812
813
814
815
816
//! MySQL: [`MySql`], and the behaviour MariaDB shares ([`MySqlFamily`]).
//!
//! PHP: `Utopia\Query\Builder\MySQL`.

use php_std::json::Flags;

use crate::builder::core::{Builder, Dialect, ExplainOptions};
use crate::builder::feature::{
    BitwiseAggregates, ConditionalAggregates, CrossJoins, FullTextSearch, Hints, InsertOrIgnore, Json, LateralJoins,
    Locking, NegatedFullTextSearch, RawSql, Rollup, Spatial, StatisticalAggregates, StringAggregates, Transactions,
    Upsert, UpsertSelect,
};
use crate::builder::sql::{self, SqlDialect, distance_operator, wkt_of};
use crate::builder::steps::{Arg, Step};
use crate::builder::types::{Condition, Statement};
use crate::error::{Error, Result};
use crate::method::Method;
use crate::query::Query;
use crate::value::{self, Array, Value};

/// A MySQL builder.
///
/// PHP: `Utopia\Query\Builder\MySQL`.
///
/// ```
/// use utopia_query::Query;
/// use utopia_query::builder::MySql;
///
/// let statement = MySql::new().from("t", "").filter([Query::equal("status", ["active", "pending"])]).build()?;
/// assert_eq!(statement.query, "SELECT * FROM `t` WHERE `status` IN (?, ?)");
/// # Ok::<(), utopia_query::Error>(())
/// ```
///
/// ```php
/// use Utopia\Query\Builder\MySQL;
/// use Utopia\Query\Query;
///
/// echo (new MySQL())->from('t')->filter([Query::equal('status', ['active', 'pending'])])->build()->query, "\n";
/// // SELECT * FROM `t` WHERE `status` IN (?, ?)
/// ```
pub type MySql = Builder<MySqlDialect>;

/// MySQL's own state: the join of a multi-table update or delete.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MySqlState {
    update_join: Option<(String, String, String, String)>,
    delete_join: Option<(String, String, String, String)>,
}

/// The MySQL dialect.
#[derive(Debug, Clone, Default)]
pub struct MySqlDialect {
    state: MySqlState,
}

/// The class whose `Spatial` trait MySQL and MariaDB use (PHP names its
/// closures and methods after it).
pub(crate) const MYSQL_CLASS: &str = "Utopia\\Query\\Builder\\MySQL";

/// What MySQL and MariaDB share: their state, and the geometry constructor.
pub trait MySqlFamily: SqlDialect {
    /// The MySQL state.
    fn mysql(b: &Builder<Self>) -> &MySqlState;
    /// The MySQL state, mutable.
    fn mysql_mut(b: &mut Builder<Self>) -> &mut MySqlState;
    /// `ST_GeomFromText(?, srid, 'axis-order=long-lat')` (MariaDB has no axis order).
    fn geom_from_text(srid: i64) -> String {
        format!("ST_GeomFromText(?, {srid}, 'axis-order=long-lat')")
    }
}

impl MySqlFamily for MySqlDialect {
    fn mysql(b: &Builder<Self>) -> &MySqlState {
        &b.dialect.state
    }

    fn mysql_mut(b: &mut Builder<Self>) -> &mut MySqlState {
        &mut b.dialect.state
    }
}

/// `/^[A-Za-z0-9_()=, \`.]+$/D`.
pub(crate) fn is_hint(hint: &str) -> bool {
    let bytes = hint.as_bytes();
    !bytes.is_empty()
        && bytes
            .iter()
            .all(|&b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'(' | b')' | b'=' | b',' | b' ' | b'`' | b'.'))
}

/// `json_encode($payload)` (default flags), `false` as `""`... PHP casts the
/// failure to a binding string only where it cannot fail; here failures are
/// the library's validation error.
pub(crate) fn encode_json_payload(payload: &Value) -> Result<String> {
    value::json_encode(payload, Flags::THROW_ON_ERROR)
        .map_err(|e| Error::Validation(format!("Invalid JSON payload: {}", e.message())))
}

/// `json_encode($values)` with default flags (`false` becomes `""` in a binding).
pub(crate) fn json_or_empty(values: &Array) -> Value {
    match value::json_encode(&Value::Array(values.clone()), Flags::NONE) {
        Ok(json) => value::string(json),
        Err(_) => Value::Bool(false),
    }
}

/// The `MATCH ... AGAINST` search shared by MySQL and MariaDB.
pub(crate) fn search_expression<D: Dialect>(
    b: &mut Builder<D>,
    attribute: &str,
    values: &Array,
    not: bool,
) -> Result<String> {
    let term = crate::builder::postgresql::search_term(values)?;
    let exact = term.ends_with('"') && term.starts_with('"');
    let mut replaced = String::with_capacity(term.len());
    for c in term.chars() {
        replaced.push(if matches!(c, '@' | '+' | '-' | '*' | ')' | '(' | '<' | '>' | '~' | '"') { ' ' } else { c });
    }
    // preg_replace('/\s+/', ' ') then trim(): runs of ASCII whitespace become one space.
    let mut collapsed = String::with_capacity(replaced.len());
    let mut in_space = false;
    for c in replaced.chars() {
        if matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0B' | '\x0C') {
            if !in_space {
                collapsed.push(' ');
            }
            in_space = true;
        } else {
            collapsed.push(c);
            in_space = false;
        }
    }
    let sanitized = collapsed.trim_matches([' ', '\t', '\n', '\r', '\0', '\x0B']);
    if sanitized.is_empty() {
        return Ok(if not { "1 = 1" } else { "1 = 0" }.into());
    }
    if exact {
        let words = split_search_words(&term);
        let indexed: Vec<&str> = words.iter().map(String::as_str).filter(|word| is_indexed_search_word(word)).collect();
        if !indexed.is_empty() {
            return Ok(exact_search_expression(b, attribute, &words, &indexed, not));
        }
    }
    let sanitized = if exact { format!("\"{sanitized}\"") } else { format!("{sanitized}*") };
    b.add_binding(value::string(sanitized), None);
    Ok(if not {
        format!("NOT (MATCH({attribute}) AGAINST(? IN BOOLEAN MODE))")
    } else {
        format!("MATCH({attribute}) AGAINST(? IN BOOLEAN MODE)")
    })
}

/// InnoDB's `innodb_ft_min_token_size`: shorter words are not indexed.
///
/// PHP: `MySQL::FULL_TEXT_MINIMUM_WORD_LENGTH`.
const FULL_TEXT_MINIMUM_WORD_LENGTH: usize = 3;

/// InnoDB's default full-text stopwords, which are not indexed.
///
/// PHP: `MySQL::FULL_TEXT_STOPWORDS`.
const FULL_TEXT_STOPWORDS: &[&str] = &[
    "a", "about", "an", "are", "as", "at", "be", "by", "com", "de", "en", "for", "from", "how", "i", "in", "is", "it",
    "la", "of", "on", "or", "that", "the", "this", "to", "was", "what", "when", "where", "who", "will", "with", "und",
    "www",
];

/// An exact search that requires every indexed word through the full-text
/// index and checks the words' order against the stored value: InnoDB loses
/// phrase matches for rows whose transactions commit out of document ID
/// order (MySQL bug #110448, also present in MariaDB).
///
/// PHP: `MySQL::compileExactSearchExpression()` (private).
fn exact_search_expression<D: Dialect>(
    b: &mut Builder<D>,
    attribute: &str,
    words: &[String],
    indexed: &[&str],
    not: bool,
) -> String {
    const SEPARATOR: &str = "[^[:alnum:]_]";
    b.add_binding(value::string(format!("+{}", indexed.join(" +"))), None);
    b.add_binding(
        value::string(format!("(^|{SEPARATOR}){}({SEPARATOR}|$)", words.join(&format!("{SEPARATOR}+")))),
        None,
    );
    let expression = format!("MATCH({attribute}) AGAINST(? IN BOOLEAN MODE) AND {attribute} REGEXP ?");
    if not { format!("NOT ({expression})") } else { format!("({expression})") }
}

/// The words of a search term: runs of letters, numbers, `_` and `'`, with
/// the quotes trimmed off their ends.
///
/// PHP: `MySQL::splitSearchWords()` (private).
fn split_search_words(term: &str) -> Vec<String> {
    use php_std::pcre::{PREG_SPLIT_NO_EMPTY, Value as PcreValue, preg_split};
    let PcreValue::Array(pieces) = preg_split(br"/[^\p{L}\p{N}_']+/u", term.as_bytes(), -1, PREG_SPLIT_NO_EMPTY).value
    else {
        return Vec::new();
    };
    pieces
        .entries()
        .iter()
        .filter_map(|(_, piece)| match piece {
            PcreValue::Str(piece) => Some(String::from_utf8_lossy(piece).trim_matches('\'').to_owned()),
            _ => None,
        })
        .filter(|word| !word.is_empty())
        .collect()
}

/// Whether InnoDB indexes `word`: long enough and not a stopword.
///
/// PHP: `MySQL::isIndexedSearchWord()` (private).
fn is_indexed_search_word(word: &str) -> bool {
    php_std::mb::mb_strlen(word.as_bytes()) >= FULL_TEXT_MINIMUM_WORD_LENGTH
        && !FULL_TEXT_STOPWORDS
            .contains(&String::from_utf8_lossy(&php_std::mb::mb_strtolower(word.as_bytes())).as_ref())
}

/// MySQL's `build()`: the group-by modifier and the hints.
pub(crate) fn build<D: Dialect>(b: &mut Builder<D>) -> Result<Statement> {
    let result = b.base_build()?;
    let mut query = result.query.clone();
    if let Some(modifier) = b.core.group_by_modifier.clone()
        && let Some(group_by) = query.find("GROUP BY ")
    {
        let after = group_by + 9;
        let end = ["HAVING ", "WINDOW ", "ORDER BY ", "LIMIT ", "FOR "]
            .iter()
            .filter_map(|keyword| query.get(after..).and_then(|rest| rest.find(keyword)).map(|p| p + after))
            .min();
        let insert_at = end.unwrap_or(query.len());
        let head = query[..insert_at].trim_end_matches([' ', '\t', '\n', '\r', '\0', '\x0B']);
        let mut rebuilt = format!("{head} {modifier}");
        if let Some(end) = end {
            rebuilt.push(' ');
            rebuilt.push_str(&query[end..]);
        }
        query = rebuilt;
    }
    if !b.core.hints.is_empty() {
        let hint = format!("/*+ {} */", b.core.hints.join(" "));
        if let Some(rest) = query.strip_prefix("SELECT") {
            let space = rest.len() - rest.trim_start_matches([' ', '\t', '\n', '\r', '\x0B', '\x0C']).len();
            let distinct = space > 0 && rest[space..].starts_with("DISTINCT");
            let keep = if distinct { space + 8 } else { 0 };
            query = format!("SELECT{} {hint}{}", &rest[..keep], &rest[keep..]);
        }
    }
    if query != result.query {
        return Ok(Statement::with_parts(query, result.bindings, result.read_only, b.core.executor.clone(), None));
    }
    Ok(result)
}

/// MySQL's `update()`: JSON assignments, then an update join or the base update.
pub(crate) fn update<D: MySqlFamily>(b: &mut Builder<D>) -> Result<Statement> {
    for (column, condition) in b.core.json_sets.0.clone() {
        b.core.raw_sets.set(column.clone(), condition.expression);
        b.core.raw_set_bindings.set(column, condition.bindings);
    }
    let result = if D::mysql(b).update_join.is_some() { update_join(b) } else { b.base_update() };
    b.core.json_sets.clear();
    result
}

fn update_join<D: MySqlFamily>(b: &mut Builder<D>) -> Result<Statement> {
    b.core.bindings.clear();
    b.validate_table()?;
    let (table, left, right, alias) = D::mysql(b).update_join.clone().unwrap_or_default();
    let mut join = b.quote(&table)?;
    if !alias.is_empty() {
        join.push_str(" AS ");
        join.push_str(&b.quote(&alias)?);
    }
    let mut sql = format!(
        "UPDATE {} JOIN {join} ON {} = {}",
        b.quote(&b.core.table.clone())?,
        b.resolve_and_wrap(&left)?,
        b.resolve_and_wrap(&right)?
    );
    let assignments = b.compile_assignments()?;
    if assignments.is_empty() {
        return Err(Error::Validation("No assignments for UPDATE. Call set() or setRaw() before update().".into()));
    }
    sql.push_str(" SET ");
    sql.push_str(&assignments.join(", "));
    let mut parts = vec![sql];
    b.compile_where_clauses(&mut parts, None)?;
    Ok(b.statement(parts.join(" ")))
}

/// MySQL's `delete()`: a delete join, or the base delete.
pub(crate) fn delete<D: MySqlFamily>(b: &mut Builder<D>) -> Result<Statement> {
    let Some((alias, table, left, right)) = D::mysql(b).delete_join.clone() else {
        return b.base_delete();
    };
    b.core.bindings.clear();
    b.validate_table()?;
    let sql = format!(
        "DELETE {} FROM {} AS {} JOIN {} ON {} = {}",
        b.quote(&alias)?,
        b.quote(&b.core.table.clone())?,
        b.quote(&alias)?,
        b.quote(&table)?,
        b.resolve_and_wrap(&left)?,
        b.resolve_and_wrap(&right)?
    );
    let mut parts = vec![sql];
    b.compile_where_clauses(&mut parts, None)?;
    Ok(b.statement(parts.join(" ")))
}

/// `INSERT IGNORE INTO ...`.
pub(crate) fn insert_or_ignore<D: Dialect>(b: &mut Builder<D>) -> Result<Statement> {
    b.core.bindings.clear();
    let (sql, bindings) = b.compile_insert_body()?;
    b.add_bindings(bindings);
    let sql = match sql.strip_prefix("INSERT INTO") {
        Some(rest) => format!("INSERT IGNORE INTO{rest}"),
        None => sql,
    };
    Ok(b.statement(sql))
}

/// `INSERT INTO table () VALUES ()`.
pub(crate) fn insert_default_values<D: Dialect>(b: &mut Builder<D>) -> Result<Statement> {
    b.core.bindings.clear();
    b.validate_table()?;
    let sql = format!("INSERT INTO {} () VALUES ()", b.quote(&b.core.table.clone())?);
    Ok(b.statement(sql))
}

/// `EXPLAIN [ANALYZE] [FORMAT=...]`.
pub(crate) fn explain<D: Dialect>(b: &mut Builder<D>, analyze: bool, options: &ExplainOptions) -> Result<Statement> {
    let result = b.built()?;
    let mut prefix = "EXPLAIN".to_owned();
    if analyze {
        prefix.push_str(" ANALYZE");
    }
    if !options.format.is_empty() {
        prefix.push_str(" FORMAT=");
        prefix.push_str(&options.format.to_ascii_uppercase());
    }
    Ok(Statement::with_parts(
        format!("{prefix} {}", result.query),
        result.bindings,
        true,
        b.core.executor.clone(),
        None,
    ))
}

/// MySQL's `reset()` of its own state (hints, JSON sets, the modifier, joins).
pub(crate) fn reset<D: MySqlFamily>(b: &mut Builder<D>) {
    b.core.hints.clear();
    b.core.json_sets.clear();
    b.reset_group_by_modifier();
    *D::mysql_mut(b) = MySqlState::default();
}

/// `ST_Distance(...) operator ?`.
pub(crate) fn spatial_distance<D: MySqlFamily>(
    b: &mut Builder<D>,
    method: Method,
    attribute: &str,
    values: &Array,
) -> Result<String> {
    let filter = sql::distance_filter(values, "Builder/MySQL.php", 484)?;
    let wkt = wkt_of(b, &filter.geometry)?;
    let operator = distance_operator(method);
    b.add_binding(wkt, None);
    b.add_binding(Value::Float(filter.distance), None);
    if filter.meters {
        return Ok(format!(
            "ST_Distance(ST_SRID({attribute}, 4326), {}, 'metre') {operator} ?",
            b.step_string(Step::GeomFromText, &[Arg::Int(Some(4326))])?
        ));
    }
    let geometry = b.step_string(Step::GeomFromText, &[Arg::Int(Some(0))])?;
    Ok(format!("ST_Distance(ST_SRID({attribute}, 0), {geometry}) {operator} ?"))
}

/// `function(attribute, ST_GeomFromText(?, 4326, ...))`, negated with `NOT`.
pub(crate) fn spatial_predicate<D: MySqlFamily>(
    b: &mut Builder<D>,
    function: &str,
    attribute: &str,
    values: &Array,
    not: bool,
) -> Result<String> {
    let wkt = sql::predicate_wkt(b, values, MYSQL_CLASS, "Builder/MySQL.php", 513)?;
    b.add_binding(value::string(wkt), None);
    let geometry = b.step_string(Step::GeomFromText, &[Arg::Int(Some(4326))])?;
    let expression = format!("{function}({attribute}, {geometry})");
    Ok(if not { format!("NOT {expression}") } else { expression })
}

/// `JSON_CONTAINS(attribute, ?)`.
pub(crate) fn json_contains<D: Dialect>(
    b: &mut Builder<D>,
    attribute: &str,
    values: &Array,
    not: bool,
) -> Result<String> {
    let payload = values.get(&php_std::ArrayKey::Int(0)).cloned().unwrap_or(Value::Null);
    b.add_binding(value::string(encode_json_payload(&payload)?), None);
    let expression = format!("JSON_CONTAINS({attribute}, ?)");
    Ok(if not { format!("NOT {expression}") } else { expression })
}

/// `JSON_OVERLAPS(attribute, ?)`.
pub(crate) fn json_overlaps<D: Dialect>(b: &mut Builder<D>, attribute: &str, values: &Array) -> Result<String> {
    let payload = values.get(&php_std::ArrayKey::Int(0)).cloned().unwrap_or(Value::Null);
    b.add_binding(value::string(encode_json_payload(&payload)?), None);
    Ok(format!("JSON_OVERLAPS({attribute}, ?)"))
}

/// `JSON_EXTRACT(attribute, '$.path') operator ?`.
pub(crate) fn json_path<D: Dialect>(b: &mut Builder<D>, attribute: &str, values: &Array) -> Result<String> {
    let (path, operator) = crate::builder::postgresql::json_path_parts(b, values)?;
    Ok(format!("JSON_EXTRACT({attribute}, '$.{path}') {operator} ?"))
}

impl Dialect for MySqlDialect {
    const CLASS: &'static str = "Utopia\\Query\\Builder\\MySQL";
    const LIKE_ESCAPE: u8 = b'!';
    const DECLARES_LIKE_ESCAPE: bool = true;

    fn base_step(
        b: &mut Builder<Self>,
        step: crate::builder::Step,
        arguments: &[crate::builder::Arg<'_>],
    ) -> Option<Result<crate::builder::Ret>> {
        sql::sql_base_step(b, step, arguments)
            .or_else(|| crate::builder::feature::aggregates_base_step::<Self>(step, arguments))
            .or_else(|| match (step, arguments) {
                (crate::builder::Step::GeomFromText, [crate::builder::Arg::Int(Some(srid))]) => {
                    Some(Ok(crate::builder::Ret::Str(Self::geom_from_text(*srid))))
                }
                _ => None,
            })
    }

    fn compile_random(_b: &Builder<Self>) -> String {
        "RAND()".into()
    }

    fn compile_regex(b: &mut Builder<Self>, attribute: &str, values: &Array, column: Option<&str>) -> Result<String> {
        b.add_binding(crate::builder::core::first(values), column);
        Ok(format!("{attribute} REGEXP ?"))
    }

    fn compile_contains_all(
        b: &mut Builder<Self>,
        attribute: &str,
        values: &Array,
        column: Option<&str>,
    ) -> Result<String> {
        if let Some(sql) = b.flavored_contains_all(attribute, values, column) {
            return Ok(sql);
        }
        b.base_compile_contains_all(attribute, values, column)
    }

    fn compile_filter(b: &mut Builder<Self>, query: &Query) -> Result<String> {
        sql::sql_compile_filter(b, query)
    }

    fn build(b: &mut Builder<Self>) -> Result<Statement> {
        build(b)
    }

    fn update(b: &mut Builder<Self>) -> Result<Statement> {
        update(b)
    }

    fn delete(b: &mut Builder<Self>) -> Result<Statement> {
        delete(b)
    }

    fn insert_default_values(b: &mut Builder<Self>) -> Result<Statement> {
        insert_default_values(b)
    }

    fn explain(b: &mut Builder<Self>, analyze: bool, options: &ExplainOptions) -> Result<Statement> {
        explain(b, analyze, options)
    }

    fn reset(b: &mut Builder<Self>) {
        reset(b)
    }

    fn ast_dialect() -> crate::builder::AstDialect {
        crate::builder::AstDialect::MySql
    }
}

impl SqlDialect for MySqlDialect {
    fn compile_search_expression(b: &mut Builder<Self>, attribute: &str, values: &Array, not: bool) -> Result<String> {
        match b.flavored_search_values(values) {
            Some(values) => search_expression(b, attribute, &values, not),
            None => search_expression(b, attribute, values, not),
        }
    }

    fn compile_spatial_distance(
        b: &mut Builder<Self>,
        method: Method,
        attribute: &str,
        values: &Array,
    ) -> Result<String> {
        spatial_distance(b, method, attribute, values)
    }

    fn compile_spatial_predicate(
        b: &mut Builder<Self>,
        function: &str,
        attribute: &str,
        values: &Array,
        not: bool,
    ) -> Result<String> {
        spatial_predicate(b, function, attribute, values, not)
    }

    fn compile_spatial_covers_predicate(
        b: &mut Builder<Self>,
        attribute: &str,
        values: &Array,
        not: bool,
    ) -> Result<String> {
        // Through the step, so a subclass's compileSpatialPredicate() writes this one too.
        b.step_string(
            crate::builder::Step::CompileSpatialPredicate,
            &[
                crate::builder::Arg::Str("ST_Contains"),
                crate::builder::Arg::Str(attribute),
                crate::builder::Arg::Values(values),
                crate::builder::Arg::Bool(not),
            ],
        )
    }

    fn compile_json_contains_expression(
        b: &mut Builder<Self>,
        attribute: &str,
        values: &Array,
        not: bool,
    ) -> Result<String> {
        json_contains(b, attribute, values, not)
    }

    fn compile_json_overlaps_expression(b: &mut Builder<Self>, attribute: &str, values: &Array) -> Result<String> {
        json_overlaps(b, attribute, values)
    }

    fn compile_json_path_expression(b: &mut Builder<Self>, attribute: &str, values: &Array) -> Result<String> {
        json_path(b, attribute, values)
    }

    fn compile_conflict_header(_b: &mut Builder<Self>) -> Result<String> {
        Ok("ON DUPLICATE KEY UPDATE".into())
    }

    fn compile_conflict_assignment(wrapped: &str) -> String {
        format!("VALUES({wrapped})")
    }
}

/// The SQL of a conflict clause for a SQL dialect.
pub(crate) fn conflict_clause<D: SqlDialect>(b: &mut Builder<D>) -> Result<String> {
    b.step_string(Step::CompileConflictClause, &[])
}

/// The builder's own `compileConflictClause()`.
pub(crate) fn base_conflict_clause<D: SqlDialect>(b: &mut Builder<D>) -> Result<String> {
    b.compile_conflict_clause(
        |b| b.step_string(Step::CompileConflictHeader, &[]),
        |b, wrapped| b.step_string(Step::CompileConflictAssignment, &[Arg::Str(wrapped)]),
    )
}

/// MySQL's JSON column updates, shared with MariaDB.
pub(crate) mod json_sets {
    use super::*;

    pub(crate) fn append<D: Dialect>(b: &mut Builder<D>, column: &str, values: &Array) -> Result<()> {
        let wrapped = b.resolve_and_wrap(column)?;
        b.core.json_sets.set(
            column,
            Condition::new(
                format!("JSON_MERGE_PRESERVE(IFNULL({wrapped}, JSON_ARRAY()), ?)"),
                vec![json_or_empty(values)],
            ),
        );
        Ok(())
    }

    pub(crate) fn prepend<D: Dialect>(b: &mut Builder<D>, column: &str, values: &Array) -> Result<()> {
        let wrapped = b.resolve_and_wrap(column)?;
        b.core.json_sets.set(
            column,
            Condition::new(
                format!("JSON_MERGE_PRESERVE(?, IFNULL({wrapped}, JSON_ARRAY()))"),
                vec![json_or_empty(values)],
            ),
        );
        Ok(())
    }

    pub(crate) fn insert<D: Dialect>(b: &mut Builder<D>, column: &str, index: i64, value: Value) -> Result<()> {
        let wrapped = b.resolve_and_wrap(column)?;
        b.core.json_sets.set(
            column,
            Condition::new(
                format!("JSON_ARRAY_INSERT({wrapped}, ?, ?)"),
                vec![value::string(format!("$[{index}]")), value],
            ),
        );
        Ok(())
    }

    pub(crate) fn remove<D: Dialect>(b: &mut Builder<D>, column: &str, value: Value) -> Result<()> {
        let wrapped = b.resolve_and_wrap(column)?;
        b.core.json_sets.set(
            column,
            Condition::new(
                // The value is a LIKE pattern to JSON_SEARCH, and a value that is not there removes nothing.
                format!(
                    "COALESCE(JSON_REMOVE({wrapped}, JSON_UNQUOTE(JSON_SEARCH({wrapped}, 'one', ?, {}))), {wrapped})",
                    D::LITERAL.quote(&char::from(D::LIKE_ESCAPE).to_string())?
                ),
                vec![crate::value::string(crate::builder::core::escape_like_value(&value, D::LIKE_ESCAPE))],
            ),
        );
        Ok(())
    }

    pub(crate) fn intersect<D: Dialect>(b: &mut Builder<D>, column: &str, values: &Array) -> Result<()> {
        let wrapped = b.resolve_and_wrap(column)?;
        let expression = format!(
            "(SELECT JSON_ARRAYAGG(val) FROM JSON_TABLE({wrapped}, '$[*]' COLUMNS(val JSON PATH '$')) AS jt WHERE JSON_CONTAINS(?, val))"
        );
        b.core.raw_sets.set(column, expression);
        b.core.raw_set_bindings.set(column, vec![json_or_empty(values)]);
        Ok(())
    }

    pub(crate) fn diff<D: Dialect>(b: &mut Builder<D>, column: &str, values: &Array) -> Result<()> {
        let wrapped = b.resolve_and_wrap(column)?;
        let expression = format!(
            "(SELECT JSON_ARRAYAGG(val) FROM JSON_TABLE({wrapped}, '$[*]' COLUMNS(val JSON PATH '$')) AS jt WHERE NOT JSON_CONTAINS(?, val))"
        );
        b.core.raw_sets.set(column, expression);
        b.core.raw_set_bindings.set(column, vec![json_or_empty(values)]);
        Ok(())
    }

    pub(crate) fn unique<D: Dialect>(b: &mut Builder<D>, column: &str) -> Result<()> {
        let wrapped = b.resolve_and_wrap(column)?;
        let expression = format!(
            "(SELECT JSON_ARRAYAGG(val) FROM (SELECT DISTINCT val FROM JSON_TABLE({wrapped}, '$[*]' COLUMNS(val JSON PATH '$')) AS jt) AS dt)"
        );
        b.core.raw_sets.set(column, expression);
        b.core.raw_set_bindings.set(column, Vec::new());
        Ok(())
    }

    pub(crate) fn path<D: Dialect>(b: &mut Builder<D>, column: &str, path: &str, value: Value) -> Result<()> {
        if !path.starts_with('$') {
            return Err(Error::Validation(format!("JSON path must start with '$': {path}")));
        }
        let wrapped = b.resolve_and_wrap(column)?;
        b.core
            .json_sets
            .set(column, Condition::new(format!("JSON_SET({wrapped}, ?, ?)"), vec![value::string(path), value]));
        Ok(())
    }
}

impl Locking for MySqlDialect {}
impl Transactions for MySqlDialect {}
impl StatisticalAggregates for MySqlDialect {}
impl BitwiseAggregates for MySqlDialect {}
impl RawSql for MySqlDialect {}
impl CrossJoins for MySqlDialect {}
impl LateralJoins for MySqlDialect {}
impl Spatial for MySqlDialect {}
impl FullTextSearch for MySqlDialect {}
impl NegatedFullTextSearch for MySqlDialect {}
impl ConditionalAggregates for MySqlDialect {}

impl Json for MySqlDialect {
    fn set_json_append(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
        json_sets::append(b, column, values)
    }
    fn set_json_prepend(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
        json_sets::prepend(b, column, values)
    }
    fn set_json_insert(b: &mut Builder<Self>, column: &str, index: i64, value: Value) -> Result<()> {
        json_sets::insert(b, column, index, value)
    }
    fn set_json_remove(b: &mut Builder<Self>, column: &str, value: Value) -> Result<()> {
        json_sets::remove(b, column, value)
    }
    fn set_json_intersect(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
        json_sets::intersect(b, column, values)
    }
    fn set_json_diff(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
        json_sets::diff(b, column, values)
    }
    fn set_json_unique(b: &mut Builder<Self>, column: &str) -> Result<()> {
        json_sets::unique(b, column)
    }
    fn set_json_path(b: &mut Builder<Self>, column: &str, path: &str, value: Value) -> Result<()> {
        json_sets::path(b, column, path, value)
    }
}

impl Hints for MySqlDialect {
    fn hint(b: &mut Builder<Self>, hint: &str) -> Result<()> {
        add_hint(b, hint)
    }
}

/// Adds a validated optimizer hint.
pub(crate) fn add_hint<D: Dialect>(b: &mut Builder<D>, hint: &str) -> Result<()> {
    if !is_hint(hint) {
        return Err(Error::Validation(format!("Invalid hint: {hint}")));
    }
    b.core.hints.push(hint.to_owned());
    Ok(())
}

impl StringAggregates for MySqlDialect {
    fn group_concat_expr(column: &str, order_by: &str) -> String {
        if order_by.is_empty() {
            format!("GROUP_CONCAT({column} SEPARATOR ?)")
        } else {
            format!("GROUP_CONCAT({column} {order_by} SEPARATOR ?)")
        }
    }
    fn json_array_agg_expr(column: &str) -> String {
        format!("JSON_ARRAYAGG({column})")
    }
    fn json_object_agg_expr(key: &str, value: &str) -> String {
        format!("JSON_OBJECTAGG({key}, {value})")
    }
}

impl Rollup for MySqlDialect {
    fn with_rollup(b: &mut Builder<Self>) {
        b.core.group_by_modifier = Some("WITH ROLLUP".into());
    }
}

impl Upsert for MySqlDialect {
    fn upsert(b: &mut Builder<Self>) -> Result<Statement> {
        b.compile_upsert(conflict_clause)
    }
}

impl UpsertSelect for MySqlDialect {
    fn upsert_select(b: &mut Builder<Self>) -> Result<Statement> {
        b.compile_upsert_select(conflict_clause)
    }
}

impl InsertOrIgnore for MySqlDialect {
    fn insert_or_ignore(b: &mut Builder<Self>) -> Result<Statement> {
        insert_or_ignore(b)
    }
}

impl<D: MySqlFamily> Builder<D> {
    /// `UPDATE table JOIN join [AS alias] ON left = right SET ...`.
    ///
    /// PHP: `updateJoin()`.
    pub fn update_join(
        &mut self,
        table: impl Into<String>,
        left: impl Into<String>,
        right: impl Into<String>,
        alias: impl Into<String>,
    ) -> &mut Self {
        let table = table.into();
        self.defer_unbound(&format!("update joining table '{table}'"));
        D::mysql_mut(self).update_join = Some((table, left.into(), right.into(), alias.into()));
        self
    }

    /// `DELETE alias FROM table AS alias JOIN join ON left = right`.
    ///
    /// PHP: `deleteJoin()`.
    pub fn delete_join(
        &mut self,
        alias: impl Into<String>,
        table: impl Into<String>,
        left: impl Into<String>,
        right: impl Into<String>,
    ) -> &mut Self {
        let table = table.into();
        self.defer_unbound(&format!("delete joining table '{table}'"));
        D::mysql_mut(self).delete_join = Some((alias.into(), table, left.into(), right.into()));
        self
    }

    /// The `MAX_EXECUTION_TIME(ms)` hint.
    ///
    /// PHP: `maxExecutionTime()`.
    pub fn max_execution_time(&mut self, ms: i64) -> Result<&mut Self> {
        add_hint(self, &format!("MAX_EXECUTION_TIME({ms})"))?;
        Ok(self)
    }
}