utopia-query 0.1.0

Queries as data, compiled to SQL (MySQL, MariaDB, PostgreSQL, SQLite, ClickHouse) and MongoDB commands; schema builders; a SQL tokenizer, parser, serializer and statement classifier.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! SQLite: [`Sqlite`], with `INSERT OR IGNORE`, `ON CONFLICT ... excluded`,
//! `json_each` JSON filters and updates, and no regex, full-text or spatial
//! filters.
//!
//! PHP: `Utopia\Query\Builder\SQLite`.

use crate::builder::core::{Builder, Dialect, quote_bytes};
use crate::builder::feature::{
    BitwiseAggregates, ConditionalAggregates, CrossJoins, InsertOrIgnore, Json, Locking, RawSql, StatisticalAggregates,
    StringAggregates, Transactions, Upsert, UpsertSelect,
};
use crate::builder::mysql::conflict_clause;
use crate::builder::postgresql::{json_binding, json_path_parts, on_conflict_header};
use crate::builder::sql::{self, SqlDialect};
use crate::builder::types::{Condition, Statement};
use crate::error::{Error, Result};
use crate::method::Method;
use crate::query::Query;
use crate::value::{self, Array, Value};

/// A SQLite builder.
///
/// PHP: `Utopia\Query\Builder\SQLite`.
///
/// ```
/// use utopia_query::Query;
/// use utopia_query::builder::Sqlite;
///
/// let statement = Sqlite::new().from("users", "").filter([Query::regex("name", "^a")]).build();
/// assert_eq!(statement.unwrap_err().to_string(), "REGEXP is not natively supported in SQLite.");
///
/// let statement = Sqlite::new().from("users", "").sort_random().limit(5).build()?;
/// assert_eq!(statement.query, "SELECT * FROM `users` ORDER BY RANDOM() LIMIT ?");
/// # Ok::<(), utopia_query::Error>(())
/// ```
///
/// ```php
/// use Utopia\Query\Builder\SQLite;
/// use Utopia\Query\Query;
///
/// try {
///     (new SQLite())->from('users')->filter([Query::regex('name', '^a')])->build();
/// } catch (\Utopia\Query\Exception\UnsupportedException $e) {
///     echo $e->getMessage(), "\n"; // REGEXP is not natively supported in SQLite.
/// }
/// echo (new SQLite())->from('users')->sortRandom()->limit(5)->build()->query, "\n";
/// // SELECT * FROM `users` ORDER BY RANDOM() LIMIT ?
/// ```
pub type Sqlite = Builder<SqliteDialect>;

/// The SQLite dialect.
#[derive(Debug, Clone, Default)]
pub struct SqliteDialect;

/// `EXISTS (SELECT 1 FROM json_each(attribute) WHERE json_each.value = json(?))`
/// for each element of the first value, joined with `glue`.
fn json_each_conditions(b: &mut Builder<SqliteDialect>, attribute: &str, values: &Array, glue: &str) -> String {
    let items = match values.get(&php_std::ArrayKey::Int(0)) {
        Some(Value::Array(items) | Value::Object(items)) => items.values().cloned().collect(),
        Some(Value::Null) | None => Vec::new(),
        Some(other) => vec![other.clone()],
    };
    let mut conditions = Vec::with_capacity(items.len());
    for item in &items {
        b.add_binding(json_binding(item), None);
        conditions.push(format!("EXISTS (SELECT 1 FROM json_each({attribute}) WHERE json_each.value = json(?))"));
    }
    format!("({})", conditions.join(glue))
}

impl Dialect for SqliteDialect {
    const CLASS: &'static str = "Utopia\\Query\\Builder\\SQLite";
    const DECLARES_LIKE_ESCAPE: bool = true;
    const IMPLICIT_LIKE_ESCAPE: Option<u8> = None;
    const LITERAL: crate::StringLiteral = crate::StringLiteral::Standard;

