navree-orm 1.2.3

Navree ORM: active-record models, a typed query builder, dirty tracking and pagination on PostgreSQL/TimescaleDB, MySQL and SQLite.
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
//! Running model queries: records, single values, plucks, existence and
//! aggregates, and [`Selectable`].

use std::borrow::Cow;
use std::hash::Hash;

use indexmap::IndexMap;

use crate::attributes::in_model_scope;
use crate::collection::Collection;
use crate::column::{Column, IntoExpr};
use crate::error::{OrmError, Result};
use crate::exec::{Access, Executor, Target};
use crate::hooks::{Hooks, ModelEvent};
use crate::ir::{Aggregate, AggregateFunction, Expr, SelectItem};
use crate::model::{Model, PrimaryKey};
use crate::query::Builder;
use crate::record::Record;
use crate::row::{Row, decode_error};
use crate::value::{Field, FieldError, Value};

/// A column or expression whose values a query can return one by one
/// ([`value`](Builder::value), [`pluck`](Builder::pluck)), with the Rust
/// type they come back as: a typed [`Column<M, T>`] gives `T` (decoded as
/// the field is, casts included); a column name or an [`Expr`] gives a
/// [`Value`].
pub trait Selectable {
    /// The Rust type of the values.
    type Output;

    /// The selected expression.
    fn selected(&self) -> Expr;

    /// Reads the value of result column `column` of `row`.
    fn read(&self, row: &Row, column: &str) -> Result<Self::Output, FieldError>;
}

impl<M, T> Selectable for Column<M, T> {
    type Output = T;

    fn selected(&self) -> Expr {
        self.expr()
    }

    fn read(&self, row: &Row, column: &str) -> Result<T, FieldError> {
        self.decode_as(row, column)
    }
}

impl Selectable for &str {
    type Output = Value;

    fn selected(&self) -> Expr {
        self.into_expr()
    }

    fn read(&self, row: &Row, column: &str) -> Result<Value, FieldError> {
        row.field(column)
    }
}

impl Selectable for String {
    type Output = Value;

    fn selected(&self) -> Expr {
        self.as_str().into_expr()
    }

    fn read(&self, row: &Row, column: &str) -> Result<Value, FieldError> {
        row.field(column)
    }
}

impl Selectable for Expr {
    type Output = Value;

    fn selected(&self) -> Expr {
        self.clone()
    }

    fn read(&self, row: &Row, column: &str) -> Result<Value, FieldError> {
        row.field(column)
    }
}

/// The result column names of selected values (stable, whatever the
/// expression).
const VALUE: &str = "value";
const KEY: &str = "key";

impl Target<'_> {
    /// Records of model `M` read from `rows`, the way a query reads its
    /// own: stored records with the model's columns, the other columns as
    /// [extras](Record::extras), decoded in the model's cast context with
    /// the app's strict modes, and the `Retrieved` hooks run. For rows a
    /// driver got outside a builder (a native MongoDB pipeline, say).
    ///
    /// ```no_run
    /// # use navree_orm::__doc_models::*;
    /// # use navree_orm::{Access, Executor, Row};
    /// # async fn demo(db: Db, rows: Vec<Row>) -> Result<()> {
    /// let target = db.target(Access::Read).await?;
    /// let deals = target.records::<Deal>(&rows).await?;
    /// # Ok(()) }
    /// ```
    pub async fn records<M: Model>(&self, rows: &[Row]) -> Result<Collection<M>> {
        let records = self
            .read_records::<M>(rows, &crate::attributes::extras::ExtraCasts::default())
            .await?;
        Ok(Collection::from(records))
    }

    /// The records of `rows`, with the query-time casts of `extra_casts`
    /// applied to their extras and the `Retrieved` hooks run.
    async fn read_records<M: Model>(
        &self,
        rows: &[Row],
        extra_casts: &crate::attributes::extras::ExtraCasts,
    ) -> Result<Vec<Record<M>>> {
        let ctx = self.context();
        // Rows decode inside the model's cast context (the app's encrypter,
        // ...) with the app's strict modes, and so do the `Retrieved` hooks
        // that may read the records.
        in_model_scope::<M, _, _>(&ctx, async {
            let mut records = Vec::new();
            if !rows.is_empty() {
                let strictness = ctx.strictness().await;
                records = crate::strict::sync_scope(strictness, || {
                    rows.iter()
                        .map(|row| {
                            let mut record = Record::<M>::from_row(row)?;
                            extra_casts.apply(&mut record)?;
                            Ok(record)
                        })
                        .collect::<Result<Vec<_>>>()
                })?;
                let hooks = Hooks::<M>::resolve(&ctx).await?;
                if !hooks.is_empty() {
                    for record in &mut records {
                        hooks.after(ModelEvent::Retrieved, &ctx, record).await?;
                    }
                }
            }
            Ok(records)
        })
        .await
    }
}

