rorm 0.10.0

A asynchronous declarative ORM written in pure rust.
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
//! [`FieldProxy`] and some utility functions which are used by rorm's various macros

use std::marker::PhantomData;
use std::mem::ManuallyDrop;

#[cfg(feature = "postgres-only")]
use ipnetwork::IpNetwork;
use rorm_db::sql::aggregation::SelectAggregator;

#[cfg(feature = "postgres-only")]
use crate::conditions::{Binary, BinaryOperator, Value};
use crate::conditions::{Column, Unary, UnaryOperator};
use crate::crud::selector::{AggregatedColumn, PathedSelector, Selector};
#[cfg(feature = "postgres-only")]
use crate::fields::traits::FieldILike;
use crate::fields::traits::{
    FieldAvg, FieldColumns, FieldCount, FieldEq, FieldIn, FieldLike, FieldMax, FieldMin, FieldOrd,
    FieldRegexp, FieldSum,
};
use crate::fields::utils::column_name::ColumnName;
use crate::internal::field::{Field, SingleColumnField};
use crate::internal::relation_path::{Path, PathField};
use crate::sealed;

/// This unit struct acts as a proxy exposing a model's field (the field's declaration not its value)
/// as a value to pass around and call methods on.
///
/// It also constructs JOIN paths by following relations between models.
///
/// TODO: more docs
pub struct FieldProxy<T>(PhantomData<ManuallyDrop<T>>);

macro_rules! FieldType {
    ($I:ident) => {
        <<$I as FieldProxyImpl>::Field as Field>::Type
    };
}

impl<F, P, I> FieldProxy<I>
where
    F: Field + PathField<<F as Field>::Type>,
    P: Path<Current = <F::ParentField as Field>::Model>,
    I: FieldProxyImpl<Field = F, Path = P>,
{
    /// Query the model this field points to using `selector`
    pub fn query_as<S>(self, selector: S) -> PathedSelector<S, <I::Path as Path>::Step<I::Field>>
    where
        S: Selector<Model = <F::ChildField as Field>::Model>,
    {
        PathedSelector {
            selector,
            path: Default::default(),
        }
    }
}

impl<I: FieldProxyImpl> FieldProxy<I> {
    /// Checks if the column contains `None`
    pub fn is_none<T>(self) -> Unary<Column<I>>
    where
        // This would have to be a trait for multi-column fields
        I::Field: SingleColumnField<Type = Option<T>>,
    {
        Unary {
            operator: UnaryOperator::IsNull,
            fst_arg: Column(self),
        }
    }

    /// Checks if the column contains `Some`
    pub fn is_some<T>(self) -> Unary<Column<I>>
    where
        // This would have to be a trait for multi-column fields
        I::Field: SingleColumnField<Type = Option<T>>,
    {
        Unary {
            operator: UnaryOperator::IsNotNull,
            fst_arg: Column(self),
        }
    }