    fn base_step(
        b: &mut Builder<Self>,
        step: crate::builder::Step,
        arguments: &[crate::builder::Arg<'_>],
    ) -> Option<Result<crate::builder::Ret>> {
        sql::sql_base_step(b, step, arguments)
            .or_else(|| crate::builder::feature::aggregates_base_step::<Self>(step, arguments))
    }

    fn quote_string(value: &[u8]) -> Vec<u8> {
        quote_bytes(value, false)
    }

    fn compile_random(_b: &Builder<Self>) -> String {
        "RANDOM()".into()
    }

    fn compile_regex(b: &mut Builder<Self>, attribute: &str, values: &Array, column: Option<&str>) -> Result<String> {
        if b.core.flavor.sqlite.is_none() {
            return Err(Error::Unsupported("REGEXP is not natively supported in SQLite.".into()));
        }
        b.add_binding(crate::builder::core::first(values), column);
        Ok(format!("{attribute} REGEXP ?"))
    }

    fn compile_like(
        b: &mut Builder<Self>,
        attribute: &str,
        values: &Array,
        prefix: &str,
        suffix: &str,
        not: bool,
        column: Option<&str>,
    ) -> Result<String> {
        if b.core.flavor.sqlite.is_none() {
            return b.base_compile_like(attribute, values, prefix, suffix, not, column);
        }
        b.sqlite_like(attribute, values, prefix, suffix, not, column)
    }

    fn compile_contains(
        b: &mut Builder<Self>,
        attribute: &str,
        values: &Array,
        column: Option<&str>,
    ) -> Result<String> {
        if b.core.flavor.sqlite.is_none() {
            return b.base_compile_contains(attribute, values, column);
        }
        let predicates = b.sqlite_substrings(attribute, values, false, column)?;
        Ok(if predicates.len() == 1 { predicates[0].clone() } else { format!("({})", predicates.join(" OR ")) })
    }

    fn compile_contains_all(
        b: &mut Builder<Self>,
        attribute: &str,
        values: &Array,
        column: Option<&str>,
    ) -> Result<String> {
        if b.core.flavor.sqlite.is_none() {
            return b.base_compile_contains_all(attribute, values, column);
        }
        Ok(format!("({})", b.sqlite_substrings(attribute, values, false, column)?.join(" AND ")))
    }

    fn compile_not_contains(
        b: &mut Builder<Self>,
        attribute: &str,
        values: &Array,
        column: Option<&str>,
    ) -> Result<String> {
        if b.core.flavor.sqlite.is_none() {
            return b.base_compile_not_contains(attribute, values, column);
        }
        let predicates = b.sqlite_substrings(attribute, values, true, column)?;
        Ok(if predicates.len() == 1 { predicates[0].clone() } else { format!("({})", predicates.join(" AND ")) })
    }

    fn compile_filter(b: &mut Builder<Self>, query: &Query) -> Result<String> {
        sql::sql_compile_filter(b, query)
    }

    fn wrap_union_member(_b: &Builder<Self>, sql: &str) -> String {
        // SQLite's compound-SELECT parser rejects parenthesised members.
        sql.to_owned()
    }

    fn update(b: &mut Builder<Self>) -> Result<Statement> {
        for (column, condition) in b.core.json_sets.0.clone() {
            b.core.raw_sets.set(column.clone(), condition.expression);
            b.core.raw_set_bindings.set(column, condition.bindings);
        }
        let result = b.base_update()?;
        b.core.json_sets.clear();
        Ok(result)
    }

    fn reset(b: &mut Builder<Self>) {
        b.core.json_sets.clear();
    }

    fn ast_dialect() -> crate::builder::AstDialect {
        crate::builder::AstDialect::Sqlite
    }
}

impl SqlDialect for SqliteDialect {
    fn compile_search_expression(
        _b: &mut Builder<Self>,
        _attribute: &str,
        _values: &Array,
        _not: bool,
    ) -> Result<String> {
        Err(Error::Unsupported("Full-text search is not supported in the SQLite query builder.".into()))
    }

    fn compile_spatial_distance(
        _b: &mut Builder<Self>,
        _method: Method,
        _attribute: &str,
        _values: &Array,
    ) -> Result<String> {
        Err(Error::Unsupported("Spatial distance queries are not supported in SQLite.".into()))
    }

