toasty 0.4.0

An async ORM for Rust supporting SQL and NoSQL databases
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
use super::{Delete, Expr, IntoStatement, List, Statement, Value};
use crate::{
    Executor, Result,
    schema::{Load, Model},
};
use std::{fmt, marker::PhantomData};
use toasty_core::stmt::{self, Returning};

/// A typed query that selects records from the database.
///
/// The type parameter `T` is the **returning type** — it encodes what
/// `exec()` produces, not just which model is being queried. A `Query` starts
/// as `Query<List<M>>` (returns `Vec<M>`) and can be narrowed:
///
/// | Type | `exec()` produces | Created by |
/// |---|---|---|
/// | `Query<List<M>>` | `Vec<M>` | [`Query::all`], [`Query::filter`] |
/// | `Query<M>` | `M` (errors if missing) | [`.one()`](Query::one) |
/// | `Query<Option<M>>` | `Option<M>` | [`.first()`](Query::first) |
///
/// # Building queries
///
/// Start with a generated finder (e.g., `User::filter_by_name("Alice")`) or
/// use [`Query::all`] / [`Query::filter`] directly:
///
/// ```
/// # #[derive(Debug, toasty::Model)]
/// # struct User {
/// #     #[key]
/// #     id: i64,
/// #     name: String,
/// #     age: i64,
/// # }
/// use toasty::stmt::{List, Query};
///
/// // All users
/// let q = Query::<List<User>>::all();
///
/// // Filtered
/// let q = Query::<List<User>>::filter(User::fields().age().gt(18));
///
/// // Chained
/// let mut q = Query::<List<User>>::all()
///     .and(User::fields().name().eq("Alice"));
/// q.limit(10);
/// ```
///
/// # Execution
///
/// Pass the query to [`Db::exec`](crate::Db::exec) or convert it with
/// [`IntoStatement`] for batch use.
pub struct Query<T> {
    pub(crate) untyped: stmt::Query,
    _p: PhantomData<T>,
}

// Methods available on all Query<T>
impl<T> Query<T> {
    /// Create an empty unit query that returns no records.
    ///
    /// # Examples
    ///
    /// ```
    /// # use toasty::stmt::Query;
    /// let q = Query::<()>::unit();
    /// ```
    pub fn unit() -> Self {
        Self {
            untyped: stmt::Query::unit(),
            _p: PhantomData,
        }
    }

    pub(crate) const fn from_untyped(untyped: stmt::Query) -> Self {
        Self {
            untyped,
            _p: PhantomData,
        }
    }

    /// Convert a model expression to a query.
    ///
    /// # Examples
    ///
    /// ```
    /// # use toasty::stmt::{Query, Expr};
    /// # use toasty_core::stmt as core_stmt;
    /// let expr = Expr::<i64>::from_untyped(core_stmt::Expr::Value(
    ///     core_stmt::Value::from(42_i64),
    /// ));
    /// let _q = Query::from_expr(expr);
    /// ```
    pub fn from_expr(expr: Expr<T>) -> Self {
        match expr.untyped {
            stmt::Expr::Stmt(expr) => match *expr.stmt {
                stmt::Statement::Query(stmt) => Self::from_untyped(stmt),
                stmt => todo!("stmt={stmt:#?}"),
            },
            expr => Self::from_untyped(stmt::Query::values(expr)),
        }
    }

    /// Add an additional filter, combined with AND, to this query.
    ///
    /// Returns `self` for method chaining.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Debug, toasty::Model)]
    /// # struct User {
    /// #     #[key]
    /// #     id: i64,
    /// #     name: String,
    /// # }
    /// use toasty::stmt::{List, Query};
    ///
    /// let q = Query::<List<User>>::all()
    ///     .and(User::fields().name().eq("Alice"));
    /// ```
    pub fn and(mut self, filter: Expr<bool>) -> Self {
        self.untyped.add_filter(filter.untyped);
        self
    }

    /// Eagerly load a related association when this query executes.
    ///
    /// `path` identifies the relation to include (e.g., a has-many or
    /// belongs-to field). The related records are loaded in the same
    /// round-trip and attached to the parent model.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Debug, toasty::Model)]
    /// # struct User {
    /// #     #[key]
    /// #     id: i64,
    /// #     name: String,
    /// # }
    /// use toasty::stmt::{List, Path, Query};
    ///
    /// let mut q = Query::<List<User>>::all();
    /// // Include the field at index 1 (name)
    /// q.include(Path::<User, String>::from_field_index(1));
    /// ```
    pub fn include(&mut self, path: impl Into<stmt::Path>) -> &mut Self {
        self.untyped.include(path.into());
        self
    }

