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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! Typed column tokens.

use std::marker::PhantomData;
use std::sync::Arc;

use crate::filter::{ArrayFilterOp, CmpOp, Filter, FilterNode, JsonFilterOp, SpatialOp, Subquery};
use crate::join::JoinOn;
use crate::json::{JsonColumn, JsonPath, JsonPathSegment, JsonSet};
use crate::order::OrderBy;
use crate::spatial::{Point, Polygon};
use crate::value::{Encodable, Ordered, Value};

/// A typed token for a physical column.
///
/// The `M` phantom type prevents mixing columns from different models into one
/// query. The `T` phantom type is the Rust type stored in the column, which is
/// used to type-check filter values at compile time.
pub struct Column<M, T> {
    /// The SQL table name.
    pub table: &'static str,
    /// The SQL column name.
    pub column: &'static str,
    _marker: PhantomData<fn() -> (M, T)>,
}

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

impl<M, T> Copy for Column<M, T> {}
impl<M, T> Clone for Column<M, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<M, T> PartialEq for Column<M, T> {
    fn eq(&self, other: &Self) -> bool {
        self.table == other.table && self.column == other.column
    }
}

impl<M, T> Eq for Column<M, T> {}

impl<M, T> Column<M, T> {
    /// Creates a new column token.
    #[must_use]
    pub const fn new(table: &'static str, column: &'static str) -> Self {
        Self {
            table,
            column,
            _marker: PhantomData,
        }
    }

    /// Reference the same column in a join condition on the right side of another model.
    pub fn on<J>(self, other: Column<J, T>) -> JoinOn {
        JoinOn::new(self, other)
    }

    /// Use this column token with a different table name, typically a self-join alias.
    ///
    /// The model marker `M` is preserved, so the resulting column still has the
    /// same Rust type; only the SQL qualifier changes. This makes self-joins
    /// type-safe without needing a separate alias type.
    #[must_use]
    pub const fn aliased(self, table: &'static str) -> Self {
        Self {
            table,
            column: self.column,
            _marker: PhantomData,
        }
    }

    /// `column IN (subquery)`.
    pub fn in_subquery<Q: Into<Subquery<T>>>(self, subquery: Q) -> Filter<M> {
        let subquery = subquery.into().compiled;
        Filter::new(FilterNode::InSubquery {
            table: self.table,
            column: self.column,
            subquery,
            negated: false,
        })
    }

    /// `column NOT IN (subquery)`.
    pub fn not_in_subquery<Q: Into<Subquery<T>>>(self, subquery: Q) -> Filter<M> {
        let subquery = subquery.into().compiled;
        Filter::new(FilterNode::InSubquery {
            table: self.table,
            column: self.column,
            subquery,
            negated: true,
        })
    }

    /// Correlate this column to an outer query's column (`inner_col = outer_col`).
    #[must_use]
    pub fn correlated_to<J>(self, other: Column<J, T>) -> Filter<M> {
        Filter::new(FilterNode::ColumnCmp {
            left_table: self.table,
            left_col: self.column,
            op: CmpOp::Eq,
            right_table: other.table,
            right_col: other.column,
        })
    }
}

impl<M, T: Encodable> Column<M, T> {
    /// `column = value`.
    pub fn eq<V: Into<T>>(self, value: V) -> Filter<M> {
        let value = value.into().to_value();
        Filter::new(FilterNode::Cmp {
            table: self.table,
            column: self.column,
            op: CmpOp::Eq,
            value,
        })
    }

    /// `column <> value`.
    pub fn ne<V: Into<T>>(self, value: V) -> Filter<M> {
        let value = value.into().to_value();
        Filter::new(FilterNode::Cmp {
            table: self.table,
            column: self.column,
            op: CmpOp::Ne,
            value,
        })
    }

    /// `column IN (...)`.
    pub fn in_<V: Into<T>>(self, values: Vec<V>) -> Filter<M> {
        Filter::new(FilterNode::In {
            table: self.table,
            column: self.column,
            values: values.into_iter().map(|v| v.into().to_value()).collect(),
            negated: false,
        })
    }

