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)]
22pub struct MariaDbDialect;
23
24const OPEN_LIMIT: &str = "18446744073709551615";
26
27macro_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 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
128fn 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
156fn 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
183fn 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
210fn 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
220fn 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
245fn 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
270fn 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;