ruprizzle 1.6.0

A schema-first ORM for Rust: typed queries, relations, and automatic migrations
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
//! Filter algebra and constructors.

use std::marker::PhantomData;

use crate::compile::CompiledSql;
use crate::json::JsonPath;
use crate::model::Model;
use crate::query::SelectQuery;
use crate::value::Value;

/// An injection-safe raw SQL fragment with bound parameters.
///
/// The literal parts are stored separately, and values are bound as
/// parameters. Calling [`RawFragment::sql`] returns the fragment with
/// PostgreSQL-style placeholders (`$1`, `$2`, ...).
#[derive(Debug, Clone, PartialEq)]
pub struct RawFragment {
    /// Literal fragments of the SQL, between placeholders.
    pub(crate) parts: Vec<String>,
    /// Bound values for each placeholder.
    pub(crate) binds: Vec<Value>,
}

impl RawFragment {
    /// Creates a new raw fragment.
    #[must_use]
    pub fn new(parts: Vec<String>, binds: Vec<Value>) -> Self {
        assert_eq!(
            parts.len(),
            binds.len() + 1,
            "RawFragment parts must split the format string around each placeholder"
        );
        Self { parts, binds }
    }

    /// Returns the SQL fragment with `$1`, `$2`, ... placeholders.
    #[must_use]
    pub fn sql(&self) -> String {
        let mut out = String::new();
        for (i, part) in self.parts.iter().enumerate() {
            out.push_str(part);
            if i < self.binds.len() {
                out.push_str(&format!("${}", i + 1));
            }
        }
        out
    }

    /// Returns the bound values for this fragment.
    #[must_use]
    pub fn binds(&self) -> &[Value] {
        &self.binds
    }
}

/// A compiled `SELECT` subquery that returns a single column of type `T`.
///
/// It is typically produced by `SelectQuery::columns(...).into::<Subquery<T>>()`
/// and consumed by [`Column::in_subquery`](crate::col::Column::in_subquery).
pub struct Subquery<T> {
    /// The compiled SQL of the subquery, including its bound values.
    pub(crate) compiled: CompiledSql,
    _marker: PhantomData<fn() -> T>,
}

impl<T> Clone for Subquery<T> {
    fn clone(&self) -> Self {
        Self {
            compiled: self.compiled.clone(),
            _marker: PhantomData,
        }
    }
}

impl<T> std::fmt::Debug for Subquery<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Subquery")
            .field("compiled", &self.compiled)
            .finish()
    }
}

impl<T> PartialEq for Subquery<T> {
    fn eq(&self, other: &Self) -> bool {
        self.compiled == other.compiled
    }
}

impl<'db, M, T, I> From<SelectQuery<'db, M, (T,), I>> for Subquery<T>
where
    M: Model,
{
    fn from(query: SelectQuery<'db, M, (T,), I>) -> Self {
        Self {
            compiled: query.to_sql().unwrap_or_else(|_| {
                unreachable!("subquery SQL compilation is an internal invariant")
            }),
            _marker: PhantomData,
        }
    }
}

/// A compiled subquery used by `EXISTS` / `NOT EXISTS` filters.
///
/// Unlike [`Subquery`], `EXISTS` does not care about the projection shape,
/// so any [`SelectQuery`] can be converted into an `ExistsSubquery`.
pub struct ExistsSubquery {
    pub(crate) compiled: CompiledSql,
}

impl Clone for ExistsSubquery {
    fn clone(&self) -> Self {
        Self {
            compiled: self.compiled.clone(),
        }
    }
}

impl std::fmt::Debug for ExistsSubquery {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ExistsSubquery")
            .field("compiled", &self.compiled)
            .finish()
    }
}

impl PartialEq for ExistsSubquery {
    fn eq(&self, other: &Self) -> bool {
        self.compiled == other.compiled
    }
}

impl<'db, M, Out, I> From<SelectQuery<'db, M, Out, I>> for ExistsSubquery
where
    M: Model,
{
    fn from(query: SelectQuery<'db, M, Out, I>) -> Self {
        Self {
            compiled: query.to_sql().unwrap_or_else(|_| {
                unreachable!("EXISTS subquery SQL compilation is an internal invariant")
            }),
        }
    }
}

/// A compiled common table expression (CTE).
///
/// Stored inside a [`SelectQuery`] and emitted as
/// `WITH ... AS (...)` or `WITH RECURSIVE ... AS (...)` when the query is
/// compiled.
#[derive(Debug, Clone, PartialEq)]
pub struct Cte {
    /// The CTE name.
    pub name: &'static str,
    /// The compiled body.
    pub compiled: CompiledSql,
    /// Whether this CTE is recursive.
    pub recursive: bool,
}

