Skip to main content

sql_builder/backend/mysql/
dialect.rs

1//! The dialect of MySQL and MariaDB.
2//!
3//! The two differ in JSON equality: MariaDB has `JSON_EQUALS` and no
4//! `CAST(.. AS JSON)`, MySQL compares its JSON type with `=`. JSON values are
5//! bound as JSON text and read back with `JSON_EXTRACT(?, '$')` where a
6//! document is needed, which both servers parse.
7
8use super::{
9    MysqlQueryBuilder,
10    json::{self, Kind},
11};
12use crate::backend::bound_sql::bound;
13use crate::backend::dialect::{
14    ArrayOperator, BoundSql, JsonContainment, JsonExistence, JsonPathStep, SqlDialect, any_element,
15    builder_dialect, document, existence_steps, json_path_text, json_text, negated,
16    unknown_when_null,
17};
18use crate::{Value, error::RenderError};
19
20/// MariaDB's query builder and dialect.
21///
22/// They are MySQL's, but for JSON equality, `RETURNING`, an `ORDER BY`/`LIMIT`
23/// on an `UPDATE` that joins other tables, the rows of a `VALUES` list,
24/// written without `ROW`, and the shared row lock, `LOCK IN SHARE MODE` with
25/// no `OF`.
26#[derive(Default, Debug, Clone, Copy)]
27pub struct MariaDbDialect;
28
29/// The limit an offset alone takes: the largest MySQL accepts.
30const OPEN_LIMIT: &str = "18446744073709551615";
31
32/// One [`SqlDialect`] impl for MySQL and for MariaDB, `$mariadb` telling them apart.
33macro_rules! mysql_family_dialect {
34    ($dialect:ident, $mariadb:expr) => {
35        impl SqlDialect for $dialect {
36            builder_dialect!($dialect);
37
38            fn json_equals(
39                &self,
40                column: &str,
41                value: &serde_json::Value,
42                negated: bool,
43            ) -> BoundSql {
44                json_equals(column, value, negated, $mariadb)
45            }
46
47            fn json_containment(
48                &self,
49                column: &str,
50                value: &serde_json::Value,
51                containment: JsonContainment,
52            ) -> BoundSql {
53                json_containment(column, value, containment)
54            }
55
56            fn json_exists(
57                &self,
58                column: &str,
59                existence: JsonExistence,
60                target: &str,
61                negated: bool,
62            ) -> Result<BoundSql, RenderError> {
63                let backend = if $mariadb { "MariaDB" } else { "MySQL" };
64                json_exists(column, existence, target, negated, backend)
65            }
66
67            fn array_predicate(
68                &self,
69                column: &str,
70                operator: ArrayOperator,
71                elements: Vec<Value>,
72                _null_allowed: bool,
73            ) -> BoundSql {
74                array_predicate(column, operator, &elements)
75            }
76
77            fn array_append(&self, column: &str, element: Value) -> BoundSql {
78                array_append(column, &element)
79            }
80
81            fn array_remove(&self, column: &str, _source: &str, element: Value) -> BoundSql {
82                array_remove(column, &element, $mariadb)
83            }
84
85            fn json_set(
86                &self,
87                column: &str,
88                path: &[JsonPathStep],
89                value: &serde_json::Value,
90            ) -> BoundSql {
91                json_set(column, path, value)
92            }
93
94            fn window_default(
95                &self,
96                function: &str,
97                column: &str,
98                offset: &str,
99                default: &str,
100                over: &str,
101            ) -> String {
102                window_default(function, column, offset, default, over)
103            }
104
105            fn open_limit(&self) -> Option<&'static str> {
106                Some(OPEN_LIMIT)
107            }
108
109            /// MySQL and MariaDB take a `LIMIT` in an `IN` subquery only a
110            /// derived table further down.
111            fn limit_in_subquery(&self) -> bool {
112                false
113            }
114
115            fn groups_frames(&self) -> bool {
116                false
117            }
118
119            fn update_limit(&self) -> bool {
120                true
121            }
122
123            fn exact_key(&self, column: &str) -> String {
124                format!("CAST({column} AS BINARY)")
125            }
126        }
127    };
128}
129
130mysql_family_dialect!(MysqlQueryBuilder, false);
131mysql_family_dialect!(MariaDbDialect, true);
132
133/// MySQL compares its JSON type with `=`; a text parameter is cast to it.
134/// MariaDB's `JSON_EQUALS` reads a NULL column as the `null` document, so it
135/// is made unknown there, matching neither the test nor its negation.
136fn json_equals(column: &str, value: &serde_json::Value, negate: bool, mariadb: bool) -> BoundSql {
137    let document = json_text(value);
138    if mariadb {
139        let test = unknown_when_null(
140            column,
141            bound!(format!("JSON_EQUALS({column}, "), document, ")"),
142        );
143        let not = if negate { "NOT " } else { "" };
144        return bound!(not, "(", test, ")");
145    }
146    let operator = if negate { "<>" } else { "=" };
147    bound!(format!("{column} {operator} CAST("), document, " AS JSON)")
148}
149
150fn json_containment(
151    column: &str,
152    value: &serde_json::Value,
153    containment: JsonContainment,
154) -> BoundSql {
155    match containment {
156        JsonContainment::Contains => json::contains(column, value),
157        JsonContainment::ContainedBy => json::contained_by(column, value),
158    }
159}
160
161/// An index of a non-array reads as the value itself here, so each indexed
162/// step also checks its parent is an array.
163fn json_exists(
164    column: &str,
165    existence: JsonExistence,
166    target: &str,
167    negate: bool,
168    backend: &str,
169) -> Result<BoundSql, RenderError> {
170    let steps = existence_steps(existence, target, backend)?;
171    let mut sql = bound!(
172        format!("JSON_CONTAINS_PATH({column}, 'one', "),
173        Value::String(Some(json_path_text(&steps))),
174        ")"
175    );
176    for (index, step) in steps.iter().enumerate() {
177        if matches!(step, JsonPathStep::Element(_)) {
178            sql.push(" AND ").push(json::guard_sql(
179                column,
180                Kind::Array,
181                json_path_text(&steps[..index]),
182            ));
183        }
184    }
185    Ok(negated(sql, negate))
186}
187
188/// A JSON array column is contained in or contains the list as a JSON
189/// document, with the guards that make `JSON_CONTAINS` read as PostgreSQL
190/// does: a column holding an object is contained by no list. An overlap is a
191/// containment of any one value.
192fn array_predicate(column: &str, operator: ArrayOperator, elements: &[Value]) -> BoundSql {
193    let documents: Vec<serde_json::Value> = elements.iter().map(document).collect();
194    let bound = match operator {
195        ArrayOperator::Contains => json::contains(column, &serde_json::Value::Array(documents)),
196        ArrayOperator::ContainedBy => {
197            json::contained_by(column, &serde_json::Value::Array(documents))
198        }
199        ArrayOperator::Overlaps => any_element(
200            documents
201                .iter()
202                .map(|document| {
203                    bound!(
204                        format!("JSON_CONTAINS({column}, "),
205                        json_text(document),
206                        ")"
207                    )
208                })
209                .collect(),
210        ),
211    };
212    bound!(format!("(JSON_TYPE({column}) = 'ARRAY' AND ("), bound, "))")
213}
214
215/// The element is bound as its JSON text and read back as JSON, so an object
216/// stays an object rather than becoming a string.
217fn array_append(column: &str, element: &Value) -> BoundSql {
218    bound!(
219        format!("JSON_ARRAY_APPEND(COALESCE({column}, JSON_ARRAY()), '$', JSON_EXTRACT("),
220        json_text(&document(element)),
221        ", '$'))"
222    )
223}
224
225/// Every element equal to the value goes, compared as JSON as `json_equals`
226/// compares a document (`1`, `"1"` and `true` differ, an object's key order
227/// does not, an array's order does), and the rest keep their order and types;
228/// a NULL column stays NULL. `JSON_TABLE` reads a JSON null as SQL NULL on
229/// MySQL, hence the extra test when null is what is removed.
230///
231/// `JSON_ARRAYAGG` leaves its order undefined, so the kept elements are put
232/// in their original order explicitly: MariaDB's takes an `ORDER BY`, MySQL's
233/// runs as a window over them in that order. MariaDB's also stops at
234/// `group_concat_max_len`, which the TideORM MySQL driver raises.
235fn array_remove(column: &str, element: &Value, mariadb: bool) -> BoundSql {
236    let value = document(element);
237    let equal = json_equals("tideorm_element.v", &value, false, mariadb);
238    let null_guard = if value.is_null() {
239        "tideorm_element.v IS NOT NULL AND "
240    } else {
241        ""
242    };
243    let kept = "JSON_ARRAYAGG(JSON_EXTRACT(tideorm_element.v, '$')";
244    let (open, aggregate, close) = if mariadb {
245        (
246            "(SELECT COALESCE(",
247            format!("{kept} ORDER BY tideorm_element.i), JSON_ARRAY())"),
248            ")",
249        )
250    } else {
251        (
252            "COALESCE((SELECT ",
253            format!(
254                "{kept}) OVER (ORDER BY tideorm_element.i \
255                 ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)"
256            ),
257            " LIMIT 1), JSON_ARRAY())",
258        )
259    };
260    bound!(
261        format!(
262            "CASE WHEN {column} IS NULL THEN NULL WHEN JSON_TYPE({column}) <> 'ARRAY' THEN {column} \
263             ELSE {open}{aggregate} \
264             FROM JSON_TABLE({column}, '$[*]' COLUMNS (i FOR ORDINALITY, v JSON PATH '$')) AS tideorm_element \
265             WHERE {null_guard}NOT COALESCE("
266        ),
267        equal,
268        format!(", FALSE){close} END")
269    )
270}
271
272/// `JSON_SET` reads an index step of a non-array as the value itself, so
273/// `$.k[1]` on a scalar wraps it in an array and `$.k[0]` replaces it; each
274/// step's parent is checked to be the object or array the step needs first.
275fn json_set(column: &str, path: &[JsonPathStep], value: &serde_json::Value) -> BoundSql {
276    if path.is_empty() {
277        return BoundSql::sql(column);
278    }
279    let guards = path.iter().enumerate().map(|(index, step)| {
280        let kind = match step {
281            JsonPathStep::Member(_) => Kind::Object,
282            JsonPathStep::Element(_) => Kind::Array,
283        };
284        json::guard_sql(column, kind, json_path_text(&path[..index]))
285    });
286    bound!(
287        "CASE WHEN ",
288        BoundSql::join(guards, " AND "),
289        format!(" THEN JSON_SET({column}, "),
290        Value::String(Some(json_path_text(path))),
291        ", JSON_EXTRACT(",
292        json_text(value),
293        format!(", '$')) ELSE {column} END")
294    )
295}
296
297/// MariaDB's `LAG` and `LEAD` take no default. The same window finds no row
298/// for a constant exactly where the default applies, where a `COALESCE` would
299/// also replace a NULL value.
300fn window_default(function: &str, column: &str, offset: &str, default: &str, over: &str) -> String {
301    format!(
302        "CASE WHEN {function}(1, {offset}) OVER ({over}) IS NULL THEN {default} \
303         ELSE {function}({column}, {offset}) OVER ({over}) END"
304    )
305}
306
307#[cfg(test)]
308#[path = "../../../tests/unit/mysql_dialect_tests.rs"]
309mod tests;