    /// Compare the field to another value using `==`
    pub fn equals<'rhs, Rhs, Any>(
        self,
        rhs: Rhs,
    ) -> <FieldType!(I) as FieldEq<'rhs, Rhs, Any>>::EqCond<I>
    where
        FieldType!(I): FieldEq<'rhs, Rhs, Any>,
    {
        <FieldType!(I)>::field_equals(self, rhs)
    }

    /// Compare the field to another value using `!=`
    pub fn not_equals<'rhs, Rhs, Any>(
        self,
        rhs: Rhs,
    ) -> <FieldType!(I) as FieldEq<'rhs, Rhs, Any>>::NeCond<I>
    where
        FieldType!(I): FieldEq<'rhs, Rhs, Any>,
    {
        <FieldType!(I)>::field_not_equals(self, rhs)
    }

    /// Check if the field's value is in a given list of values
    pub fn r#in<'rhs, Rhs, Any>(
        self,
        rhs: Rhs,
    ) -> <FieldType!(I) as FieldIn<'rhs, Rhs, Any>>::InCond<I>
    where
        FieldType!(I): FieldIn<'rhs, Rhs, Any>,
    {
        <FieldType!(I)>::field_in(self, rhs)
    }

    /// Check if the field's value is not in a given list of values
    pub fn not_in<'rhs, Rhs, Any>(
        self,
        rhs: Rhs,
    ) -> <FieldType!(I) as FieldIn<'rhs, Rhs, Any>>::NiCond<I>
    where
        FieldType!(I): FieldIn<'rhs, Rhs, Any>,
    {
        <FieldType!(I)>::field_not_in(self, rhs)
    }

    /// Compare the field to another value using `<`
    pub fn less_than<'rhs, Rhs, Any>(
        self,
        rhs: Rhs,
    ) -> <FieldType!(I) as FieldOrd<'rhs, Rhs, Any>>::LtCond<I>
    where
        FieldType!(I): FieldOrd<'rhs, Rhs, Any>,
    {
        <FieldType!(I)>::field_less_than(self, rhs)
    }

    /// Compare the field to another value using `<=`
    pub fn less_equals<'rhs, Rhs, Any>(
        self,
        rhs: Rhs,
    ) -> <FieldType!(I) as FieldOrd<'rhs, Rhs, Any>>::LeCond<I>
    where
        FieldType!(I): FieldOrd<'rhs, Rhs, Any>,
    {
        <FieldType!(I)>::field_less_equals(self, rhs)
    }

    /// Compare the field to another value using `<`
    pub fn greater_than<'rhs, Rhs, Any>(
        self,
        rhs: Rhs,
    ) -> <FieldType!(I) as FieldOrd<'rhs, Rhs, Any>>::GtCond<I>
    where
        FieldType!(I): FieldOrd<'rhs, Rhs, Any>,
    {
        <FieldType!(I)>::field_greater_than(self, rhs)
    }

    /// Compare the field to another value using `>=`
    pub fn greater_equals<'rhs, Rhs, Any>(
        self,
        rhs: Rhs,
    ) -> <FieldType!(I) as FieldOrd<'rhs, Rhs, Any>>::GeCond<I>
    where
        FieldType!(I): FieldOrd<'rhs, Rhs, Any>,
    {
        <FieldType!(I)>::field_greater_equals(self, rhs)
    }

    /// Compare the field to another value using `LIKE`
    pub fn like<'rhs, Rhs, Any>(
        self,
        rhs: Rhs,
    ) -> <FieldType!(I) as FieldLike<'rhs, Rhs, Any>>::LiCond<I>
    where
        FieldType!(I): FieldLike<'rhs, Rhs, Any>,
    {
        <FieldType!(I)>::field_like(self, rhs)
    }

    /// Compare the field to another value using `NOT LIKE`
    pub fn not_like<'rhs, Rhs, Any>(
        self,
        rhs: Rhs,
    ) -> <FieldType!(I) as FieldLike<'rhs, Rhs, Any>>::NlCond<I>
    where
        FieldType!(I): FieldLike<'rhs, Rhs, Any>,
    {
        <FieldType!(I)>::field_not_like(self, rhs)
    }

    /// Uses `LIKE` to check whether the field contains the string `rhs`
    pub fn contains<'rhs, Any>(
        self,
        rhs: &str,
    ) -> <FieldType!(I) as FieldLike<'rhs, String, Any>>::LiCond<I>
    where
        FieldType!(I): FieldLike<'rhs, String, Any>,
    {
        self.like(format!("%{}%", escape_like(rhs)))
    }

    /// Uses `LIKE` to check whether the field starts with the string `rhs`
    pub fn starts_with<'rhs, Any>(
        self,
        rhs: &str,
    ) -> <FieldType!(I) as FieldLike<'rhs, String, Any>>::LiCond<I>
    where
        FieldType!(I): FieldLike<'rhs, String, Any>,
    {
        self.like(format!("{}%", escape_like(rhs)))
    }

    /// Uses `LIKE` to check whether the field ends with the string `rhs`
    pub fn ends_with<'rhs, Any>(
        self,
        rhs: &str,
    ) -> <FieldType!(I) as FieldLike<'rhs, String, Any>>::LiCond<I>
    where
        FieldType!(I): FieldLike<'rhs, String, Any>,
    {
        self.like(format!("%{}", escape_like(rhs)))
    }

    /// Compare the field to another value using `>=`
    pub fn regexp<'rhs, Rhs: 'rhs, Any>(
        self,
        rhs: Rhs,
    ) -> <FieldType!(I) as FieldRegexp<'rhs, Rhs, Any>>::ReCond<I>
    where
        FieldType!(I): FieldRegexp<'rhs, Rhs, Any>,
    {
        <FieldType!(I)>::field_regexp(self, rhs)
    }

    /// Compare the field to another value using `>=`
    pub fn not_regexp<'rhs, Rhs: 'rhs, Any>(
        self,
        rhs: Rhs,
    ) -> <FieldType!(I) as FieldRegexp<'rhs, Rhs, Any>>::NrCond<I>
    where
        FieldType!(I): FieldRegexp<'rhs, Rhs, Any>,
    {
        <FieldType!(I)>::field_not_regexp(self, rhs)
    }

    /// Returns the count of the number of times that the column is not null.
    pub fn count(self) -> AggregatedColumn<I, i64>
    where
        FieldType!(I): FieldCount,
    {
        AggregatedColumn {
            sql: SelectAggregator::Count,
            alias: "count",
            field: self,
            result: PhantomData,
        }
    }

    /// Returns the summary off all non-null values in the group.
    /// If there are only null values in the group, this function will return null.
    pub fn sum(self) -> AggregatedColumn<I, <FieldType!(I) as FieldSum>::Result>
    where
        FieldType!(I): FieldSum,
    {
        AggregatedColumn {
            sql: SelectAggregator::Sum,
            alias: "sum",
            field: self,
            result: PhantomData,
        }
    }

    /// Returns the average value of all non-null values.
    /// The result of avg is a floating point value, except all input values are null, than the
    /// result will also be null.
    pub fn avg(self) -> AggregatedColumn<I, Option<f64>>
    where
        FieldType!(I): FieldAvg,
    {
        AggregatedColumn {
            sql: SelectAggregator::Avg,
            alias: "avg",
            field: self,
            result: PhantomData,
        }
    }

    /// Returns the maximum value of all values in the group.
    /// If there are only null values in the group, this function will return null.
    pub fn max(self) -> AggregatedColumn<I, <FieldType!(I) as FieldMax>::Result>
    where
        FieldType!(I): FieldMax,
    {
        AggregatedColumn {
            sql: SelectAggregator::Max,
            alias: "max",
            field: self,
            result: PhantomData,
        }
    }

    /// Returns the minimum value of all values in the group.
    /// If there are only null values in the group, this function will return null.
    pub fn min(self) -> AggregatedColumn<I, <FieldType!(I) as FieldMin>::Result>
    where
        FieldType!(I): FieldMin,
    {
        AggregatedColumn {
            sql: SelectAggregator::Min,
            alias: "min",
            field: self,
            result: PhantomData,
        }
    }
}