impl<M: Model> Builder<M> {
    /// Runs the query on `target` and reads its records (with the strict
    /// modes of the executor's app, running the `Retrieved` hooks), then
    /// loads its eager loads into them (an empty result still checks the
    /// names of the first level).
    pub(crate) async fn fetch(self, target: &Target<'_>) -> Result<Collection<M>> {
        let mut query = self.with_pending_default_counts();
        let eager = query.take_eager();
        let extra_casts = query.extra_casts.clone();
        let ir = crate::workspace::with_target(target, || query.into_ir());
        let rows = target.fetch(&ir).await?;
        let mut records = target.read_records::<M>(&rows, &extra_casts).await?;
        crate::relations::eager::after_fetch(target, &mut records, &eager).await?;
        Ok(Collection::from(records))
    }

    /// The rows of the query with `items` as its select list (global scopes
    /// applied).
    async fn select_rows(self, target: &Target<'_>, items: Vec<SelectItem>) -> Result<Vec<Row>> {
        let builder = crate::workspace::with_target(target, || self.apply_global_scopes());
        let defaults = crate::query::model_columns::<M>(builder.ir.table.qualifier());
        let query = crate::query::reading_values(builder.ir, items, defaults);
        target.fetch(&query).await
    }

    /// The query's records.
    pub async fn get<E: Executor + ?Sized>(self, exec: &E) -> Result<Collection<M>> {
        let target = exec
            .target_routed(crate::query::read_access(&self.ir), self.route())
            .await?;
        self.fetch(&target).await
    }

    /// The first record, if any.
    pub async fn first<E: Executor + ?Sized>(self, exec: &E) -> Result<Option<Record<M>>> {
        Ok(self.limit(1).get(exec).await?.into_vec().into_iter().next())
    }

    /// The first record, or [`OrmError::ModelNotFound`] (a 404 in Navree's
    /// error shape when a handler returns it).
    pub async fn first_or_fail<E: Executor + ?Sized>(self, exec: &E) -> Result<Record<M>> {
        self.first(exec)
            .await?
            .ok_or_else(|| OrmError::not_found(M::meta().name(), Vec::new()))
    }

    /// The only record the query matches: [`OrmError::ModelNotFound`] when
    /// there is none, [`OrmError::MultipleRecordsFound`] when there are
    /// more.
    pub async fn sole<E: Executor + ?Sized>(self, exec: &E) -> Result<Record<M>> {
        self.limit(2).get(exec).await?.sole()
    }

    /// The record with key `key`, if the query matches it.
    pub async fn find<E: Executor + ?Sized>(
        self,
        exec: &E,
        key: impl Into<M::Key>,
    ) -> Result<Option<Record<M>>> {
        self.where_key(key).first(exec).await
    }

    /// The record with key `key`, or [`OrmError::ModelNotFound`] naming the
    /// key (a 404 over HTTP).
    pub async fn find_or_fail<E: Executor + ?Sized>(
        self,
        exec: &E,
        key: impl Into<M::Key>,
    ) -> Result<Record<M>> {
        let key = key.into();
        let text = key.to_key_string();
        self.find(exec, key)
            .await?
            .ok_or_else(|| OrmError::not_found(M::meta().name(), vec![text]))
    }

    /// The records with these keys that the query matches, in the query's
    /// order (missing keys are left out).
    pub async fn find_many<E: Executor + ?Sized>(
        self,
        exec: &E,
        keys: impl IntoIterator<Item = impl Into<M::Key>>,
    ) -> Result<Collection<M>> {
        let keys: Vec<M::Key> = keys.into_iter().map(Into::into).collect();
        if keys.is_empty() {
            return Ok(Collection::new());
        }
        self.where_key_in(keys).get(exec).await
    }

