1use 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#[derive(Default, Debug, Clone, Copy)]
27pub struct MariaDbDialect;
28
29const OPEN_LIMIT: &str = "18446744073709551615";
31
32macro_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 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
133fn 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
161fn 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
188fn 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
215fn 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
225fn 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
272fn 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
297fn 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;