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