Skip to main content

utopia_query/builder/
mysql.rs

1//! MySQL: [`MySql`], and the behaviour MariaDB shares ([`MySqlFamily`]).
2//!
3//! PHP: `Utopia\Query\Builder\MySQL`.
4
5use php_std::json::Flags;
6
7use crate::builder::core::{Builder, Dialect, ExplainOptions};
8use crate::builder::feature::{
9    BitwiseAggregates, ConditionalAggregates, CrossJoins, FullTextSearch, Hints, InsertOrIgnore, Json, LateralJoins,
10    Locking, NegatedFullTextSearch, RawSql, Rollup, Spatial, StatisticalAggregates, StringAggregates, Transactions,
11    Upsert, UpsertSelect,
12};
13use crate::builder::sql::{self, SqlDialect, distance_operator, wkt_of};
14use crate::builder::steps::{Arg, Step};
15use crate::builder::types::{Condition, Statement};
16use crate::error::{Error, Result};
17use crate::method::Method;
18use crate::query::Query;
19use crate::value::{self, Array, Value};
20
21/// A MySQL builder.
22///
23/// PHP: `Utopia\Query\Builder\MySQL`.
24///
25/// ```
26/// use utopia_query::Query;
27/// use utopia_query::builder::MySql;
28///
29/// let statement = MySql::new().from("t", "").filter([Query::equal("status", ["active", "pending"])]).build()?;
30/// assert_eq!(statement.query, "SELECT * FROM `t` WHERE `status` IN (?, ?)");
31/// # Ok::<(), utopia_query::Error>(())
32/// ```
33///
34/// ```php
35/// use Utopia\Query\Builder\MySQL;
36/// use Utopia\Query\Query;
37///
38/// echo (new MySQL())->from('t')->filter([Query::equal('status', ['active', 'pending'])])->build()->query, "\n";
39/// // SELECT * FROM `t` WHERE `status` IN (?, ?)
40/// ```
41pub type MySql = Builder<MySqlDialect>;
42
43/// MySQL's own state: the join of a multi-table update or delete.
44#[derive(Debug, Clone, Default, PartialEq, Eq)]
45pub struct MySqlState {
46    update_join: Option<(String, String, String, String)>,
47    delete_join: Option<(String, String, String, String)>,
48}
49
50/// The MySQL dialect.
51#[derive(Debug, Clone, Default)]
52pub struct MySqlDialect {
53    state: MySqlState,
54}
55
56/// The class whose `Spatial` trait MySQL and MariaDB use (PHP names its
57/// closures and methods after it).
58pub(crate) const MYSQL_CLASS: &str = "Utopia\\Query\\Builder\\MySQL";
59
60/// What MySQL and MariaDB share: their state, and the geometry constructor.
61pub trait MySqlFamily: SqlDialect {
62    /// The MySQL state.
63    fn mysql(b: &Builder<Self>) -> &MySqlState;
64    /// The MySQL state, mutable.
65    fn mysql_mut(b: &mut Builder<Self>) -> &mut MySqlState;
66    /// `ST_GeomFromText(?, srid, 'axis-order=long-lat')` (MariaDB has no axis order).
67    fn geom_from_text(srid: i64) -> String {
68        format!("ST_GeomFromText(?, {srid}, 'axis-order=long-lat')")
69    }
70}
71
72impl MySqlFamily for MySqlDialect {
73    fn mysql(b: &Builder<Self>) -> &MySqlState {
74        &b.dialect.state
75    }
76
77    fn mysql_mut(b: &mut Builder<Self>) -> &mut MySqlState {
78        &mut b.dialect.state
79    }
80}
81
82/// `/^[A-Za-z0-9_()=, \`.]+$/D`.
83pub(crate) fn is_hint(hint: &str) -> bool {
84    let bytes = hint.as_bytes();
85    !bytes.is_empty()
86        && bytes
87            .iter()
88            .all(|&b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'(' | b')' | b'=' | b',' | b' ' | b'`' | b'.'))
89}
90
91/// `json_encode($payload)` (default flags), `false` as `""`... PHP casts the
92/// failure to a binding string only where it cannot fail; here failures are
93/// the library's validation error.
94pub(crate) fn encode_json_payload(payload: &Value) -> Result<String> {
95    value::json_encode(payload, Flags::THROW_ON_ERROR)
96        .map_err(|e| Error::Validation(format!("Invalid JSON payload: {}", e.message())))
97}
98
99/// `json_encode($values)` with default flags (`false` becomes `""` in a binding).
100pub(crate) fn json_or_empty(values: &Array) -> Value {
101    match value::json_encode(&Value::Array(values.clone()), Flags::NONE) {
102        Ok(json) => value::string(json),
103        Err(_) => Value::Bool(false),
104    }
105}
106
107/// The `MATCH ... AGAINST` search shared by MySQL and MariaDB.
108pub(crate) fn search_expression<D: Dialect>(
109    b: &mut Builder<D>,
110    attribute: &str,
111    values: &Array,
112    not: bool,
113) -> Result<String> {
114    let term = crate::builder::postgresql::search_term(values)?;
115    let exact = term.ends_with('"') && term.starts_with('"');
116    let mut replaced = String::with_capacity(term.len());
117    for c in term.chars() {
118        replaced.push(if matches!(c, '@' | '+' | '-' | '*' | ')' | '(' | '<' | '>' | '~' | '"') { ' ' } else { c });
119    }
120    // preg_replace('/\s+/', ' ') then trim(): runs of ASCII whitespace become one space.
121    let mut collapsed = String::with_capacity(replaced.len());
122    let mut in_space = false;
123    for c in replaced.chars() {
124        if matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0B' | '\x0C') {
125            if !in_space {
126                collapsed.push(' ');
127            }
128            in_space = true;
129        } else {
130            collapsed.push(c);
131            in_space = false;
132        }
133    }
134    let sanitized = collapsed.trim_matches([' ', '\t', '\n', '\r', '\0', '\x0B']);
135    if sanitized.is_empty() {
136        return Ok(if not { "1 = 1" } else { "1 = 0" }.into());
137    }
138    if exact {
139        let words = split_search_words(&term);
140        let indexed: Vec<&str> = words.iter().map(String::as_str).filter(|word| is_indexed_search_word(word)).collect();
141        if !indexed.is_empty() {
142            return Ok(exact_search_expression(b, attribute, &words, &indexed, not));
143        }
144    }
145    let sanitized = if exact { format!("\"{sanitized}\"") } else { format!("{sanitized}*") };
146    b.add_binding(value::string(sanitized), None);
147    Ok(if not {
148        format!("NOT (MATCH({attribute}) AGAINST(? IN BOOLEAN MODE))")
149    } else {
150        format!("MATCH({attribute}) AGAINST(? IN BOOLEAN MODE)")
151    })
152}
153
154/// InnoDB's `innodb_ft_min_token_size`: shorter words are not indexed.
155///
156/// PHP: `MySQL::FULL_TEXT_MINIMUM_WORD_LENGTH`.
157const FULL_TEXT_MINIMUM_WORD_LENGTH: usize = 3;
158
159/// InnoDB's default full-text stopwords, which are not indexed.
160///
161/// PHP: `MySQL::FULL_TEXT_STOPWORDS`.
162const FULL_TEXT_STOPWORDS: &[&str] = &[
163    "a", "about", "an", "are", "as", "at", "be", "by", "com", "de", "en", "for", "from", "how", "i", "in", "is", "it",
164    "la", "of", "on", "or", "that", "the", "this", "to", "was", "what", "when", "where", "who", "will", "with", "und",
165    "www",
166];
167
168/// An exact search that requires every indexed word through the full-text
169/// index and checks the words' order against the stored value: InnoDB loses
170/// phrase matches for rows whose transactions commit out of document ID
171/// order (MySQL bug #110448, also present in MariaDB).
172///
173/// PHP: `MySQL::compileExactSearchExpression()` (private).
174fn exact_search_expression<D: Dialect>(
175    b: &mut Builder<D>,
176    attribute: &str,
177    words: &[String],
178    indexed: &[&str],
179    not: bool,
180) -> String {
181    const SEPARATOR: &str = "[^[:alnum:]_]";
182    b.add_binding(value::string(format!("+{}", indexed.join(" +"))), None);
183    b.add_binding(
184        value::string(format!("(^|{SEPARATOR}){}({SEPARATOR}|$)", words.join(&format!("{SEPARATOR}+")))),
185        None,
186    );
187    let expression = format!("MATCH({attribute}) AGAINST(? IN BOOLEAN MODE) AND {attribute} REGEXP ?");
188    if not { format!("NOT ({expression})") } else { format!("({expression})") }
189}
190
191/// The words of a search term: runs of letters, numbers, `_` and `'`, with
192/// the quotes trimmed off their ends.
193///
194/// PHP: `MySQL::splitSearchWords()` (private).
195fn split_search_words(term: &str) -> Vec<String> {
196    use php_std::pcre::{PREG_SPLIT_NO_EMPTY, Value as PcreValue, preg_split};
197    let PcreValue::Array(pieces) = preg_split(br"/[^\p{L}\p{N}_']+/u", term.as_bytes(), -1, PREG_SPLIT_NO_EMPTY).value
198    else {
199        return Vec::new();
200    };
201    pieces
202        .entries()
203        .iter()
204        .filter_map(|(_, piece)| match piece {
205            PcreValue::Str(piece) => Some(String::from_utf8_lossy(piece).trim_matches('\'').to_owned()),
206            _ => None,
207        })
208        .filter(|word| !word.is_empty())
209        .collect()
210}
211
212/// Whether InnoDB indexes `word`: long enough and not a stopword.
213///
214/// PHP: `MySQL::isIndexedSearchWord()` (private).
215fn is_indexed_search_word(word: &str) -> bool {
216    php_std::mb::mb_strlen(word.as_bytes()) >= FULL_TEXT_MINIMUM_WORD_LENGTH
217        && !FULL_TEXT_STOPWORDS
218            .contains(&String::from_utf8_lossy(&php_std::mb::mb_strtolower(word.as_bytes())).as_ref())
219}
220
221/// MySQL's `build()`: the group-by modifier and the hints.
222pub(crate) fn build<D: Dialect>(b: &mut Builder<D>) -> Result<Statement> {
223    let result = b.base_build()?;
224    let mut query = result.query.clone();
225    if let Some(modifier) = b.core.group_by_modifier.clone()
226        && let Some(group_by) = query.find("GROUP BY ")
227    {
228        let after = group_by + 9;
229        let end = ["HAVING ", "WINDOW ", "ORDER BY ", "LIMIT ", "FOR "]
230            .iter()
231            .filter_map(|keyword| query.get(after..).and_then(|rest| rest.find(keyword)).map(|p| p + after))
232            .min();
233        let insert_at = end.unwrap_or(query.len());
234        let head = query[..insert_at].trim_end_matches([' ', '\t', '\n', '\r', '\0', '\x0B']);
235        let mut rebuilt = format!("{head} {modifier}");
236        if let Some(end) = end {
237            rebuilt.push(' ');
238            rebuilt.push_str(&query[end..]);
239        }
240        query = rebuilt;
241    }
242    if !b.core.hints.is_empty() {
243        let hint = format!("/*+ {} */", b.core.hints.join(" "));
244        if let Some(rest) = query.strip_prefix("SELECT") {
245            let space = rest.len() - rest.trim_start_matches([' ', '\t', '\n', '\r', '\x0B', '\x0C']).len();
246            let distinct = space > 0 && rest[space..].starts_with("DISTINCT");
247            let keep = if distinct { space + 8 } else { 0 };
248            query = format!("SELECT{} {hint}{}", &rest[..keep], &rest[keep..]);
249        }
250    }
251    if query != result.query {
252        return Ok(Statement::with_parts(query, result.bindings, result.read_only, b.core.executor.clone(), None));
253    }
254    Ok(result)
255}
256
257/// MySQL's `update()`: JSON assignments, then an update join or the base update.
258pub(crate) fn update<D: MySqlFamily>(b: &mut Builder<D>) -> Result<Statement> {
259    for (column, condition) in b.core.json_sets.0.clone() {
260        b.core.raw_sets.set(column.clone(), condition.expression);
261        b.core.raw_set_bindings.set(column, condition.bindings);
262    }
263    let result = if D::mysql(b).update_join.is_some() { update_join(b) } else { b.base_update() };
264    b.core.json_sets.clear();
265    result
266}
267
268fn update_join<D: MySqlFamily>(b: &mut Builder<D>) -> Result<Statement> {
269    b.core.bindings.clear();
270    b.validate_table()?;
271    let (table, left, right, alias) = D::mysql(b).update_join.clone().unwrap_or_default();
272    let mut join = b.quote(&table)?;
273    if !alias.is_empty() {
274        join.push_str(" AS ");
275        join.push_str(&b.quote(&alias)?);
276    }
277    let mut sql = format!(
278        "UPDATE {} JOIN {join} ON {} = {}",
279        b.quote(&b.core.table.clone())?,
280        b.resolve_and_wrap(&left)?,
281        b.resolve_and_wrap(&right)?
282    );
283    let assignments = b.compile_assignments()?;
284    if assignments.is_empty() {
285        return Err(Error::Validation("No assignments for UPDATE. Call set() or setRaw() before update().".into()));
286    }
287    sql.push_str(" SET ");
288    sql.push_str(&assignments.join(", "));
289    let mut parts = vec![sql];
290    b.compile_where_clauses(&mut parts, None)?;
291    Ok(b.statement(parts.join(" ")))
292}
293
294/// MySQL's `delete()`: a delete join, or the base delete.
295pub(crate) fn delete<D: MySqlFamily>(b: &mut Builder<D>) -> Result<Statement> {
296    let Some((alias, table, left, right)) = D::mysql(b).delete_join.clone() else {
297        return b.base_delete();
298    };
299    b.core.bindings.clear();
300    b.validate_table()?;
301    let sql = format!(
302        "DELETE {} FROM {} AS {} JOIN {} ON {} = {}",
303        b.quote(&alias)?,
304        b.quote(&b.core.table.clone())?,
305        b.quote(&alias)?,
306        b.quote(&table)?,
307        b.resolve_and_wrap(&left)?,
308        b.resolve_and_wrap(&right)?
309    );
310    let mut parts = vec![sql];
311    b.compile_where_clauses(&mut parts, None)?;
312    Ok(b.statement(parts.join(" ")))
313}
314
315/// `INSERT IGNORE INTO ...`.
316pub(crate) fn insert_or_ignore<D: Dialect>(b: &mut Builder<D>) -> Result<Statement> {
317    b.core.bindings.clear();
318    let (sql, bindings) = b.compile_insert_body()?;
319    b.add_bindings(bindings);
320    let sql = match sql.strip_prefix("INSERT INTO") {
321        Some(rest) => format!("INSERT IGNORE INTO{rest}"),
322        None => sql,
323    };
324    Ok(b.statement(sql))
325}
326
327/// `INSERT INTO table () VALUES ()`.
328pub(crate) fn insert_default_values<D: Dialect>(b: &mut Builder<D>) -> Result<Statement> {
329    b.core.bindings.clear();
330    b.validate_table()?;
331    let sql = format!("INSERT INTO {} () VALUES ()", b.quote(&b.core.table.clone())?);
332    Ok(b.statement(sql))
333}
334
335/// `EXPLAIN [ANALYZE] [FORMAT=...]`.
336pub(crate) fn explain<D: Dialect>(b: &mut Builder<D>, analyze: bool, options: &ExplainOptions) -> Result<Statement> {
337    let result = b.built()?;
338    let mut prefix = "EXPLAIN".to_owned();
339    if analyze {
340        prefix.push_str(" ANALYZE");
341    }
342    if !options.format.is_empty() {
343        prefix.push_str(" FORMAT=");
344        prefix.push_str(&options.format.to_ascii_uppercase());
345    }
346    Ok(Statement::with_parts(
347        format!("{prefix} {}", result.query),
348        result.bindings,
349        true,
350        b.core.executor.clone(),
351        None,
352    ))
353}
354
355/// MySQL's `reset()` of its own state (hints, JSON sets, the modifier, joins).
356pub(crate) fn reset<D: MySqlFamily>(b: &mut Builder<D>) {
357    b.core.hints.clear();
358    b.core.json_sets.clear();
359    b.reset_group_by_modifier();
360    *D::mysql_mut(b) = MySqlState::default();
361}
362
363/// `ST_Distance(...) operator ?`.
364pub(crate) fn spatial_distance<D: MySqlFamily>(
365    b: &mut Builder<D>,
366    method: Method,
367    attribute: &str,
368    values: &Array,
369) -> Result<String> {
370    let filter = sql::distance_filter(values, "Builder/MySQL.php", 484)?;
371    let wkt = wkt_of(b, &filter.geometry)?;
372    let operator = distance_operator(method);
373    b.add_binding(wkt, None);
374    b.add_binding(Value::Float(filter.distance), None);
375    if filter.meters {
376        return Ok(format!(
377            "ST_Distance(ST_SRID({attribute}, 4326), {}, 'metre') {operator} ?",
378            b.step_string(Step::GeomFromText, &[Arg::Int(Some(4326))])?
379        ));
380    }
381    let geometry = b.step_string(Step::GeomFromText, &[Arg::Int(Some(0))])?;
382    Ok(format!("ST_Distance(ST_SRID({attribute}, 0), {geometry}) {operator} ?"))
383}
384
385/// `function(attribute, ST_GeomFromText(?, 4326, ...))`, negated with `NOT`.
386pub(crate) fn spatial_predicate<D: MySqlFamily>(
387    b: &mut Builder<D>,
388    function: &str,
389    attribute: &str,
390    values: &Array,
391    not: bool,
392) -> Result<String> {
393    let wkt = sql::predicate_wkt(b, values, MYSQL_CLASS, "Builder/MySQL.php", 513)?;
394    b.add_binding(value::string(wkt), None);
395    let geometry = b.step_string(Step::GeomFromText, &[Arg::Int(Some(4326))])?;
396    let expression = format!("{function}({attribute}, {geometry})");
397    Ok(if not { format!("NOT {expression}") } else { expression })
398}
399
400/// `JSON_CONTAINS(attribute, ?)`.
401pub(crate) fn json_contains<D: Dialect>(
402    b: &mut Builder<D>,
403    attribute: &str,
404    values: &Array,
405    not: bool,
406) -> Result<String> {
407    let payload = values.get(&php_std::ArrayKey::Int(0)).cloned().unwrap_or(Value::Null);
408    b.add_binding(value::string(encode_json_payload(&payload)?), None);
409    let expression = format!("JSON_CONTAINS({attribute}, ?)");
410    Ok(if not { format!("NOT {expression}") } else { expression })
411}
412
413/// `JSON_OVERLAPS(attribute, ?)`.
414pub(crate) fn json_overlaps<D: Dialect>(b: &mut Builder<D>, attribute: &str, values: &Array) -> Result<String> {
415    let payload = values.get(&php_std::ArrayKey::Int(0)).cloned().unwrap_or(Value::Null);
416    b.add_binding(value::string(encode_json_payload(&payload)?), None);
417    Ok(format!("JSON_OVERLAPS({attribute}, ?)"))
418}
419
420/// `JSON_EXTRACT(attribute, '$.path') operator ?`.
421pub(crate) fn json_path<D: Dialect>(b: &mut Builder<D>, attribute: &str, values: &Array) -> Result<String> {
422    let (path, operator) = crate::builder::postgresql::json_path_parts(b, values)?;
423    Ok(format!("JSON_EXTRACT({attribute}, '$.{path}') {operator} ?"))
424}
425
426impl Dialect for MySqlDialect {
427    const CLASS: &'static str = "Utopia\\Query\\Builder\\MySQL";
428    const LIKE_ESCAPE: u8 = b'!';
429    const DECLARES_LIKE_ESCAPE: bool = true;
430
431    fn base_step(
432        b: &mut Builder<Self>,
433        step: crate::builder::Step,
434        arguments: &[crate::builder::Arg<'_>],
435    ) -> Option<Result<crate::builder::Ret>> {
436        sql::sql_base_step(b, step, arguments)
437            .or_else(|| crate::builder::feature::aggregates_base_step::<Self>(step, arguments))
438            .or_else(|| match (step, arguments) {
439                (crate::builder::Step::GeomFromText, [crate::builder::Arg::Int(Some(srid))]) => {
440                    Some(Ok(crate::builder::Ret::Str(Self::geom_from_text(*srid))))
441                }
442                _ => None,
443            })
444    }
445
446    fn compile_random(_b: &Builder<Self>) -> String {
447        "RAND()".into()
448    }
449
450    fn compile_regex(b: &mut Builder<Self>, attribute: &str, values: &Array, column: Option<&str>) -> Result<String> {
451        b.add_binding(crate::builder::core::first(values), column);
452        Ok(format!("{attribute} REGEXP ?"))
453    }
454
455    fn compile_contains_all(
456        b: &mut Builder<Self>,
457        attribute: &str,
458        values: &Array,
459        column: Option<&str>,
460    ) -> Result<String> {
461        if let Some(sql) = b.flavored_contains_all(attribute, values, column) {
462            return Ok(sql);
463        }
464        b.base_compile_contains_all(attribute, values, column)
465    }
466
467    fn compile_filter(b: &mut Builder<Self>, query: &Query) -> Result<String> {
468        sql::sql_compile_filter(b, query)
469    }
470
471    fn build(b: &mut Builder<Self>) -> Result<Statement> {
472        build(b)
473    }
474
475    fn update(b: &mut Builder<Self>) -> Result<Statement> {
476        update(b)
477    }
478
479    fn delete(b: &mut Builder<Self>) -> Result<Statement> {
480        delete(b)
481    }
482
483    fn insert_default_values(b: &mut Builder<Self>) -> Result<Statement> {
484        insert_default_values(b)
485    }
486
487    fn explain(b: &mut Builder<Self>, analyze: bool, options: &ExplainOptions) -> Result<Statement> {
488        explain(b, analyze, options)
489    }
490
491    fn reset(b: &mut Builder<Self>) {
492        reset(b)
493    }
494
495    fn ast_dialect() -> crate::builder::AstDialect {
496        crate::builder::AstDialect::MySql
497    }
498}
499
500impl SqlDialect for MySqlDialect {
501    fn compile_search_expression(b: &mut Builder<Self>, attribute: &str, values: &Array, not: bool) -> Result<String> {
502        match b.flavored_search_values(values) {
503            Some(values) => search_expression(b, attribute, &values, not),
504            None => search_expression(b, attribute, values, not),
505        }
506    }
507
508    fn compile_spatial_distance(
509        b: &mut Builder<Self>,
510        method: Method,
511        attribute: &str,
512        values: &Array,
513    ) -> Result<String> {
514        spatial_distance(b, method, attribute, values)
515    }
516
517    fn compile_spatial_predicate(
518        b: &mut Builder<Self>,
519        function: &str,
520        attribute: &str,
521        values: &Array,
522        not: bool,
523    ) -> Result<String> {
524        spatial_predicate(b, function, attribute, values, not)
525    }
526
527    fn compile_spatial_covers_predicate(
528        b: &mut Builder<Self>,
529        attribute: &str,
530        values: &Array,
531        not: bool,
532    ) -> Result<String> {
533        // Through the step, so a subclass's compileSpatialPredicate() writes this one too.
534        b.step_string(
535            crate::builder::Step::CompileSpatialPredicate,
536            &[
537                crate::builder::Arg::Str("ST_Contains"),
538                crate::builder::Arg::Str(attribute),
539                crate::builder::Arg::Values(values),
540                crate::builder::Arg::Bool(not),
541            ],
542        )
543    }
544
545    fn compile_json_contains_expression(
546        b: &mut Builder<Self>,
547        attribute: &str,
548        values: &Array,
549        not: bool,
550    ) -> Result<String> {
551        json_contains(b, attribute, values, not)
552    }
553
554    fn compile_json_overlaps_expression(b: &mut Builder<Self>, attribute: &str, values: &Array) -> Result<String> {
555        json_overlaps(b, attribute, values)
556    }
557
558    fn compile_json_path_expression(b: &mut Builder<Self>, attribute: &str, values: &Array) -> Result<String> {
559        json_path(b, attribute, values)
560    }
561
562    fn compile_conflict_header(_b: &mut Builder<Self>) -> Result<String> {
563        Ok("ON DUPLICATE KEY UPDATE".into())
564    }
565
566    fn compile_conflict_assignment(wrapped: &str) -> String {
567        format!("VALUES({wrapped})")
568    }
569}
570
571/// The SQL of a conflict clause for a SQL dialect.
572pub(crate) fn conflict_clause<D: SqlDialect>(b: &mut Builder<D>) -> Result<String> {
573    b.step_string(Step::CompileConflictClause, &[])
574}
575
576/// The builder's own `compileConflictClause()`.
577pub(crate) fn base_conflict_clause<D: SqlDialect>(b: &mut Builder<D>) -> Result<String> {
578    b.compile_conflict_clause(
579        |b| b.step_string(Step::CompileConflictHeader, &[]),
580        |b, wrapped| b.step_string(Step::CompileConflictAssignment, &[Arg::Str(wrapped)]),
581    )
582}
583
584/// MySQL's JSON column updates, shared with MariaDB.
585pub(crate) mod json_sets {
586    use super::*;
587
588    pub(crate) fn append<D: Dialect>(b: &mut Builder<D>, column: &str, values: &Array) -> Result<()> {
589        let wrapped = b.resolve_and_wrap(column)?;
590        b.core.json_sets.set(
591            column,
592            Condition::new(
593                format!("JSON_MERGE_PRESERVE(IFNULL({wrapped}, JSON_ARRAY()), ?)"),
594                vec![json_or_empty(values)],
595            ),
596        );
597        Ok(())
598    }
599
600    pub(crate) fn prepend<D: Dialect>(b: &mut Builder<D>, column: &str, values: &Array) -> Result<()> {
601        let wrapped = b.resolve_and_wrap(column)?;
602        b.core.json_sets.set(
603            column,
604            Condition::new(
605                format!("JSON_MERGE_PRESERVE(?, IFNULL({wrapped}, JSON_ARRAY()))"),
606                vec![json_or_empty(values)],
607            ),
608        );
609        Ok(())
610    }
611
612    pub(crate) fn insert<D: Dialect>(b: &mut Builder<D>, column: &str, index: i64, value: Value) -> Result<()> {
613        let wrapped = b.resolve_and_wrap(column)?;
614        b.core.json_sets.set(
615            column,
616            Condition::new(
617                format!("JSON_ARRAY_INSERT({wrapped}, ?, ?)"),
618                vec![value::string(format!("$[{index}]")), value],
619            ),
620        );
621        Ok(())
622    }
623
624    pub(crate) fn remove<D: Dialect>(b: &mut Builder<D>, column: &str, value: Value) -> Result<()> {
625        let wrapped = b.resolve_and_wrap(column)?;
626        b.core.json_sets.set(
627            column,
628            Condition::new(
629                // The value is a LIKE pattern to JSON_SEARCH, and a value that is not there removes nothing.
630                format!(
631                    "COALESCE(JSON_REMOVE({wrapped}, JSON_UNQUOTE(JSON_SEARCH({wrapped}, 'one', ?, {}))), {wrapped})",
632                    D::LITERAL.quote(&char::from(D::LIKE_ESCAPE).to_string())?
633                ),
634                vec![crate::value::string(crate::builder::core::escape_like_value(&value, D::LIKE_ESCAPE))],
635            ),
636        );
637        Ok(())
638    }
639
640    pub(crate) fn intersect<D: Dialect>(b: &mut Builder<D>, column: &str, values: &Array) -> Result<()> {
641        let wrapped = b.resolve_and_wrap(column)?;
642        let expression = format!(
643            "(SELECT JSON_ARRAYAGG(val) FROM JSON_TABLE({wrapped}, '$[*]' COLUMNS(val JSON PATH '$')) AS jt WHERE JSON_CONTAINS(?, val))"
644        );
645        b.core.raw_sets.set(column, expression);
646        b.core.raw_set_bindings.set(column, vec![json_or_empty(values)]);
647        Ok(())
648    }
649
650    pub(crate) fn diff<D: Dialect>(b: &mut Builder<D>, column: &str, values: &Array) -> Result<()> {
651        let wrapped = b.resolve_and_wrap(column)?;
652        let expression = format!(
653            "(SELECT JSON_ARRAYAGG(val) FROM JSON_TABLE({wrapped}, '$[*]' COLUMNS(val JSON PATH '$')) AS jt WHERE NOT JSON_CONTAINS(?, val))"
654        );
655        b.core.raw_sets.set(column, expression);
656        b.core.raw_set_bindings.set(column, vec![json_or_empty(values)]);
657        Ok(())
658    }
659
660    pub(crate) fn unique<D: Dialect>(b: &mut Builder<D>, column: &str) -> Result<()> {
661        let wrapped = b.resolve_and_wrap(column)?;
662        let expression = format!(
663            "(SELECT JSON_ARRAYAGG(val) FROM (SELECT DISTINCT val FROM JSON_TABLE({wrapped}, '$[*]' COLUMNS(val JSON PATH '$')) AS jt) AS dt)"
664        );
665        b.core.raw_sets.set(column, expression);
666        b.core.raw_set_bindings.set(column, Vec::new());
667        Ok(())
668    }
669
670    pub(crate) fn path<D: Dialect>(b: &mut Builder<D>, column: &str, path: &str, value: Value) -> Result<()> {
671        if !path.starts_with('$') {
672            return Err(Error::Validation(format!("JSON path must start with '$': {path}")));
673        }
674        let wrapped = b.resolve_and_wrap(column)?;
675        b.core
676            .json_sets
677            .set(column, Condition::new(format!("JSON_SET({wrapped}, ?, ?)"), vec![value::string(path), value]));
678        Ok(())
679    }
680}
681
682impl Locking for MySqlDialect {}
683impl Transactions for MySqlDialect {}
684impl StatisticalAggregates for MySqlDialect {}
685impl BitwiseAggregates for MySqlDialect {}
686impl RawSql for MySqlDialect {}
687impl CrossJoins for MySqlDialect {}
688impl LateralJoins for MySqlDialect {}
689impl Spatial for MySqlDialect {}
690impl FullTextSearch for MySqlDialect {}
691impl NegatedFullTextSearch for MySqlDialect {}
692impl ConditionalAggregates for MySqlDialect {}
693
694impl Json for MySqlDialect {
695    fn set_json_append(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
696        json_sets::append(b, column, values)
697    }
698    fn set_json_prepend(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
699        json_sets::prepend(b, column, values)
700    }
701    fn set_json_insert(b: &mut Builder<Self>, column: &str, index: i64, value: Value) -> Result<()> {
702        json_sets::insert(b, column, index, value)
703    }
704    fn set_json_remove(b: &mut Builder<Self>, column: &str, value: Value) -> Result<()> {
705        json_sets::remove(b, column, value)
706    }
707    fn set_json_intersect(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
708        json_sets::intersect(b, column, values)
709    }
710    fn set_json_diff(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
711        json_sets::diff(b, column, values)
712    }
713    fn set_json_unique(b: &mut Builder<Self>, column: &str) -> Result<()> {
714        json_sets::unique(b, column)
715    }
716    fn set_json_path(b: &mut Builder<Self>, column: &str, path: &str, value: Value) -> Result<()> {
717        json_sets::path(b, column, path, value)
718    }
719}
720
721impl Hints for MySqlDialect {
722    fn hint(b: &mut Builder<Self>, hint: &str) -> Result<()> {
723        add_hint(b, hint)
724    }
725}
726
727/// Adds a validated optimizer hint.
728pub(crate) fn add_hint<D: Dialect>(b: &mut Builder<D>, hint: &str) -> Result<()> {
729    if !is_hint(hint) {
730        return Err(Error::Validation(format!("Invalid hint: {hint}")));
731    }
732    b.core.hints.push(hint.to_owned());
733    Ok(())
734}
735
736impl StringAggregates for MySqlDialect {
737    fn group_concat_expr(column: &str, order_by: &str) -> String {
738        if order_by.is_empty() {
739            format!("GROUP_CONCAT({column} SEPARATOR ?)")
740        } else {
741            format!("GROUP_CONCAT({column} {order_by} SEPARATOR ?)")
742        }
743    }
744    fn json_array_agg_expr(column: &str) -> String {
745        format!("JSON_ARRAYAGG({column})")
746    }
747    fn json_object_agg_expr(key: &str, value: &str) -> String {
748        format!("JSON_OBJECTAGG({key}, {value})")
749    }
750}
751
752impl Rollup for MySqlDialect {
753    fn with_rollup(b: &mut Builder<Self>) {
754        b.core.group_by_modifier = Some("WITH ROLLUP".into());
755    }
756}
757
758impl Upsert for MySqlDialect {
759    fn upsert(b: &mut Builder<Self>) -> Result<Statement> {
760        b.compile_upsert(conflict_clause)
761    }
762}
763
764impl UpsertSelect for MySqlDialect {
765    fn upsert_select(b: &mut Builder<Self>) -> Result<Statement> {
766        b.compile_upsert_select(conflict_clause)
767    }
768}
769
770impl InsertOrIgnore for MySqlDialect {
771    fn insert_or_ignore(b: &mut Builder<Self>) -> Result<Statement> {
772        insert_or_ignore(b)
773    }
774}
775
776impl<D: MySqlFamily> Builder<D> {
777    /// `UPDATE table JOIN join [AS alias] ON left = right SET ...`.
778    ///
779    /// PHP: `updateJoin()`.
780    pub fn update_join(
781        &mut self,
782        table: impl Into<String>,
783        left: impl Into<String>,
784        right: impl Into<String>,
785        alias: impl Into<String>,
786    ) -> &mut Self {
787        let table = table.into();
788        self.defer_unbound(&format!("update joining table '{table}'"));
789        D::mysql_mut(self).update_join = Some((table, left.into(), right.into(), alias.into()));
790        self
791    }
792
793    /// `DELETE alias FROM table AS alias JOIN join ON left = right`.
794    ///
795    /// PHP: `deleteJoin()`.
796    pub fn delete_join(
797        &mut self,
798        alias: impl Into<String>,
799        table: impl Into<String>,
800        left: impl Into<String>,
801        right: impl Into<String>,
802    ) -> &mut Self {
803        let table = table.into();
804        self.defer_unbound(&format!("delete joining table '{table}'"));
805        D::mysql_mut(self).delete_join = Some((alias.into(), table, left.into(), right.into()));
806        self
807    }
808
809    /// The `MAX_EXECUTION_TIME(ms)` hint.
810    ///
811    /// PHP: `maxExecutionTime()`.
812    pub fn max_execution_time(&mut self, ms: i64) -> Result<&mut Self> {
813        add_hint(self, &format!("MAX_EXECUTION_TIME({ms})"))?;
814        Ok(self)
815    }
816}