utopia-query 0.1.1

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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! The values builders produce and keep: statements, conditions, join and
//! window definitions.

use std::fmt;
use std::sync::Arc;

use crate::error::{Error, Result};
use crate::method::backed_enum;
use crate::value::{Array, Value};

/// What runs a statement: given it, returns its rows (an array) or an
/// affected-row count (an integer).
///
/// PHP: the `Closure(Statement): (array|int)` of `setExecutor()` / `withExecutor()`.
pub type Executor = Arc<dyn Fn(&Statement) -> Result<Value> + Send + Sync>;

/// A compiled statement: the SQL (or MongoDB command JSON) with `?`
/// placeholders and the values bound to them, in order.
///
/// PHP: `Utopia\Query\Builder\Statement`.
#[derive(Clone)]
pub struct Statement {
    /// The statement text.
    pub query: String,
    /// The values of the placeholders, in order.
    pub bindings: Vec<Value>,
    /// Whether the statement only reads.
    pub read_only: bool,
    /// Named parameters (ClickHouse's `{name:Type}` placeholders), if any.
    pub named_bindings: Option<Array>,
    executor: Option<Executor>,
}

impl fmt::Debug for Statement {
    /// The statement without its executor.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Statement")
            .field("query", &self.query)
            .field("bindings", &self.bindings)
            .field("read_only", &self.read_only)
            .field("named_bindings", &self.named_bindings)
            .field("executor", &self.executor.is_some())
            .finish()
    }
}

impl PartialEq for Statement {
    /// Same text, bindings and flags (executors are not compared).
    fn eq(&self, other: &Self) -> bool {
        self.query == other.query
            && self.bindings == other.bindings
            && self.read_only == other.read_only
            && self.named_bindings == other.named_bindings
    }
}

impl Statement {
    /// A statement that is not read-only and has no executor.
    ///
    /// PHP: `new Statement($query, $bindings)`.
    pub fn new(query: impl Into<String>, bindings: Vec<Value>) -> Self {
        Statement { query: query.into(), bindings, read_only: false, named_bindings: None, executor: None }
    }

    /// Every part of a statement.
    ///
    /// PHP: `new Statement($query, $bindings, $readOnly, $executor, $namedBindings)`.
    pub fn with_parts(
        query: impl Into<String>,
        bindings: Vec<Value>,
        read_only: bool,
        executor: Option<Executor>,
        named_bindings: Option<Array>,
    ) -> Self {
        Statement { query: query.into(), bindings, read_only, named_bindings, executor }
    }

    /// Runs the statement with its executor.
    ///
    /// PHP: `execute()`, which throws `BadMethodCallException` ([`Error::NoExecutor`]) without one.
    pub fn execute(&self) -> Result<Value> {
        match &self.executor {
            Some(executor) => executor(self),
            None => Err(Error::NoExecutor("No executor configured on this plan".into())),
        }
    }

    /// The same statement run by `executor`.
    ///
    /// PHP: `withExecutor()`.
    pub fn with_executor(&self, executor: Executor) -> Statement {
        Statement { executor: Some(executor), ..self.clone() }
    }

    /// The executor, if any.
    pub fn executor(&self) -> Option<&Executor> {
        self.executor.as_ref()
    }
}

/// A binding captured while compiling: the value and the column it was
/// compared to, when known (ClickHouse types named parameters by column).
///
/// PHP: `Utopia\Query\Builder\Binding`.
#[derive(Debug, Clone, PartialEq)]
pub struct Binding {
    /// The value.
    pub value: Value,
    /// The raw column name, if the value was bound against one.
    pub column: Option<String>,
}

impl Binding {
    /// A binding of `value` against `column`.
    pub fn new(value: Value, column: Option<String>) -> Self {
        Binding { value, column }
    }
}

/// A SQL fragment with its bindings.
///
/// PHP: `Utopia\Query\Builder\Condition`.
#[derive(Debug, Clone, PartialEq)]
pub struct Condition {
    /// The SQL, with `?` placeholders.
    pub expression: String,
    /// The values of the placeholders.
    pub bindings: Vec<Value>,
}