impl Cte {
    /// Creates a new non-recursive CTE.
    #[must_use]
    pub fn new(name: &'static str, compiled: CompiledSql) -> Self {
        Self {
            name,
            compiled,
            recursive: false,
        }
    }
}

/// A compiled query that can be used as the body of a CTE.
///
/// This is a thin wrapper around [`CompiledSql`] so that
/// [`SelectQuery::with`](crate::query::SelectQuery::with) and
/// [`SelectQuery::with_recursive`](crate::query::SelectQuery::with_recursive)
/// can accept anything that converts into it.
#[derive(Debug, Clone, PartialEq)]
pub struct CteQuery {
    pub(crate) compiled: CompiledSql,
}

impl CteQuery {
    pub(crate) fn new(compiled: CompiledSql) -> Self {
        Self { compiled }
    }
}

impl<'db, M, Out, I> From<SelectQuery<'db, M, Out, I>> for CteQuery
where
    M: Model,
{
    fn from(query: SelectQuery<'db, M, Out, I>) -> Self {
        Self::new(
            query
                .to_sql()
                .unwrap_or_else(|_| unreachable!("CTE SQL compilation is an internal invariant")),
        )
    }
}

/// A predicate that is tied to a model `M`.
pub struct Filter<M> {
    /// The root filter node.
    pub node: FilterNode,
    _marker: PhantomData<fn() -> M>,
}

impl<M> std::fmt::Debug for Filter<M> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Filter").field("node", &self.node).finish()
    }
}

impl<M> Clone for Filter<M> {
    fn clone(&self) -> Self {
        Self {
            node: self.node.clone(),
            _marker: PhantomData,
        }
    }
}

impl<M> PartialEq for Filter<M> {
    fn eq(&self, other: &Self) -> bool {
        self.node == other.node
    }
}

impl<M> Filter<M> {
    /// Creates a new filter.
    #[must_use]
    pub const fn new(node: FilterNode) -> Self {
        Self {
            node,
            _marker: PhantomData,
        }
    }

    /// Combines two filters with `AND`.
    #[must_use]
    pub fn and(self, other: Self) -> Self {
        Self::new(flatten_and(vec![self.node, other.node]))
    }

    /// Combines two filters with `OR`.
    #[must_use]
    pub fn or(self, other: Self) -> Self {
        Self::new(flatten_or(vec![self.node, other.node]))
    }

    /// Creates a filter from a raw SQL fragment.
    #[must_use]
    pub fn raw(fragment: RawFragment) -> Self {
        Self::new(FilterNode::Raw(fragment))
    }

    /// `EXISTS (subquery)`.
    #[must_use]
    pub fn exists(subquery: impl Into<ExistsSubquery>) -> Self {
        Self::new(FilterNode::ExistsSubquery {
            subquery: subquery.into().compiled,
            negated: false,
        })
    }

    /// `NOT EXISTS (subquery)`.
    #[must_use]
    pub fn not_exists(subquery: impl Into<ExistsSubquery>) -> Self {
        Self::new(FilterNode::ExistsSubquery {
            subquery: subquery.into().compiled,
            negated: true,
        })
    }
}

impl<M> std::ops::Not for Filter<M> {
    type Output = Self;

    fn not(self) -> Self::Output {
        Self::new(FilterNode::Not(Box::new(self.node)))
    }
}