    /// `column IN (values)`.
    pub fn in_set(self, values: impl IntoIterator<Item = impl Into<T>>) -> Filter<M> {
        Filter::new(FilterNode::In {
            table: self.table,
            column: self.column,
            values: values.into_iter().map(|v| v.into().to_value()).collect(),
            negated: false,
        })
    }

    /// `column NOT IN (values)`.
    pub fn not_in_set(self, values: impl IntoIterator<Item = impl Into<T>>) -> Filter<M> {
        Filter::new(FilterNode::In {
            table: self.table,
            column: self.column,
            values: values.into_iter().map(|v| v.into().to_value()).collect(),
            negated: true,
        })
    }

    /// `ASC`.
    pub fn asc(self) -> OrderBy<M> {
        OrderBy::new(self.table, self.column, false)
    }

    /// `DESC`.
    pub fn desc(self) -> OrderBy<M> {
        OrderBy::new(self.table, self.column, true)
    }
}

impl<M, T: Ordered> Column<M, T> {
    /// `column > value`.
    pub fn gt<V: Into<T>>(self, value: V) -> Filter<M> {
        let value = value.into().to_value();
        Filter::new(FilterNode::Cmp {
            table: self.table,
            column: self.column,
            op: CmpOp::Gt,
            value,
        })
    }

    /// `column >= value`.
    pub fn gte<V: Into<T>>(self, value: V) -> Filter<M> {
        let value = value.into().to_value();
        Filter::new(FilterNode::Cmp {
            table: self.table,
            column: self.column,
            op: CmpOp::Gte,
            value,
        })
    }

    /// `column < value`.
    pub fn lt<V: Into<T>>(self, value: V) -> Filter<M> {
        let value = value.into().to_value();
        Filter::new(FilterNode::Cmp {
            table: self.table,
            column: self.column,
            op: CmpOp::Lt,
            value,
        })
    }

    /// `column <= value`.
    pub fn lte<V: Into<T>>(self, value: V) -> Filter<M> {
        let value = value.into().to_value();
        Filter::new(FilterNode::Cmp {
            table: self.table,
            column: self.column,
            op: CmpOp::Lte,
            value,
        })
    }

    /// `column BETWEEN lo AND hi`.
    pub fn between<Lo: Into<T>, Hi: Into<T>>(self, lo: Lo, hi: Hi) -> Filter<M> {
        Filter::new(FilterNode::Between {
            table: self.table,
            column: self.column,
            lo: lo.into().to_value(),
            hi: hi.into().to_value(),
        })
    }
}

impl<M> Column<M, String> {
    /// `column LIKE '%pattern%'`.
    pub fn contains(self, pattern: &str) -> Filter<M> {
        Filter::new(FilterNode::Cmp {
            table: self.table,
            column: self.column,
            op: CmpOp::Like,
            value: Value::Str(format!("%{pattern}%").into()),
        })
    }

    /// `column LIKE 'pattern%'`.
    pub fn starts_with(self, prefix: &str) -> Filter<M> {
        Filter::new(FilterNode::Cmp {
            table: self.table,
            column: self.column,
            op: CmpOp::Like,
            value: Value::Str(format!("{prefix}%").into()),
        })
    }

    /// `column LIKE '%pattern'`.
    pub fn ends_with(self, suffix: &str) -> Filter<M> {
        Filter::new(FilterNode::Cmp {
            table: self.table,
            column: self.column,
            op: CmpOp::Like,
            value: Value::Str(format!("%{suffix}").into()),
        })
    }

    /// Case-insensitive pattern match (`ILIKE` on Postgres, `LIKE` on SQLite).
    pub fn ilike(self, pattern: &str) -> Filter<M> {
        Filter::new(FilterNode::Cmp {
            table: self.table,
            column: self.column,
            op: CmpOp::Ilike,
            value: Value::Str(format!("%{pattern}%").into()),
        })
    }

    /// Full-text search match (`to_tsvector @@ plainto_tsquery` on Postgres, `MATCH...AGAINST` on MySQL, `MATCH` on SQLite).
    pub fn matches(self, query: impl Into<String>) -> Filter<M> {
        Filter::new(FilterNode::FullTextMatch {
            table: self.table,
            column: self.column,
            query: query.into(),
        })
    }
}