impl Condition {
    /// A fragment with its bindings.
    pub fn new(expression: impl Into<String>, bindings: Vec<Value>) -> Self {
        Condition { expression: expression.into(), bindings }
    }
}

/// `left operator right`, both columns.
///
/// PHP: `Utopia\Query\Builder\ColumnPredicate`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ColumnPredicate {
    /// The left column.
    pub left: String,
    /// The operator.
    pub operator: String,
    /// The right column.
    pub right: String,
}

impl ColumnPredicate {
    /// A column comparison.
    pub fn new(left: impl Into<String>, operator: impl Into<String>, right: impl Into<String>) -> Self {
        ColumnPredicate { left: left.into(), operator: operator.into(), right: right.into() }
    }
}

/// A common table expression, compiled.
///
/// PHP: `Utopia\Query\Builder\CteClause`.
#[derive(Debug, Clone, PartialEq)]
pub struct CteClause {
    /// The name.
    pub name: String,
    /// The SQL.
    pub query: String,
    /// The bindings of the SQL.
    pub bindings: Vec<Value>,
    /// Whether it is recursive.
    pub recursive: bool,
    /// The column names, if given.
    pub columns: Vec<String>,
}

impl CteClause {
    /// A compiled CTE.
    pub fn new(
        name: impl Into<String>,
        query: impl Into<String>,
        bindings: Vec<Value>,
        recursive: bool,
        columns: Vec<String>,
    ) -> Self {
        CteClause { name: name.into(), query: query.into(), bindings, recursive, columns }
    }
}

/// A column-to-column condition of a join built with a [`JoinBuilder`](super::JoinBuilder).
///
/// PHP: `Utopia\Query\Builder\JoinOn`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JoinOn {
    /// The left column.
    pub left: String,
    /// The operator.
    pub operator: String,
    /// The right column.
    pub right: String,
}

impl JoinOn {
    /// A join condition.
    pub fn new(left: impl Into<String>, operator: impl Into<String>, right: impl Into<String>) -> Self {
        JoinOn { left: left.into(), operator: operator.into(), right: right.into() }
    }
}

backed_enum! {
    /// A kind of join, as its SQL keyword.
    ///
    /// PHP: `Utopia\Query\Builder\JoinType`.
    pub enum JoinType: "Utopia\\Query\\Builder\\JoinType" {
        /// `JOIN`.
        Inner = "JOIN",
        /// `LEFT JOIN`.
        Left = "LEFT JOIN",
        /// `RIGHT JOIN`.
        Right = "RIGHT JOIN",
        /// `CROSS JOIN`.
        Cross = "CROSS JOIN",
        /// `FULL OUTER JOIN`.
        FullOuter = "FULL OUTER JOIN",
        /// `NATURAL JOIN`.
        Natural = "NATURAL JOIN",
    }
}

backed_enum! {
    /// A row lock, as its SQL.
    ///
    /// PHP: `Utopia\Query\Builder\LockMode`.
    pub enum LockMode: "Utopia\\Query\\Builder\\LockMode" {
        /// `FOR UPDATE`.
        ForUpdate = "FOR UPDATE",
        /// `FOR SHARE`.
        ForShare = "FOR SHARE",
        /// `FOR UPDATE SKIP LOCKED`.
        ForUpdateSkipLocked = "FOR UPDATE SKIP LOCKED",
        /// `FOR UPDATE NOWAIT`.
        ForUpdateNoWait = "FOR UPDATE NOWAIT",
        /// `FOR SHARE SKIP LOCKED`.
        ForShareSkipLocked = "FOR SHARE SKIP LOCKED",
        /// `FOR SHARE NOWAIT`.
        ForShareNoWait = "FOR SHARE NOWAIT",
    }
}

impl LockMode {
    /// The SQL.
    ///
    /// PHP: `toSql()`.
    pub fn to_sql(self) -> &'static str {
        self.as_str()
    }
}