    /// The value of `column` in the first matching row; `None` when no row
    /// matches.
    ///
    /// ```no_run
    /// # use navree_orm::__doc_models::*;
    /// # async fn demo(db: Db, id: Uuid) -> Result<()> {
    /// let title: Option<String> = Deal::query().where_key(id).value(&db, Deal::TITLE).await?;
    /// # Ok(()) }
    /// ```
    pub async fn value<E, C>(self, exec: &E, column: C) -> Result<Option<C::Output>>
    where
        E: Executor + ?Sized,
        C: Selectable,
    {
        let target = exec
            .target_routed(crate::query::read_access(&self.ir), self.route())
            .await?;
        let item = SelectItem {
            expr: column.selected(),
            alias: Some(Cow::Borrowed(VALUE)),
        };
        let rows = self.limit(1).select_rows(&target, vec![item]).await?;
        match rows.first() {
            Some(row) => column.read(row, VALUE).map(Some).map_err(|error| {
                decode_error(M::meta().name(), VALUE, "the selected value".into(), &error)
            }),
            None => Ok(None),
        }
    }

    /// The values of `column` in every matching row, in order.
    ///
    /// ```no_run
    /// # use navree_orm::__doc_models::*;
    /// # async fn demo(db: Db) -> Result<()> {
    /// let titles: Vec<String> = Deal::query().latest().pluck(&db, Deal::TITLE).await?;
    /// # Ok(()) }
    /// ```
    pub async fn pluck<E, C>(self, exec: &E, column: C) -> Result<Vec<C::Output>>
    where
        E: Executor + ?Sized,
        C: Selectable,
    {
        let target = exec
            .target_routed(crate::query::read_access(&self.ir), self.route())
            .await?;
        let item = SelectItem {
            expr: column.selected(),
            alias: Some(Cow::Borrowed(VALUE)),
        };
        let rows = self.select_rows(&target, vec![item]).await?;
        rows.iter()
            .map(|row| {
                column.read(row, VALUE).map_err(|error| {
                    decode_error(M::meta().name(), VALUE, "the selected value".into(), &error)
                })
            })
            .collect()
    }

    /// The values of `column` keyed by the values of `key`, in order (a
    /// later row with the same key replaces an earlier one, keeping its
    /// position).
    ///
    /// ```no_run
    /// # use navree_orm::__doc_models::*;
    /// # async fn demo(db: Db) -> Result<()> {
    /// let titles: IndexMap<Uuid, String> = Deal::query().pluck_keyed(&db, Deal::TITLE, Deal::ID).await?;
    /// # Ok(()) }
    /// ```
    pub async fn pluck_keyed<E, V, K>(
        self,
        exec: &E,
        column: V,
        key: K,
    ) -> Result<IndexMap<K::Output, V::Output>>
    where
        E: Executor + ?Sized,
        V: Selectable,
        K: Selectable,
        K::Output: Hash + Eq,
    {
        let target = exec
            .target_routed(crate::query::read_access(&self.ir), self.route())
            .await?;
        let items = vec![
            SelectItem {
                expr: column.selected(),
                alias: Some(Cow::Borrowed(VALUE)),
            },
            SelectItem {
                expr: key.selected(),
                alias: Some(Cow::Borrowed(KEY)),
            },
        ];
        let rows = self.select_rows(&target, items).await?;
        let mut map = IndexMap::with_capacity(rows.len());
        for row in &rows {
            let value = column.read(row, VALUE).map_err(|error| {
                decode_error(M::meta().name(), VALUE, "the selected value".into(), &error)
            })?;
            let key = key.read(row, KEY).map_err(|error| {
                decode_error(M::meta().name(), KEY, "the selected key".into(), &error)
            })?;
            map.insert(key, value);
        }
        Ok(map)
    }

    /// Whether the query matches any record.
    pub async fn exists<E: Executor + ?Sized>(self, exec: &E) -> Result<bool> {
        let target = exec.target_routed(Access::Read, self.route()).await?;
        let ir = crate::workspace::with_target(&target, || self.into_ir());
        target.exists(&ir).await
    }

    /// Whether the query matches no record.
    pub async fn doesnt_exist<E: Executor + ?Sized>(self, exec: &E) -> Result<bool> {
        Ok(!self.exists(exec).await?)
    }

    /// The number of matching records (of matching groups for a grouped
    /// query).
    pub async fn count<E: Executor + ?Sized>(self, exec: &E) -> Result<u64> {
        let target = exec.target_routed(Access::Read, self.route()).await?;
        self.count_on(&target).await
    }