/// A filter node, independent of the model it operates on.
#[derive(Debug, Clone, PartialEq)]
#[allow(missing_docs)]
pub enum FilterNode {
    Cmp {
        table: &'static str,
        column: &'static str,
        op: CmpOp,
        value: Value,
    },
    Between {
        table: &'static str,
        column: &'static str,
        lo: Value,
        hi: Value,
    },
    Null {
        table: &'static str,
        column: &'static str,
        negated: bool,
    },
    In {
        table: &'static str,
        column: &'static str,
        values: Vec<Value>,
        negated: bool,
    },
    /// `column [NOT] IN (subquery)`.
    InSubquery {
        table: &'static str,
        column: &'static str,
        subquery: CompiledSql,
        negated: bool,
    },
    /// A comparison between two columns, used for join `ON` clauses.
    ColumnCmp {
        left_table: &'static str,
        left_col: &'static str,
        op: CmpOp,
        right_table: &'static str,
        right_col: &'static str,
    },
    /// Correlated `EXISTS (SELECT 1 FROM child_table WHERE child_fk = parent_pk AND filter)`.
    Exists {
        child_table: &'static str,
        child_col: &'static str,
        parent_table: &'static str,
        parent_col: &'static str,
        filter: Box<FilterNode>,
        negated: bool,
    },
    /// Correlated `[NOT] EXISTS (<subquery>)`.
    ExistsSubquery {
        subquery: CompiledSql,
        negated: bool,
    },
    And(Vec<FilterNode>),
    Or(Vec<FilterNode>),
    Not(Box<FilterNode>),
    /// A raw SQL fragment with bound parameters.
    Raw(RawFragment),
    /// A JSON column operation.
    Json {
        /// The SQL table name.
        table: &'static str,
        /// The SQL column name.
        column: &'static str,
        /// The JSON path inside the column.
        path: JsonPath,
        /// `true` for text extraction, `false` for JSON.
        text: bool,
        /// The JSON-specific operator.
        op: JsonFilterOp,
        /// The bound value.
        value: Value,
    },
    /// A scalar/enum array column operation.
    Array {
        /// The SQL table name.
        table: &'static str,
        /// The SQL column name.
        column: &'static str,
        /// The array-specific operator.
        op: ArrayFilterOp,
        /// The bound element values.
        values: Vec<Value>,
    },
    /// A full-text search match operation.
    FullTextMatch {
        /// The SQL table name.
        table: &'static str,
        /// The SQL column name.
        column: &'static str,
        /// The text query or terms to match.
        query: String,
    },
    /// A spatial / geospatial column operation.
    Spatial {
        /// The SQL table name.
        table: &'static str,
        /// The SQL column name.
        column: &'static str,
        /// The spatial operator.
        op: SpatialOp,
        /// The geometry value (WKT formatted).
        geometry: String,
        /// Optional distance in meters (e.g. for `WithinRadius`).
        distance: Option<f64>,
    },
}

/// Spatial / PostGIS filter operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpatialOp {
    /// Distance between geometries is within radius (`ST_DWithin`).
    WithinRadius,
    /// Geometries spatially intersect (`ST_Intersects`).
    Intersects,
    /// Geometry A completely contains geometry B (`ST_Contains`).
    Contains,
    /// Geometry A is completely within geometry B (`ST_Within`).
    Within,
}

/// JSON-specific filter operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JsonFilterOp {
    /// A scalar comparison (`=`, `<>`, `>`, ...).
    Cmp(CmpOp),
    /// JSON containment (`@>`).
    Contains,
    /// Top-level or nested key existence (`?`).
    HasKey,
}

/// Array-specific filter operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum ArrayFilterOp {
    /// The column contains a specific single element (`= ANY(column)` / `JSON_CONTAINS`).
    Has,
    /// The column contains all of the supplied values (`@>` / `JSON_CONTAINS`).
    Contains,
    /// The column is contained by the supplied set (`<@` / `JSON_CONTAINS` reversed).
    ContainedBy,
    /// The column and the supplied set share at least one element (`&&` / `JSON_OVERLAPS`).
    Overlaps,
    /// The array is empty (`cardinality(col) = 0` / `JSON_LENGTH(col) = 0` or NULL).
    IsEmpty,
    /// The array is non-empty (`cardinality(col) > 0` / `JSON_LENGTH(col) > 0`).
    IsNotEmpty,
}

/// Comparison operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
pub enum CmpOp {
    Eq,
    Ne,
    Gt,
    Gte,
    Lt,
    Lte,
    Like,
    Ilike,
}

/// Combines a list of filters with `AND`.
///
/// `all([])` is `TRUE`.
pub fn all<M>(filters: impl IntoIterator<Item = Filter<M>>) -> Filter<M> {
    Filter::new(flatten_and(filters.into_iter().map(|f| f.node).collect()))
}

/// Combines a list of filters with `OR`.
///
/// `any([])` is `FALSE`.
pub fn any<M>(filters: impl IntoIterator<Item = Filter<M>>) -> Filter<M> {
    Filter::new(flatten_or(filters.into_iter().map(|f| f.node).collect()))
}

fn flatten_and(nodes: Vec<FilterNode>) -> FilterNode {
    if nodes.is_empty() {
        return FilterNode::And(Vec::new());
    }
    let mut out = Vec::with_capacity(nodes.len());
    for node in nodes {
        match node {
            FilterNode::And(children) => out.extend(children),
            other => out.push(other),
        }
    }
    FilterNode::And(out)
}

fn flatten_or(nodes: Vec<FilterNode>) -> FilterNode {
    if nodes.is_empty() {
        return FilterNode::Or(Vec::new());
    }
    let mut out = Vec::with_capacity(nodes.len());
    for node in nodes {
        match node {
            FilterNode::Or(children) => out.extend(children),
            other => out.push(other),
        }
    }
    FilterNode::Or(out)
}