impl<M> Column<M, Option<String>> {
    /// Full-text search match for optional string column.
    pub fn matches(self, query: impl Into<String>) -> Filter<M> {
        Filter::new(FilterNode::FullTextMatch {
            table: self.table,
            column: self.column,
            query: query.into(),
        })
    }
}

impl<M> Column<M, Point> {
    /// Geospatial radius filter (`ST_DWithin(column, point, distance_in_meters)`).
    pub fn within_radius(self, point: &Point, distance_meters: f64) -> Filter<M> {
        Filter::new(FilterNode::Spatial {
            table: self.table,
            column: self.column,
            op: SpatialOp::WithinRadius,
            geometry: point.to_wkt(),
            distance: Some(distance_meters),
        })
    }

    /// Spatial distance expression ordering ascending (`ST_Distance(column, point) ASC`).
    pub fn distance_asc(self, point: &Point) -> OrderBy<M> {
        OrderBy::spatial_distance(self.table, self.column, point.to_wkt(), false)
    }

    /// Spatial distance expression ordering descending (`ST_Distance(column, point) DESC`).
    pub fn distance_desc(self, point: &Point) -> OrderBy<M> {
        OrderBy::spatial_distance(self.table, self.column, point.to_wkt(), true)
    }

    /// Geospatial intersection check against a polygon (`ST_Intersects`).
    pub fn intersects(self, polygon: &Polygon) -> Filter<M> {
        Filter::new(FilterNode::Spatial {
            table: self.table,
            column: self.column,
            op: SpatialOp::Intersects,
            geometry: polygon.to_wkt(),
            distance: None,
        })
    }

    /// Geospatial containment check (`ST_Within(point, polygon)`).
    pub fn within_polygon(self, polygon: &Polygon) -> Filter<M> {
        Filter::new(FilterNode::Spatial {
            table: self.table,
            column: self.column,
            op: SpatialOp::Within,
            geometry: polygon.to_wkt(),
            distance: None,
        })
    }
}

impl<M> Column<M, Option<Point>> {
    /// Geospatial radius filter for optional point column.
    pub fn within_radius(self, point: &Point, distance_meters: f64) -> Filter<M> {
        Filter::new(FilterNode::Spatial {
            table: self.table,
            column: self.column,
            op: SpatialOp::WithinRadius,
            geometry: point.to_wkt(),
            distance: Some(distance_meters),
        })
    }

    /// Spatial distance expression ordering ascending for optional point.
    pub fn distance_asc(self, point: &Point) -> OrderBy<M> {
        OrderBy::spatial_distance(self.table, self.column, point.to_wkt(), false)
    }

    /// Spatial distance expression ordering descending for optional point.
    pub fn distance_desc(self, point: &Point) -> OrderBy<M> {
        OrderBy::spatial_distance(self.table, self.column, point.to_wkt(), true)
    }

    /// Geospatial intersection check for optional point.
    pub fn intersects(self, polygon: &Polygon) -> Filter<M> {
        Filter::new(FilterNode::Spatial {
            table: self.table,
            column: self.column,
            op: SpatialOp::Intersects,
            geometry: polygon.to_wkt(),
            distance: None,
        })
    }
}

impl<M> Column<M, Polygon> {
    /// Geospatial intersection check (`ST_Intersects`).
    pub fn intersects(self, polygon: &Polygon) -> Filter<M> {
        Filter::new(FilterNode::Spatial {
            table: self.table,
            column: self.column,
            op: SpatialOp::Intersects,
            geometry: polygon.to_wkt(),
            distance: None,
        })
    }

    /// Geospatial containment check (`ST_Contains(column, point)`).
    pub fn contains_point(self, point: &Point) -> Filter<M> {
        Filter::new(FilterNode::Spatial {
            table: self.table,
            column: self.column,
            op: SpatialOp::Contains,
            geometry: point.to_wkt(),
            distance: None,
        })
    }

    /// Geospatial containment check (`ST_Contains(column, polygon)`).
    pub fn contains(self, polygon: &Polygon) -> Filter<M> {
        Filter::new(FilterNode::Spatial {
            table: self.table,
            column: self.column,
            op: SpatialOp::Contains,
            geometry: polygon.to_wkt(),
            distance: None,
        })
    }
}