    /// Set the sort order for this query.
    ///
    /// Pass an [`OrderByExpr`](toasty_core::stmt::OrderByExpr) obtained from
    /// [`Path::asc`] or [`Path::desc`]:
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Debug, toasty::Model)]
    /// # struct User {
    /// #     #[key]
    /// #     id: i64,
    /// #     name: String,
    /// # }
    /// use toasty::stmt::{List, Query};
    ///
    /// let mut q = Query::<List<User>>::all();
    /// q.order_by(User::fields().name().desc());
    /// ```
    pub fn order_by(&mut self, order_by: impl Into<stmt::OrderBy>) -> &mut Self {
        self.untyped.order_by = Some(order_by.into());
        self
    }

    /// Limit the number of records returned.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Debug, toasty::Model)]
    /// # struct User {
    /// #     #[key]
    /// #     id: i64,
    /// #     name: String,
    /// # }
    /// use toasty::stmt::{List, Query};
    ///
    /// let mut q = Query::<List<User>>::all();
    /// q.limit(10);
    /// ```
    pub fn limit(&mut self, n: usize) -> &mut Self {
        self.untyped.limit = Some(stmt::Limit::Offset(stmt::LimitOffset {
            limit: stmt::Value::from(n as i64).into(),
            offset: None,
        }));
        self
    }

    /// Skip the first `n` records. Requires a prior call to [`limit`](Query::limit).
    ///
    /// # Panics
    ///
    /// Panics if no `limit` has been set on this query.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Debug, toasty::Model)]
    /// # struct User {
    /// #     #[key]
    /// #     id: i64,
    /// #     name: String,
    /// # }
    /// use toasty::stmt::{List, Query};
    ///
    /// let mut q = Query::<List<User>>::all();
    /// q.limit(10);
    /// q.offset(20);
    /// ```
    pub fn offset(&mut self, n: usize) -> &mut Self {
        self.untyped.limit = match self.untyped.limit.take() {
            Some(stmt::Limit::Offset(limit_offset)) => {
                Some(stmt::Limit::Offset(stmt::LimitOffset {
                    limit: limit_offset.limit,
                    offset: Some(stmt::Expr::Value(Value::from(n))),
                }))
            }
            Some(stmt::Limit::Cursor(_)) => {
                panic!("cannot use offset with cursor-based pagination")
            }
            None => panic!("limit required for offset"),
        };
        self
    }

    /// Convert this query into a [`Delete`] statement that removes all matching
    /// records.
    ///
    /// The returned `Delete<()>` does not return the removed records.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Debug, toasty::Model)]
    /// # struct User {
    /// #     #[key]
    /// #     id: i64,
    /// #     name: String,
    /// # }
    /// use toasty::stmt::{List, Query};
    ///
    /// let delete = Query::<List<User>>::filter(User::fields().name().eq("Alice"))
    ///     .delete();
    /// ```
    pub fn delete(self) -> Delete<()> {
        Delete::from_untyped(self.untyped.delete())
    }

    /// Widen a single-row query back into a list query.
    ///
    /// This is the inverse of [`first`](Query::first) or [`one`](Query::one).
    /// Panics if the query is not currently in single-row mode.
    ///
    /// # Panics
    ///
    /// Panics if this query is not a single-row query.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Debug, toasty::Model)]
    /// # struct User {
    /// #     #[key]
    /// #     id: i64,
    /// #     name: String,
    /// # }
    /// use toasty::stmt::{List, Query};
    ///
    /// let q: Query<User> = Query::<List<User>>::all().one();
    /// let _list_q: Query<List<User>> = q.to_list();
    /// ```
    pub fn to_list(mut self) -> Query<List<T>> {
        assert!(self.untyped.single, "not a single query");
        self.untyped.single = false;

        Query {
            untyped: self.untyped,
            _p: PhantomData,
        }
    }
}

impl<T> Query<List<T>> {
    /// Narrow this list query to return at most one record, wrapped in
    /// `Option`.
    ///
    /// The resulting `Query<Option<T>>` returns `Some(record)` if at least one
    /// row matches, or `None` if no rows match.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Debug, toasty::Model)]
    /// # struct User {
    /// #     #[key]
    /// #     id: i64,
    /// #     name: String,
    /// # }
    /// use toasty::stmt::{List, Query};
    ///
    /// let q: Query<Option<User>> = Query::<List<User>>::all().first();
    /// ```
    pub fn first(mut self) -> Query<Option<T>> {
        set_first(&mut self.untyped);

        Query {
            untyped: self.untyped,
            _p: PhantomData,
        }
    }