backed_enum! {
    /// How a compound select combines its members.
    ///
    /// PHP: `Utopia\Query\Builder\UnionType`.
    pub enum UnionType: "Utopia\\Query\\Builder\\UnionType" {
        /// `UNION`.
        Union = "UNION",
        /// `UNION ALL`.
        UnionAll = "UNION ALL",
        /// `INTERSECT`.
        Intersect = "INTERSECT",
        /// `INTERSECT ALL`.
        IntersectAll = "INTERSECT ALL",
        /// `EXCEPT`.
        Except = "EXCEPT",
        /// `EXCEPT ALL`.
        ExceptAll = "EXCEPT ALL",
    }
}

/// A compiled member of a compound select.
///
/// PHP: `Utopia\Query\Builder\UnionClause`.
#[derive(Debug, Clone, PartialEq)]
pub struct UnionClause {
    /// How it combines.
    pub union_type: UnionType,
    /// The SQL.
    pub query: String,
    /// Its bindings.
    pub bindings: Vec<Value>,
}

impl UnionClause {
    /// A compiled member.
    pub fn new(union_type: UnionType, query: impl Into<String>, bindings: Vec<Value>) -> Self {
        UnionClause { union_type, query: query.into(), bindings }
    }
}

backed_enum! {
    /// A vector distance metric (pgvector).
    ///
    /// PHP: `Utopia\Query\Builder\VectorMetric`.
    pub enum VectorMetric: "Utopia\\Query\\Builder\\VectorMetric" {
        /// Cosine distance.
        Cosine = "cosine",
        /// Euclidean distance.
        Euclidean = "euclidean",
        /// Negative inner product.
        Dot = "dot",
    }
}

impl VectorMetric {
    /// The pgvector operator: `<=>`, `<->` or `<#>`.
    ///
    /// PHP: `toOperator()`.
    pub fn to_operator(self) -> &'static str {
        match self {
            VectorMetric::Cosine => "<=>",
            VectorMetric::Euclidean => "<->",
            VectorMetric::Dot => "<#>",
        }
    }
}

/// A window frame: `ROWS UNBOUNDED PRECEDING`, `RANGE BETWEEN ... AND ...`.
///
/// PHP: `Utopia\Query\Builder\WindowFrame`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WindowFrame {
    /// `ROWS`, `RANGE` or `GROUPS`.
    pub frame_type: String,
    /// The start bound.
    pub start: String,
    /// The end bound, if any.
    pub end: Option<String>,
}

impl WindowFrame {
    /// A frame.
    pub fn new(frame_type: impl Into<String>, start: impl Into<String>, end: Option<String>) -> Self {
        WindowFrame { frame_type: frame_type.into(), start: start.into(), end }
    }

    /// The SQL.
    ///
    /// PHP: `toSql()`.
    pub fn to_sql(&self) -> String {
        match &self.end {
            None => format!("{} {}", self.frame_type, self.start),
            Some(end) => format!("{} BETWEEN {} AND {}", self.frame_type, self.start, end),
        }
    }
}

/// A named window: `WINDOW name AS (...)`.
///
/// PHP: `Utopia\Query\Builder\WindowDefinition`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WindowDefinition {
    /// The name.
    pub name: String,
    /// The partition columns, if any.
    pub partition_by: Option<Vec<String>>,
    /// The order columns (`-col` descending), if any.
    pub order_by: Option<Vec<String>>,
    /// The frame, if any.
    pub frame: Option<WindowFrame>,
}

impl WindowDefinition {
    /// A named window.
    pub fn new(
        name: impl Into<String>,
        partition_by: Option<Vec<String>>,
        order_by: Option<Vec<String>>,
        frame: Option<WindowFrame>,
    ) -> Self {
        WindowDefinition { name: name.into(), partition_by, order_by, frame }
    }
}

/// A window function in the select list.
///
/// PHP: `Utopia\Query\Builder\WindowSelect`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WindowSelect {
    /// The function call (`ROW_NUMBER()`).
    pub function: String,
    /// The alias.
    pub alias: String,
    /// The partition columns, if any.
    pub partition_by: Option<Vec<String>>,
    /// The order columns (`-col` descending), if any.
    pub order_by: Option<Vec<String>>,
    /// A named window used instead of an inline one.
    pub window_name: Option<String>,
    /// The frame, if any.
    pub frame: Option<WindowFrame>,
}