impl<M> Column<M, Option<Polygon>> {
    /// Geospatial intersection check for optional polygon.
    pub fn intersects(self, polygon: &Polygon) -> Filter<M> {
        Filter::new(FilterNode::Spatial {
            table: self.table,
            column: self.column,
            op: SpatialOp::Intersects,
            geometry: polygon.to_wkt(),
            distance: None,
        })
    }

    /// Geospatial containment check for optional polygon.
    pub fn contains(self, polygon: &Polygon) -> Filter<M> {
        Filter::new(FilterNode::Spatial {
            table: self.table,
            column: self.column,
            op: SpatialOp::Contains,
            geometry: polygon.to_wkt(),
            distance: None,
        })
    }
}

impl<M, T> Column<M, Option<T>> {
    /// `column IS NULL`.
    pub fn is_null(self) -> Filter<M> {
        Filter::new(FilterNode::Null {
            table: self.table,
            column: self.column,
            negated: false,
        })
    }

    /// `column IS NOT NULL`.
    pub fn is_not_null(self) -> Filter<M> {
        Filter::new(FilterNode::Null {
            table: self.table,
            column: self.column,
            negated: true,
        })
    }
}

impl<M> Column<M, serde_json::Value> {
    /// Extract a JSON field by key (`column->'key'` or `column#>'{...}'`).
    #[must_use]
    pub fn get(self, key: &'static str) -> JsonColumn<M, serde_json::Value> {
        JsonColumn {
            table: self.table,
            column: self.column,
            path: JsonPath(vec![JsonPathSegment::Key(key)]),
            text: false,
            _marker: PhantomData,
        }
    }

    /// Extract a JSON field by key as text (`column->>'key'` or `column#>>'{...}'`).
    #[must_use]
    pub fn get_text(self, key: &'static str) -> JsonColumn<M, String> {
        JsonColumn {
            table: self.table,
            column: self.column,
            path: JsonPath(vec![JsonPathSegment::Key(key)]),
            text: true,
            _marker: PhantomData,
        }
    }

    /// Extract a JSON array element by index (`column->[index]` or `column#>'{index}'`).
    #[must_use]
    pub fn at(self, index: usize) -> JsonColumn<M, serde_json::Value> {
        JsonColumn {
            table: self.table,
            column: self.column,
            path: JsonPath(vec![JsonPathSegment::Index(index)]),
            text: false,
            _marker: PhantomData,
        }
    }

    /// `column @> value` (JSON containment).
    pub fn contains(self, value: serde_json::Value) -> Filter<M> {
        Filter::new(FilterNode::Json {
            table: self.table,
            column: self.column,
            path: JsonPath::default(),
            text: false,
            op: JsonFilterOp::Contains,
            value: value.to_value(),
        })
    }

    /// `column ? key` (top-level key existence).
    pub fn has_key(self, key: impl Into<String>) -> Filter<M> {
        Filter::new(FilterNode::Json {
            table: self.table,
            column: self.column,
            path: JsonPath::default(),
            text: false,
            op: JsonFilterOp::HasKey,
            value: Value::Str(Arc::from(key.into())),
        })
    }

    /// Build a JSON set expression for this column and key.
    #[must_use]
    pub fn json_set(self, key: &'static str, value: serde_json::Value) -> JsonSet {
        JsonSet {
            column: self.column,
            path: JsonPath(vec![JsonPathSegment::Key(key)]),
            value: value.to_value(),
        }
    }

    /// Build a JSON set expression for this column and key (Postgres naming).
    #[must_use]
    pub fn jsonb_set(self, key: &'static str, value: serde_json::Value) -> JsonSet {
        self.json_set(key, value)
    }
}

impl<M, T: Encodable> Column<M, Vec<T>> {
    /// `value = ANY(column)` (Postgres) or single element containment.
    pub fn has<V: Into<T>>(self, value: V) -> Filter<M> {
        Filter::new(FilterNode::Array {
            table: self.table,
            column: self.column,
            op: ArrayFilterOp::Has,
            values: vec![value.into().to_value()],
        })
    }