    fn compile_spatial_predicate(
        _b: &mut Builder<Self>,
        _function: &str,
        _attribute: &str,
        _values: &Array,
        _not: bool,
    ) -> Result<String> {
        Err(Error::Unsupported("Spatial predicates are not supported in SQLite.".into()))
    }

    fn compile_spatial_covers_predicate(
        _b: &mut Builder<Self>,
        _attribute: &str,
        _values: &Array,
        _not: bool,
    ) -> Result<String> {
        Err(Error::Unsupported("Spatial covers predicates are not supported in SQLite.".into()))
    }

    fn compile_json_contains_expression(
        b: &mut Builder<Self>,
        attribute: &str,
        values: &Array,
        not: bool,
    ) -> Result<String> {
        if b.core.flavor.sqlite.is_some() {
            let needles = crate::builder::core::first(values);
            let expression = format!("({})", b.sqlite_element_matches(attribute, &needles)?.join(" AND "));
            return Ok(if not { format!("({attribute} IS NOT NULL AND NOT {expression})") } else { expression });
        }
        let expression = json_each_conditions(b, attribute, values, " AND ");
        Ok(if not { format!("NOT {expression}") } else { expression })
    }

    fn compile_json_overlaps_expression(b: &mut Builder<Self>, attribute: &str, values: &Array) -> Result<String> {
        if b.core.flavor.sqlite.is_some() {
            let needles = crate::builder::core::first(values);
            return Ok(format!("({})", b.sqlite_element_matches(attribute, &needles)?.join(" OR ")));
        }
        Ok(json_each_conditions(b, attribute, values, " OR "))
    }

    fn compile_array_filter(b: &mut Builder<Self>, method: Method, attribute: &str, query: &Query) -> Result<String> {
        if b.core.flavor.sqlite.is_some() && method == Method::NotContains {
            let wrapped = value::list([Value::Array(query.values().clone())]);
            let overlaps = b.step_string(
                crate::builder::Step::CompileJsonOverlapsExpression,
                &[crate::builder::Arg::Str(attribute), crate::builder::Arg::Values(&wrapped)],
            )?;
            return Ok(format!("({attribute} IS NOT NULL AND NOT {overlaps})"));
        }
        sql::sql_compile_array_filter(b, method, attribute, query)
    }

    fn compile_json_path_expression(b: &mut Builder<Self>, attribute: &str, values: &Array) -> Result<String> {
        let (path, operator) = json_path_parts(b, values)?;
        Ok(format!("json_extract({attribute}, '$.{path}') {operator} ?"))
    }

    fn compile_conflict_header(b: &mut Builder<Self>) -> Result<String> {
        on_conflict_header(b)
    }

    fn compile_conflict_assignment(wrapped: &str) -> String {
        format!("excluded.{wrapped}")
    }
}

impl Locking for SqliteDialect {}
impl Transactions for SqliteDialect {}
impl StatisticalAggregates for SqliteDialect {}
impl BitwiseAggregates for SqliteDialect {}
impl RawSql for SqliteDialect {}
impl CrossJoins for SqliteDialect {}
impl ConditionalAggregates for SqliteDialect {}

impl StringAggregates for SqliteDialect {
    fn group_concat_expr(column: &str, order_by: &str) -> String {
        if order_by.is_empty() {
            format!("GROUP_CONCAT({column}, ?)")
        } else {
            format!("GROUP_CONCAT({column} {order_by}, ?)")
        }
    }
    fn json_array_agg_expr(column: &str) -> String {
        format!("json_group_array({column})")
    }
    fn json_object_agg_expr(key: &str, value: &str) -> String {
        format!("json_group_object({key}, {value})")
    }
}

impl Upsert for SqliteDialect {
    fn upsert(b: &mut Builder<Self>) -> Result<Statement> {
        b.compile_upsert(conflict_clause)
    }
}

impl UpsertSelect for SqliteDialect {
    fn upsert_select(b: &mut Builder<Self>) -> Result<Statement> {
        b.compile_upsert_select(conflict_clause)
    }
}

impl InsertOrIgnore for SqliteDialect {
    fn insert_or_ignore(b: &mut Builder<Self>) -> Result<Statement> {
        b.core.bindings.clear();
        let (sql, bindings) = b.compile_insert_body()?;
        b.add_bindings(bindings);
        let sql = match sql.strip_prefix("INSERT INTO") {
            Some(rest) => format!("INSERT OR IGNORE INTO{rest}"),
            None => sql,
        };
        Ok(b.statement(sql))
    }
}

impl Json for SqliteDialect {
    fn set_json_append(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
        let wrapped = b.resolve_and_wrap(column)?;
        b.core.json_sets.set(
            column,
            Condition::new(
                format!(
                    "json_group_array(value) FROM (SELECT value FROM json_each(IFNULL({wrapped}, '[]')) UNION ALL SELECT value FROM json_each(?))"
                ),
                vec![json_binding(&Value::Array(values.clone()))],
            ),
        );
        Ok(())
    }