impl WindowSelect {
    /// A window function.
    pub fn new(
        function: impl Into<String>,
        alias: impl Into<String>,
        partition_by: Option<Vec<String>>,
        order_by: Option<Vec<String>>,
        window_name: Option<String>,
        frame: Option<WindowFrame>,
    ) -> Self {
        WindowSelect { function: function.into(), alias: alias.into(), partition_by, order_by, window_name, frame }
    }
}

/// A `MERGE` action and its bindings.
///
/// PHP: `Utopia\Query\Builder\MergeClause`.
#[derive(Debug, Clone, PartialEq)]
pub struct MergeClause {
    /// The action SQL.
    pub action: String,
    /// Whether it applies to matched rows.
    pub matched: bool,
    /// Its bindings.
    pub bindings: Vec<Value>,
}

impl MergeClause {
    /// A merge action.
    pub fn new(action: impl Into<String>, matched: bool, bindings: Vec<Value>) -> Self {
        MergeClause { action: action.into(), matched, bindings }
    }
}

/// The geometry, distance and unit of a `distance*` query.
///
/// PHP: `Utopia\Query\Builder\SpatialDistanceFilter`.
#[derive(Debug, Clone, PartialEq)]
pub struct SpatialDistanceFilter {
    /// WKT, or a coordinate array.
    pub geometry: Value,
    /// The distance threshold.
    pub distance: f64,
    /// Whether the distance is in meters (sphere / geography).
    pub meters: bool,
}

impl SpatialDistanceFilter {
    /// A distance filter.
    pub fn new(geometry: Value, distance: f64, meters: bool) -> Self {
        SpatialDistanceFilter { geometry, distance, meters }
    }

    /// The filter from the `[geometry, distance, meters]` value of a `distance*` query.
    ///
    /// PHP: `SpatialDistanceFilter::fromTuple()`.
    /// Fails with [`Error::Validation`] unless the geometry is a WKT string
    /// or a coordinate array, the distance a finite number (a numeric
    /// string counts), and `meters` a boolean as `FILTER_VALIDATE_BOOL`
    /// reads one (`true`, `1`, `"on"`, `"no"`, ...; absent is `false`).
    pub fn from_tuple(tuple: &Array) -> crate::Result<Self> {
        let at = |i: i64| tuple.get(&php_std::ArrayKey::Int(i)).filter(|v| !matches!(v, Value::Null));
        let geometry = match at(0) {
            Some(g @ (Value::Str(_) | Value::Array(_))) => g.clone(),
            _ => {
                return Err(Error::Validation(
                    "Invalid distance query: the geometry must be a WKT string or a coordinate array".into(),
                ));
            }
        };
        let distance = at(1).filter(|d| crate::query::is_numeric(d)).map(Value::to_double);
        let Some(distance) = distance.filter(|d| d.is_finite()) else {
            return Err(Error::Validation("Invalid distance query: the distance must be a finite number".into()));
        };
        let Some(meters) = at(2).map_or(Some(false), filter_bool) else {
            return Err(Error::Validation("Invalid distance query: meters must be a boolean".into()));
        };
        Ok(SpatialDistanceFilter { geometry, distance, meters })
    }
}

/// `filter_var($value, FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE)`:
/// `None` when the value is not a boolean.
fn filter_bool(value: &Value) -> Option<bool> {
    use php_std::filter as f;
    let value = match value {
        Value::Null => f::Value::Null,
        Value::Bool(b) => f::Value::Bool(*b),
        Value::Int(i) => f::Value::Int(*i),
        Value::Float(x) => f::Value::Float(*x),
        Value::Str(s) => f::Value::Str(s.as_bytes().to_vec()),
        // Neither an array nor an object without `__toString()` is a scalar.
        _ => return None,
    };
    match f::filter_var(&value, f::FILTER_VALIDATE_BOOL, &f::Options::Flags(f::FILTER_NULL_ON_FAILURE)) {
        Ok(f::Filtered { value: f::Value::Bool(b), .. }) => Some(b),
        _ => None,
    }
}