    /// `column @> ARRAY[values]` (Postgres) or JSON array containment.
    pub fn contains<V: Into<T>>(self, values: impl IntoIterator<Item = V>) -> Filter<M> {
        Filter::new(FilterNode::Array {
            table: self.table,
            column: self.column,
            op: ArrayFilterOp::Contains,
            values: values.into_iter().map(|v| v.into().to_value()).collect(),
        })
    }

    /// Alias for [`contains`](Column::contains): column contains all given values.
    pub fn has_every<V: Into<T>>(self, values: impl IntoIterator<Item = V>) -> Filter<M> {
        self.contains(values)
    }

    /// `column <@ ARRAY[values]` (Postgres) or JSON array subset.
    pub fn contained_by<V: Into<T>>(self, values: impl IntoIterator<Item = V>) -> Filter<M> {
        Filter::new(FilterNode::Array {
            table: self.table,
            column: self.column,
            op: ArrayFilterOp::ContainedBy,
            values: values.into_iter().map(|v| v.into().to_value()).collect(),
        })
    }

    /// `column && ARRAY[values]` (Postgres) or JSON array overlap.
    pub fn overlaps<V: Into<T>>(self, values: impl IntoIterator<Item = V>) -> Filter<M> {
        Filter::new(FilterNode::Array {
            table: self.table,
            column: self.column,
            op: ArrayFilterOp::Overlaps,
            values: values.into_iter().map(|v| v.into().to_value()).collect(),
        })
    }

    /// Alias for [`overlaps`](Column::overlaps): column has at least one of the given values.
    pub fn has_some<V: Into<T>>(self, values: impl IntoIterator<Item = V>) -> Filter<M> {
        self.overlaps(values)
    }

    /// Array is empty (`cardinality(col) = 0` on Postgres / `JSON_LENGTH(col) = 0` on SQLite/MySQL).
    pub fn is_empty(self) -> Filter<M> {
        Filter::new(FilterNode::Array {
            table: self.table,
            column: self.column,
            op: ArrayFilterOp::IsEmpty,
            values: Vec::new(),
        })
    }

    /// Array is not empty (`cardinality(col) > 0` on Postgres / `JSON_LENGTH(col) > 0` on SQLite/MySQL).
    pub fn is_not_empty(self) -> Filter<M> {
        Filter::new(FilterNode::Array {
            table: self.table,
            column: self.column,
            op: ArrayFilterOp::IsNotEmpty,
            values: Vec::new(),
        })
    }
}

/// A selection of columns that changes the output type of a
/// [`SelectQuery`](crate::query::SelectQuery).
pub trait Projection<M> {
    /// The Rust type a row of the projection decodes into.
    type Output;

    /// Returns the list of column names to select.
    fn projection(&self) -> Vec<&'static str>;
}

impl<M, T> Projection<M> for Column<M, T> {
    type Output = (T,);

    fn projection(&self) -> Vec<&'static str> {
        vec![self.column]
    }
}

macro_rules! impl_projection_tuples {
    ($($n:tt $T:ident),+) => {
        impl<M, $($T),+> Projection<M> for ($(Column<M, $T>,)+) {
            type Output = ($($T,)+);

            #[allow(clippy::vec_init_then_push)]
            fn projection(&self) -> Vec<&'static str> {
                let mut cols = Vec::new();
                $(
                    cols.push(self.$n.column);
                )+
                cols
            }
        }
    };
}

impl_projection_tuples! { 0 T0 }
impl_projection_tuples! { 0 T0, 1 T1 }
impl_projection_tuples! { 0 T0, 1 T1, 2 T2 }
impl_projection_tuples! { 0 T0, 1 T1, 2 T2, 3 T3 }
impl_projection_tuples! { 0 T0, 1 T1, 2 T2, 3 T3, 4 T4 }
impl_projection_tuples! { 0 T0, 1 T1, 2 T2, 3 T3, 4 T4, 5 T5 }
impl_projection_tuples! { 0 T0, 1 T1, 2 T2, 3 T3, 4 T4, 5 T5, 6 T6 }
impl_projection_tuples! { 0 T0, 1 T1, 2 T2, 3 T3, 4 T4, 5 T5, 6 T6, 7 T7 }