    /// [`count`](Self::count) on `target`.
    pub(crate) async fn count_on(self, target: &Target<'_>) -> Result<u64> {
        self.aggregate_on::<u64>(target, AggregateFunction::Count, None, false)
            .await
            .map(Option::unwrap_or_default)
    }

    /// The number of matching records where `column` is not NULL.
    pub async fn count_column(
        self,
        exec: &(impl Executor + ?Sized),
        column: impl IntoExpr,
    ) -> Result<u64> {
        self.aggregate::<u64>(
            exec,
            AggregateFunction::Count,
            Some(column.into_expr()),
            false,
        )
        .await
        .map(Option::unwrap_or_default)
    }

    /// The number of distinct non-NULL values of `column`.
    pub async fn count_distinct(
        self,
        exec: &(impl Executor + ?Sized),
        column: impl IntoExpr,
    ) -> Result<u64> {
        self.aggregate::<u64>(
            exec,
            AggregateFunction::Count,
            Some(column.into_expr()),
            true,
        )
        .await
        .map(Option::unwrap_or_default)
    }

    /// The sum of `column` over the matching records (zero when none match).
    ///
    /// ```no_run
    /// # use navree_orm::__doc_models::*;
    /// # async fn demo(db: Db) -> Result<()> {
    /// let pipeline: i64 = Deal::query().where_(Deal::STAGE.eq(Stage::Open)).sum(&db, Deal::AMOUNT_CENTS).await?;
    /// # Ok(()) }
    /// ```
    pub async fn sum<T: Field + Default>(
        self,
        exec: &(impl Executor + ?Sized),
        column: impl IntoExpr,
    ) -> Result<T> {
        self.aggregate::<T>(
            exec,
            AggregateFunction::Sum,
            Some(column.into_expr()),
            false,
        )
        .await
        .map(Option::unwrap_or_default)
    }

    /// The average of `column`; `None` when no record matches. Read it as
    /// an `f64` or, exactly, as a [`Decimal`](crate::Decimal).
    pub async fn avg<T: Field>(
        self,
        exec: &(impl Executor + ?Sized),
        column: impl IntoExpr,
    ) -> Result<Option<T>> {
        self.aggregate::<T>(
            exec,
            AggregateFunction::Avg,
            Some(column.into_expr()),
            false,
        )
        .await
    }

    /// The smallest value of `column`; `None` when no record matches.
    pub async fn min<T: Field>(
        self,
        exec: &(impl Executor + ?Sized),
        column: impl IntoExpr,
    ) -> Result<Option<T>> {
        self.aggregate::<T>(
            exec,
            AggregateFunction::Min,
            Some(column.into_expr()),
            false,
        )
        .await
    }

    /// The largest value of `column`; `None` when no record matches.
    pub async fn max<T: Field>(
        self,
        exec: &(impl Executor + ?Sized),
        column: impl IntoExpr,
    ) -> Result<Option<T>> {
        self.aggregate::<T>(
            exec,
            AggregateFunction::Max,
            Some(column.into_expr()),
            false,
        )
        .await
    }

    /// An aggregate of the matching records read as `T`; `None` when the
    /// database returns NULL (no row matched, for everything but counts).
    pub async fn aggregate<T: Field>(
        self,
        exec: &(impl Executor + ?Sized),
        function: AggregateFunction,
        argument: Option<Expr>,
        distinct: bool,
    ) -> Result<Option<T>> {
        let target = exec.target_routed(Access::Read, self.route()).await?;
        self.aggregate_on(&target, function, argument, distinct)
            .await
    }

    async fn aggregate_on<T: Field>(
        self,
        target: &Target<'_>,
        function: AggregateFunction,
        argument: Option<Expr>,
        distinct: bool,
    ) -> Result<Option<T>> {
        let aggregate = Aggregate {
            function,
            arg: argument,
            distinct,
        };
        // Without the default columns: a grouped count selects only the
        // groups (PostgreSQL refuses ungrouped columns).
        let ir = crate::workspace::with_target(target, || self.apply_global_scopes()).ir;
        let value = target.aggregate(&ir, &aggregate).await?;
        <Option<T>>::from_value(value).map_err(|error| {
            decode_error(
                M::meta().name(),
                function.sql_name(),
                Cow::Owned(T::type_name().into_owned()),
                &error,
            )
        })
    }
}