    /// Narrow this list query to return exactly one record.
    ///
    /// The resulting `Query<T>` returns the record directly. If no rows match,
    /// execution returns an error.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Debug, toasty::Model)]
    /// # struct User {
    /// #     #[key]
    /// #     id: i64,
    /// #     name: String,
    /// # }
    /// use toasty::stmt::{List, Query};
    ///
    /// let q: Query<User> = Query::<List<User>>::all().one();
    /// ```
    pub fn one(mut self) -> Query<T> {
        set_first(&mut self.untyped);

        Query {
            untyped: self.untyped,
            _p: PhantomData,
        }
    }
}

fn set_first(query: &mut stmt::Query) {
    assert!(!query.single, "query is single");
    query.single = true;
}

impl<T: Load> Query<T> {
    /// Execute this query against the given executor and return the result.
    ///
    /// The return type depends on the query's type parameter `T`:
    /// - `Query<List<M>>` returns `Vec<M>`.
    /// - `Query<M>` returns `M` (errors if no row matches).
    /// - `Query<Option<M>>` returns `Option<M>`.
    ///
    /// # Examples
    ///
    /// ```
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// # #[derive(Debug, toasty::Model)]
    /// # struct User {
    /// #     #[key]
    /// #     id: i64,
    /// #     name: String,
    /// # }
    /// # let driver = toasty_driver_sqlite::Sqlite::in_memory();
    /// # let mut db = toasty::Db::builder().models(toasty::models!(User)).build(driver).await.unwrap();
    /// # db.push_schema().await.unwrap();
    /// use toasty::stmt::{List, Query};
    ///
    /// let users: Vec<User> = Query::<List<User>>::all()
    ///     .exec(&mut db)
    ///     .await
    ///     .unwrap();
    /// # });
    /// ```
    pub async fn exec(self, executor: &mut dyn Executor) -> Result<T::Output> {
        executor.exec(self.into_statement()).await
    }
}

/// Methods for list queries: `Query<List<M>>`
impl<M: Model> Query<List<M>> {
    /// Create a query that selects records of `M` matching `expr`.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Debug, toasty::Model)]
    /// # struct User {
    /// #     #[key]
    /// #     id: i64,
    /// #     name: String,
    /// # }
    /// use toasty::stmt::{List, Query};
    ///
    /// let q = Query::<List<User>>::filter(User::fields().name().eq("Alice"));
    /// ```
    pub fn filter(expr: Expr<bool>) -> Self {
        let mut query = stmt::Query::new_select(M::id(), expr.untyped);
        query.single = false;
        Self::from_untyped(query)
    }

    /// Convert this list query into a count query that returns the number of
    /// matching records as a `u64`.
    ///
    /// The returned `Query<u64>` wraps a `SELECT COUNT(*)` query.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Debug, toasty::Model)]
    /// # struct User {
    /// #     #[key]
    /// #     id: i64,
    /// #     name: String,
    /// # }
    /// use toasty::stmt::{List, Query};
    ///
    /// let q: Query<u64> = Query::<List<User>>::all().count();
    /// ```
    pub fn count(mut self) -> Query<u64> {
        // Set the returning clause to COUNT(*)
        *self.untyped.returning_mut_unwrap() = Returning::Expr(stmt::Expr::count_star());
        self.untyped.single = true;

        Query::from_untyped(self.untyped)
    }

    /// Create a query that selects all records of `M`.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[derive(Debug, toasty::Model)]
    /// # struct User {
    /// #     #[key]
    /// #     id: i64,
    /// #     name: String,
    /// # }
    /// use toasty::stmt::{List, Query};
    ///
    /// let q = Query::<List<User>>::all();
    /// ```
    pub fn all() -> Self {
        let filter = stmt::Expr::Value(Value::from_bool(true));
        let mut query = stmt::Query::new_select(M::id(), filter);
        query.single = false;
        Self::from_untyped(query)
    }
}

impl<T> IntoStatement for Query<T> {
    type Returning = T;

    fn into_statement(self) -> Statement<T> {
        Statement::from_untyped_stmt(self.untyped.into())
    }
}

impl<T> IntoStatement for &Query<T> {
    type Returning = T;

    fn into_statement(self) -> Statement<T> {
        Statement::from_untyped_stmt(self.clone().untyped.into())
    }
}

impl<T> Clone for Query<T> {
    fn clone(&self) -> Self {
        Self {
            untyped: self.untyped.clone(),
            _p: PhantomData,
        }
    }
}

impl<T> fmt::Debug for Query<T> {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.untyped.fmt(fmt)
    }
}