#[cfg(feature = "postgres-only")]
impl<I: FieldProxyImpl> FieldProxy<I> {
    /// Compare the field to another value using `ILIKE`
    pub fn like_ignore_case<'rhs, Rhs: 'rhs, Any>(
        self,
        rhs: Rhs,
    ) -> <FieldType!(I) as FieldILike<'rhs, Rhs, Any>>::IliCond<I>
    where
        FieldType!(I): FieldILike<'rhs, Rhs, Any>,
    {
        <FieldType!(I)>::field_ilike(self, rhs)
    }

    /// Compare the field to another value using `NOT ILIKE`
    pub fn not_like_ignore_case<'rhs, Rhs: 'rhs, Any>(
        self,
        rhs: Rhs,
    ) -> <FieldType!(I) as FieldILike<'rhs, Rhs, Any>>::NilCond<I>
    where
        FieldType!(I): FieldILike<'rhs, Rhs, Any>,
    {
        <FieldType!(I)>::field_not_ilike(self, rhs)
    }

    /// Uses `ILIKE` to check whether the field contains the string `rhs` while ignoring case
    pub fn contains_ignore_case<'rhs, Any>(
        self,
        rhs: &str,
    ) -> <FieldType!(I) as FieldILike<'rhs, String, Any>>::IliCond<I>
    where
        FieldType!(I): FieldILike<'rhs, String, Any>,
    {
        self.like_ignore_case(format!("%{}%", escape_like(rhs)))
    }

    /// Uses `ILIKE` to check whether the field starts with the string `rhs` while ignoring case
    pub fn starts_with_ignore_case<'rhs, Any>(
        self,
        rhs: &str,
    ) -> <FieldType!(I) as FieldILike<'rhs, String, Any>>::IliCond<I>
    where
        FieldType!(I): FieldILike<'rhs, String, Any>,
    {
        self.like_ignore_case(format!("{}%", escape_like(rhs)))
    }

    /// Uses `ILIKE` to check whether the field ends with the string `rhs` while ignoring case
    pub fn ends_with_ignore_case<'rhs, Any>(
        self,
        rhs: &str,
    ) -> <FieldType!(I) as FieldILike<'rhs, String, Any>>::IliCond<I>
    where
        FieldType!(I): FieldILike<'rhs, String, Any>,
    {
        self.like_ignore_case(format!("%{}", escape_like(rhs)))
    }

    /// Uses `ILIKE` to check whether the field is equal to the string `rhs` while ignoring case
    pub fn equals_ignore_case<'rhs, Any>(
        self,
        rhs: &str,
    ) -> <FieldType!(I) as FieldILike<'rhs, String, Any>>::IliCond<I>
    where
        FieldType!(I): FieldILike<'rhs, String, Any>,
    {
        self.like_ignore_case(escape_like(rhs))
    }
}