    fn set_json_prepend(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
        let wrapped = b.resolve_and_wrap(column)?;
        b.core.json_sets.set(
            column,
            Condition::new(
                format!(
                    "json_group_array(value) FROM (SELECT value FROM json_each(?) UNION ALL SELECT value FROM json_each(IFNULL({wrapped}, '[]')))"
                ),
                vec![json_binding(&Value::Array(values.clone()))],
            ),
        );
        Ok(())
    }

    fn set_json_insert(b: &mut Builder<Self>, column: &str, index: i64, value: Value) -> Result<()> {
        let wrapped = b.resolve_and_wrap(column)?;
        b.core.json_sets.set(
            column,
            Condition::new(format!("json_insert({wrapped}, '$[{index}]', json(?))"), vec![json_binding(&value)]),
        );
        Ok(())
    }

    fn set_json_remove(b: &mut Builder<Self>, column: &str, value: Value) -> Result<()> {
        let wrapped = b.resolve_and_wrap(column)?;
        b.core.json_sets.set(
            column,
            Condition::new(
                format!("(SELECT json_group_array(value) FROM json_each({wrapped}) WHERE value != json(?))"),
                vec![json_binding(&value)],
            ),
        );
        Ok(())
    }

    fn set_json_intersect(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
        let wrapped = b.resolve_and_wrap(column)?;
        b.set_raw(
            column,
            format!(
                "(SELECT json_group_array(value) FROM json_each(IFNULL({wrapped}, '[]')) WHERE value IN (SELECT value FROM json_each(?)))"
            ),
            vec![json_binding(&Value::Array(values.clone()))],
        );
        Ok(())
    }

    fn set_json_diff(b: &mut Builder<Self>, column: &str, values: &Array) -> Result<()> {
        let wrapped = b.resolve_and_wrap(column)?;
        b.set_raw(
            column,
            format!(
                "(SELECT json_group_array(value) FROM json_each(IFNULL({wrapped}, '[]')) WHERE value NOT IN (SELECT value FROM json_each(?)))"
            ),
            vec![json_binding(&Value::Array(values.clone()))],
        );
        Ok(())
    }

    fn set_json_unique(b: &mut Builder<Self>, column: &str) -> Result<()> {
        let wrapped = b.resolve_and_wrap(column)?;
        b.set_raw(
            column,
            format!("(SELECT json_group_array(DISTINCT value) FROM json_each(IFNULL({wrapped}, '[]')))"),
            Vec::<Value>::new(),
        );
        Ok(())
    }

    fn set_json_path(b: &mut Builder<Self>, column: &str, path: &str, value: Value) -> Result<()> {
        if !path.starts_with('$') {
            return Err(Error::Validation(format!("JSON path must start with '$': {path}")));
        }
        let wrapped = b.resolve_and_wrap(column)?;
        b.core
            .json_sets
            .set(column, Condition::new(format!("json_set({wrapped}, ?, ?)"), vec![value::string(path), value]));
        Ok(())
    }
}