Skip to main content

utopia_query/builder/
mariadb.rs

1//! MariaDB: [`MariaDb`], MySQL with `RETURNING`, sequences, its own geometry
2//! constructor and `ST_DISTANCE_SPHERE` for distances in meters.
3//!
4//! PHP: `Utopia\Query\Builder\MariaDB`.
5
6use crate::builder::core::{Builder, Dialect, ExplainOptions, first};
7use crate::builder::feature::{
8    BitwiseAggregates, ConditionalAggregates, CrossJoins, FullTextSearch, Hints, InsertOrIgnore, Json, LateralJoins,
9    Locking, NegatedFullTextSearch, RawSql, Returning, Rollup, Sequences, Spatial, StatisticalAggregates,
10    StringAggregates, Transactions, Upsert, UpsertSelect,
11};
12use crate::builder::mysql::{self, MySqlFamily, MySqlState, conflict_clause, json_sets};
13use crate::builder::sql::{self, SqlDialect, distance_operator, wkt_of};
14use crate::builder::types::Statement;
15use crate::error::{Error, Result};
16use crate::method::Method;
17use crate::query::Query;
18use crate::value::{Array, Value};
19
20/// A MariaDB builder.
21///
22/// PHP: `Utopia\Query\Builder\MariaDB`.
23///
24/// ```
25/// use utopia_query::Query;
26/// use utopia_query::builder::MariaDb;
27///
28/// let statement = MariaDb::new()
29///     .from("users", "")
30///     .filter([Query::equal("id", [1])])
31///     .returning(["id"])
32///     .delete()?;
33/// assert_eq!(statement.query, "DELETE FROM `users` WHERE `id` IN (?) RETURNING `id`");
34/// # Ok::<(), utopia_query::Error>(())
35/// ```
36///
37/// ```php
38/// use Utopia\Query\Builder\MariaDB;
39/// use Utopia\Query\Query;
40///
41/// echo (new MariaDB())->from('users')->filter([Query::equal('id', [1])])->returning(['id'])->delete()->query, "\n";
42/// // DELETE FROM `users` WHERE `id` IN (?) RETURNING `id`
43/// ```
44pub type MariaDb = Builder<MariaDbDialect>;
45
46/// The MariaDB dialect: MySQL's state.
47#[derive(Debug, Clone, Default)]
48pub struct MariaDbDialect {
49    state: MySqlState,
50}
51
52const NO_RETURNING_UPSERT: &str = "MariaDB does not support RETURNING with ON DUPLICATE KEY UPDATE. \
53     Call returning([]) to clear before upsert(), or use a separate update() statement.";
54
55impl MySqlFamily for MariaDbDialect {
56    fn mysql(b: &Builder<Self>) -> &MySqlState {
57        &b.dialect.state
58    }
59
60    fn mysql_mut(b: &mut Builder<Self>) -> &mut MySqlState {
61        &mut b.dialect.state
62    }
63
64    fn geom_from_text(srid: i64) -> String {
65        format!("ST_GeomFromText(?, {srid})")
66    }
67}
68
69impl Dialect for MariaDbDialect {
70    const CLASS: &'static str = "Utopia\\Query\\Builder\\MariaDB";
71    const LIKE_ESCAPE: u8 = b'!';
72    const DECLARES_LIKE_ESCAPE: bool = true;
73
74    fn base_step(
75        b: &mut Builder<Self>,
76        step: crate::builder::Step,
77        arguments: &[crate::builder::Arg<'_>],
78    ) -> Option<Result<crate::builder::Ret>> {
79        sql::sql_base_step(b, step, arguments)
80            .or_else(|| crate::builder::feature::aggregates_base_step::<Self>(step, arguments))
81            .or_else(|| match (step, arguments) {
82                (crate::builder::Step::GeomFromText, [crate::builder::Arg::Int(Some(srid))]) => {
83                    Some(Ok(crate::builder::Ret::Str(Self::geom_from_text(*srid))))
84                }
85                _ => None,
86            })
87    }
88
89    fn compile_random(_b: &Builder<Self>) -> String {
90        "RAND()".into()
91    }
92
93    fn compile_regex(b: &mut Builder<Self>, attribute: &str, values: &Array, column: Option<&str>) -> Result<String> {
94        b.add_binding(first(values), column);
95        Ok(format!("{attribute} REGEXP ?"))
96    }
97
98    fn compile_contains_all(
99        b: &mut Builder<Self>,
100        attribute: &str,
101        values: &Array,
102        column: Option<&str>,
103    ) -> Result<String> {
104        if let Some(sql) = b.flavored_contains_all(attribute, values, column) {
105            return Ok(sql);
106        }
107        b.base_compile_contains_all(attribute, values, column)
108    }
109
110    fn compile_filter(b: &mut Builder<Self>, query: &Query) -> Result<String> {
111        sql::sql_compile_filter(b, query)
112    }
113
114    fn build(b: &mut Builder<Self>) -> Result<Statement> {
115        mysql::build(b)
116    }
117
118    fn insert(b: &mut Builder<Self>) -> Result<Statement> {
119        let result = b.base_insert()?;
120        b.append_returning(result)
121    }
122
123    fn update(b: &mut Builder<Self>) -> Result<Statement> {
124        let result = mysql::update(b)?;
125        b.append_returning(result)
126    }
127
128    fn delete(b: &mut Builder<Self>) -> Result<Statement> {
129        let result = mysql::delete(b)?;
130        b.append_returning(result)
131    }
132
133    fn insert_default_values(b: &mut Builder<Self>) -> Result<Statement> {
134        mysql::insert_default_values(b)
135    }
136
137    fn explain(b: &mut Builder<Self>, analyze: bool, options: &ExplainOptions) -> Result<Statement> {
138        mysql::explain(b, analyze, options)
139    }
140
141    fn reset(b: &mut Builder<Self>) {
142        mysql::reset(b);
143        b.reset_returning();
144    }
145
146    fn ast_dialect() -> crate::builder::AstDialect {
147        crate::builder::AstDialect::MariaDb
148    }
149}
150
151impl SqlDialect for MariaDbDialect {
152    fn compile_search_expression(b: &mut Builder<Self>, attribute: &str, values: &Array, not: bool) -> Result<String> {
153        match b.flavored_search_values(values) {
154            Some(values) => mysql::search_expression(b, attribute, &values, not),
155            None => mysql::search_expression(b, attribute, values, not),
156        }
157    }
158
159    fn compile_spatial_filter(b: &mut Builder<Self>, method: Method, attribute: &str, query: &Query) -> Result<String> {
160        use Method::*;
161        if matches!(method, DistanceLessThan | DistanceGreaterThan | DistanceEqual | DistanceNotEqual) {
162            let filter = sql::distance_filter(query.values(), "Builder/MariaDB.php", 83)?;
163            if filter.meters && !query.attribute_type().is_empty() {
164                let wkt = crate::value::to_php_string(&wkt_of(b, &filter.geometry)?);
165                let wkt_type = match wkt.find('(') {
166                    Some(position) => {
167                        wkt[..position].trim_matches([' ', '\t', '\n', '\r', '\0', '\x0B']).to_ascii_lowercase()
168                    }
169                    None => String::new(),
170                };
171                let attribute_type = query.attribute_type().to_ascii_lowercase();
172                if wkt_type != "point" || attribute_type != "point" {
173                    return Err(Error::Validation(format!(
174                        "Distance in meters is not supported between {attribute_type} and {wkt_type}"
175                    )));
176                }
177            }
178        }
179        sql::sql_compile_spatial_filter(b, method, attribute, query)
180    }
181
182    fn compile_spatial_distance(
183        b: &mut Builder<Self>,
184        method: Method,
185        attribute: &str,
186        values: &Array,
187    ) -> Result<String> {
188        let filter = sql::distance_filter(values, "Builder/MariaDB.php", 111)?;
189        let operator = distance_operator(method);
190        let wkt = wkt_of(b, &filter.geometry)?;
191        b.add_binding(wkt, None);
192        b.add_binding(Value::Float(filter.distance), None);
193        if filter.meters {
194            return Ok(format!("ST_DISTANCE_SPHERE({attribute}, ST_GeomFromText(?, 4326)) {operator} ?"));
195        }
196        Ok(format!("ST_Distance({attribute}, ST_GeomFromText(?, 4326)) {operator} ?"))
197    }
198
199    fn compile_spatial_predicate(
200        b: &mut Builder<Self>,
201        function: &str,
202        attribute: &str,
203        values: &Array,
204        not: bool,
205    ) -> Result<String> {
206        mysql::spatial_predicate(b, function, attribute, values, not)
207    }
208
209    fn compile_spatial_covers_predicate(
210        b: &mut Builder<Self>,
211        attribute: &str,
212        values: &Array,
213        not: bool,
214    ) -> Result<String> {
215        // Through the step, so a subclass's compileSpatialPredicate() writes this one too.
216        b.step_string(
217            crate::builder::Step::CompileSpatialPredicate,
218            &[
219                crate::builder::Arg::Str("ST_Contains"),
220                crate::builder::Arg::Str(attribute),
221                crate::builder::Arg::Values(values),
222                crate::builder::Arg::Bool(not),
223            ],
224        )
225    }
226
227    fn compile_json_contains_expression(
228        b: &mut Builder<Self>,
229        attribute: &str,
230        values: &Array,
231        not: bool,
232    ) -> Result<String> {
233        mysql::json_contains(b, attribute, values, not)
234    }
235
236    fn compile_json_overlaps_expression(b: &mut Builder<Self>, attribute: &str, values: &Array) -> Result<String> {
237        mysql::json_overlaps(b, attribute, values)
238    }
239
240    fn compile_json_path_expression(b: &mut Builder<Self>, attribute: &str, values: &Array) -> Result<String> {
241        mysql::json_path(b, attribute, values)
242    }
243
244    fn compile_conflict_header(_b: &mut Builder<Self>) -> Result<String> {
245        Ok("ON DUPLICATE KEY UPDATE".into())
246    }
247
248    fn compile_conflict_assignment(wrapped: &str) -> String {
249        format!("VALUES({wrapped})")
250    }
251}
252
253impl Locking for MariaDbDialect {}
254impl Transactions for MariaDbDialect {}
255impl StatisticalAggregates for MariaDbDialect {}
256impl BitwiseAggregates for MariaDbDialect {}
257impl RawSql for MariaDbDialect {}
258impl CrossJoins for MariaDbDialect {}
259impl LateralJoins for MariaDbDialect {}
260impl Spatial for MariaDbDialect {}
261impl FullTextSearch for MariaDbDialect {}
262impl NegatedFullTextSearch for MariaDbDialect {}
263impl ConditionalAggregates for MariaDbDialect {}
264impl Returning for MariaDbDialect {}
265
266impl Json for MariaDbDialect {
267    fn set_json_append(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
268        json_sets::append(b, column, values)
269    }
270    fn set_json_prepend(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
271        json_sets::prepend(b, column, values)
272    }
273    fn set_json_insert(b: &mut Builder<Self>, column: &str, index: i64, value: Value) -> Result<()> {
274        json_sets::insert(b, column, index, value)
275    }
276    fn set_json_remove(b: &mut Builder<Self>, column: &str, value: Value) -> Result<()> {
277        json_sets::remove(b, column, value)
278    }
279    fn set_json_intersect(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
280        json_sets::intersect(b, column, values)
281    }
282    fn set_json_diff(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
283        json_sets::diff(b, column, values)
284    }
285    fn set_json_unique(b: &mut Builder<Self>, column: &str) -> Result<()> {
286        json_sets::unique(b, column)
287    }
288    fn set_json_path(b: &mut Builder<Self>, column: &str, path: &str, value: Value) -> Result<()> {
289        json_sets::path(b, column, path, value)
290    }
291}
292
293impl Hints for MariaDbDialect {
294    fn hint(b: &mut Builder<Self>, hint: &str) -> Result<()> {
295        mysql::add_hint(b, hint)
296    }
297}
298
299impl StringAggregates for MariaDbDialect {
300    fn group_concat_expr(column: &str, order_by: &str) -> String {
301        if order_by.is_empty() {
302            format!("GROUP_CONCAT({column} SEPARATOR ?)")
303        } else {
304            format!("GROUP_CONCAT({column} {order_by} SEPARATOR ?)")
305        }
306    }
307    fn json_array_agg_expr(column: &str) -> String {
308        format!("JSON_ARRAYAGG({column})")
309    }
310    fn json_object_agg_expr(key: &str, value: &str) -> String {
311        format!("JSON_OBJECTAGG({key}, {value})")
312    }
313}
314
315impl Rollup for MariaDbDialect {
316    fn with_rollup(b: &mut Builder<Self>) {
317        b.core.group_by_modifier = Some("WITH ROLLUP".into());
318    }
319}
320
321impl Upsert for MariaDbDialect {
322    fn upsert(b: &mut Builder<Self>) -> Result<Statement> {
323        if !b.core.returning.is_empty() {
324            return Err(Error::Validation(NO_RETURNING_UPSERT.into()));
325        }
326        b.compile_upsert(conflict_clause)
327    }
328}
329
330impl UpsertSelect for MariaDbDialect {
331    fn upsert_select(b: &mut Builder<Self>) -> Result<Statement> {
332        if !b.core.returning.is_empty() {
333            return Err(Error::Validation(NO_RETURNING_UPSERT.into()));
334        }
335        b.compile_upsert_select(conflict_clause)
336    }
337}
338
339impl InsertOrIgnore for MariaDbDialect {
340    fn insert_or_ignore(b: &mut Builder<Self>) -> Result<Statement> {
341        let result = mysql::insert_or_ignore(b)?;
342        b.append_returning(result)
343    }
344}
345
346impl Sequences for MariaDbDialect {
347    fn sequence_expression(b: &mut Builder<Self>, next: bool, sequence: &str) -> Result<String> {
348        Ok(format!("{}({})", if next { "NEXTVAL" } else { "LASTVAL" }, b.quote(sequence)?))
349    }
350}