#[cfg(feature = "postgres-only")]
impl<'a, I> FieldProxy<I>
where
    I: FieldProxyImpl,
    I::Field: Field<Type = IpNetwork>,
{
    /// Compare the field to another value using postgresql's `<<`
    pub fn net_contained_in(self, rhs: IpNetwork) -> Binary<Column<I>, Value<'a>> {
        Binary {
            operator: BinaryOperator::Contained,
            fst_arg: Column(self),
            snd_arg: Value::IpNetwork(rhs),
        }
    }

    /// Compare the field to another value using postgresql's `<<=`
    pub fn net_contained_in_or_equals(self, rhs: IpNetwork) -> Binary<Column<I>, Value<'a>> {
        Binary {
            operator: BinaryOperator::ContainedOrEquals,
            fst_arg: Column(self),
            snd_arg: Value::IpNetwork(rhs),
        }
    }

    /// Compare the field to another value using postgresql's `>>`
    pub fn net_contains(self, rhs: IpNetwork) -> Binary<Column<I>, Value<'a>> {
        Binary {
            operator: BinaryOperator::Contains,
            fst_arg: Column(self),
            snd_arg: Value::IpNetwork(rhs),
        }
    }

    /// Compare the field to another value using postgresql's `>>=`
    pub fn net_contains_or_equals(self, rhs: IpNetwork) -> Binary<Column<I>, Value<'a>> {
        Binary {
            operator: BinaryOperator::ContainsOrEquals,
            fst_arg: Column(self),
            snd_arg: Value::IpNetwork(rhs),
        }
    }
}

// SAFETY:
// struct contains no data
unsafe impl<T> Send for FieldProxy<T> {}
unsafe impl<T> Sync for FieldProxy<T> {}

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

/// Implementation detail of [`FieldProxy`], `FieldProxy`'s generic must implement this trait.
///
/// This trait is not relevant for the average rorm user.
pub trait FieldProxyImpl: 'static {
    sealed!(trait);

    /// Field which is proxied
    type Field: Field;

    /// Path the field is accessed through
    type Path: Path;
}

impl<F, P> FieldProxyImpl for (F, P)
where
    F: Field,
    P: Path,
{
    sealed!(impl);

    type Field = F;
    type Path = P;
}

/// Construct a new `FieldProxy`
///
/// *Not relevant for the average rorm user*
///
/// This function is used by the `#[derive(Model)]` macro to populate the Fields struct.
pub const fn new<I: FieldProxyImpl>() -> FieldProxy<I> {
    FieldProxy(PhantomData)
}

/// Get a [`Field`]'s `INDEX` from a `FieldProxy`
///
/// *Not relevant for the average rorm user*
///
/// This function is used by the [`get_field`](crate::get_field) and [`field`](crate::field) macros.
pub const fn index<I: FieldProxyImpl>(_: fn() -> FieldProxy<I>) -> usize {
    <I::Field as Field>::INDEX
}

/// Get the names of the columns which store the field
///
/// *Not relevant for the average rorm user*
///
/// This function is used by the `#[derive(Patch)]` macro to gather a list of all columns.
pub const fn columns<T: FieldProxyImpl>(
    _: fn() -> FieldProxy<T>,
) -> FieldColumns<<T::Field as Field>::Type, ColumnName> {
    <T::Field as Field>::EFFECTIVE_NAMES
}

/// Escape the special character from an argument to `LIKE`
fn escape_like(string: &str) -> String {
    string
        .replace('\\', r"\\")
        .replace('%', r"\%")
        .replace('_', r"\_")
}