cot 0.8.0

The Rust web framework for lazy developers.
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
//! Database query builder.

pub mod expr;

use std::marker::PhantomData;

use derive_more::with_trait::Debug;
use thiserror::Error;

use crate::db;
pub use crate::db::query::expr::{Expr, ExprAdd, ExprDiv, ExprMul, ExprOrd, ExprSort, ExprSub};
use crate::db::query::expr::{OrderByExpr, SqlQueryBuilder};
use crate::db::{Auto, DatabaseBackend, ForeignKey, Model, StatementResult, ToDbFieldValue};
const ERROR_PREFIX: &str = "expression error:";

/// An error that can occur when building a query.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum QueryBuildingError {
    /// Error when building an expression.
    #[error("{ERROR_PREFIX} unsupported expression: {0}")]
    UnsupportedExpr(String),
    /// Error when building a query.
    #[error(transparent)]
    SeaQuery(#[from] sea_query::error::Error),
}

/// A query that can be executed on a database. Can be used to filter, update,
/// or delete rows.
///
/// # Example
///
/// ```
/// use cot::db::model;
/// use cot::db::query::Query;
///
/// #[model]
/// struct User {
///     #[model(primary_key)]
///     id: i32,
///     name: String,
///     age: i32,
/// }
///
/// let query = Query::<User>::new();
/// ```
pub struct Query<T> {
    filter: Option<Expr>,
    limit: Option<u64>,
    order_by: Vec<OrderByExpr>,
    offset: Option<u64>,
    phantom_data: PhantomData<fn() -> T>,
}

// manual implementation to avoid `T: Debug` in the trait bounds
impl<T> Debug for Query<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Query")
            .field("filter", &self.filter)
            .field("order_by", &self.order_by)
            .field("limit", &self.limit)
            .field("offset", &self.offset)
            .field("phantom_data", &self.phantom_data)
            .finish()
    }
}

// manual implementation to avoid `T: Clone` in the trait bounds
impl<T> Clone for Query<T> {
    fn clone(&self) -> Self {
        Self {
            filter: self.filter.clone(),
            limit: self.limit,
            order_by: self.order_by.clone(),
            offset: self.offset,
            phantom_data: PhantomData,
        }
    }
}

// manual implementation to avoid `T: PartialEq` in the trait bounds
impl<T> PartialEq for Query<T> {
    fn eq(&self, other: &Self) -> bool {
        self.filter == other.filter
    }
}

impl<T: Model> Default for Query<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Model> Query<T> {
    /// Create a new query.
    ///
    /// # Example
    ///
    /// ```
    /// use cot::db::model;
    /// use cot::db::query::Query;
    ///
    /// #[model]
    /// struct User {
    ///     #[model(primary_key)]
    ///     id: i32,
    ///     name: String,
    ///     age: i32,
    /// }
    ///
    /// let query = Query::<User>::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            filter: None,
            limit: None,
            order_by: Vec::new(),
            offset: None,
            phantom_data: PhantomData,
        }
    }

    /// Set the filter expression for the query.
    ///
    /// # Example
    ///
    /// ```
    /// use cot::db::model;
    /// use cot::db::query::{Expr, Query};
    ///
    /// #[model]
    /// struct User {
    ///     #[model(primary_key)]
    ///     id: i32,
    ///     name: String,
    ///     age: i32,
    /// }
    ///
    /// let query = Query::<User>::new().filter(Expr::eq(Expr::field("name"), Expr::value("John")));
    /// ```
    pub fn filter(&mut self, filter: Expr) -> &mut Self {
        self.filter = Some(filter);
        self
    }

    /// Set the limit for the query.
    ///
    /// # Example
    ///
    /// ```
    /// use cot::db::model;
    /// use cot::db::query::{Expr, Query};
    ///
    /// #[model]
    /// struct User {
    ///     #[model(primary_key)]
    ///     id: i32,
    ///     name: String,
    ///     age: i32,
    /// }
    ///
    /// let query = Query::<User>::new().limit(10);
    /// ```
    pub fn limit(&mut self, limit: u64) -> &mut Self {
        self.limit = Some(limit);
        self
    }

    /// Set an order for records from the query.
    ///
    /// # Example
    ///
    /// ```
    /// use cot::db::model;
    /// use cot::db::query::{ExprSort, Query};
    ///
    /// #[model]
    /// struct User {
    ///     #[model(primary_key)]
    ///     id: i32,
    ///     name: String,
    /// }
    ///
    /// let mut query = Query::<User>::new();
    /// query.order_by([
    ///     <User as cot::db::Model>::Fields::id.asc(),
    ///     <User as cot::db::Model>::Fields::name.desc().nulls_first(),
    /// ]);
    /// ```
    pub fn order_by<I, O>(&mut self, order_by: I) -> &mut Self
    where
        O: Into<OrderByExpr>,
        I: IntoIterator<Item = O>,
    {
        self.order_by = order_by.into_iter().map(Into::into).collect();
        self
    }

    /// Set the offset for the query.
    ///
    /// # Example
    ///
    /// ```
    /// use cot::db::model;
    /// use cot::db::query::{Expr, Query};
    ///
    /// #[model]
    /// struct User {
    ///     #[model(primary_key)]
    ///     id: i32,
    ///     name: String,
    ///     age: i32,
    /// }
    ///
    /// let query = Query::<User>::new().offset(10);
    /// ```
    pub fn offset(&mut self, offset: u64) -> &mut Self {
        self.offset = Some(offset);
        self
    }

    /// Execute the query and return all results.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub async fn all<DB: DatabaseBackend>(&self, mut db: DB) -> db::Result<Vec<T>> {
        db.query(self).await
    }

    /// Execute the query and return the first result.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub async fn get<DB: DatabaseBackend>(&self, mut db: DB) -> db::Result<Option<T>> {
        // TODO panic/error if more than one result
        db.get(self).await
    }

    /// Execute the query and return the number of results.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub async fn count<DB: DatabaseBackend>(&self, mut db: DB) -> db::Result<u64> {
        db.count(self).await
    }

    /// Execute the query and check if any results exist.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub async fn exists<DB: DatabaseBackend>(&self, mut db: DB) -> db::Result<bool> {
        db.exists(self).await
    }

    /// Delete all rows that match the query.
    ///
    /// # Errors
    ///
    /// Returns an error if the query fails.
    pub async fn delete<DB: DatabaseBackend>(&self, mut db: DB) -> db::Result<StatementResult> {
        db.delete(self).await
    }

    pub(super) fn add_filter_to_statement<S: sea_query::ConditionalStatement>(
        &self,
        statement: &mut S,
        sql_builder: &dyn SqlQueryBuilder,
    ) -> Result<(), QueryBuildingError> {
        if let Some(filter) = &self.filter {
            statement.and_where(filter.as_sea_query_expr(sql_builder)?);
        }
        Ok(())
    }

    pub(super) fn add_limit_to_statement(&self, statement: &mut sea_query::SelectStatement) {
        if let Some(limit) = self.limit {
            statement.limit(limit);
        }
    }

    pub(super) fn add_order_by_to_statement(
        &self,
        statement: &mut sea_query::SelectStatement,
        sql_builder: &dyn SqlQueryBuilder,
    ) -> Result<(), QueryBuildingError> {
        for order_by in &self.order_by {
            order_by.add_to_statement(statement, sql_builder)?;
        }
        Ok(())
    }

    pub(super) fn add_offset_to_statement(&self, statement: &mut sea_query::SelectStatement) {
        if let Some(offset) = self.offset {
            statement.offset(offset);
        }
    }
}

/// A trait for database types that can be converted to the field type.
///
/// This trait is mostly a helper trait to make comparisons like `$id == 5`
/// where `id` is of type [`Auto`] or [`ForeignKey`] easier to write and more
/// readable.
///
/// # Example
///
/// ```
/// use cot::db::query::Query;
/// use cot::db::query::expr::{Expr, ExprEq};
/// use cot::db::{Auto, model, query};
///
/// #[model]
/// struct MyModel {
///     #[model(primary_key)]
///     id: Auto<i32>,
/// };
///
/// // uses the `IntoField` trait to convert the `5` to `Auto<i32>`
/// let expr = <MyModel as cot::db::Model>::Fields::id.eq(5);
/// ```
pub trait IntoField<T> {
    /// Converts the type to the field type.
    fn into_field(self) -> T;
}

impl<T: ToDbFieldValue> IntoField<T> for T {
    fn into_field(self) -> T {
        self
    }
}

impl<T> IntoField<Auto<T>> for T {
    fn into_field(self) -> Auto<T> {
        Auto::fixed(self)
    }
}

impl IntoField<String> for &str {
    fn into_field(self) -> String {
        self.to_string()
    }
}

impl<T: Model + Send + Sync> IntoField<ForeignKey<T>> for T {
    fn into_field(self) -> ForeignKey<T> {
        ForeignKey::from(self)
    }
}

impl<T: Model + Send + Sync> IntoField<ForeignKey<T>> for &T {
    fn into_field(self) -> ForeignKey<T> {
        ForeignKey::from(self)
    }
}

#[cfg(test)]
mod tests {
    use cot_macros::model;

    use super::*;
    use crate::db::{MockDatabaseBackend, RowsNum};

    #[model]
    #[derive(std::fmt::Debug, PartialEq, Eq)]
    struct MockModel {
        #[model(primary_key)]
        id: i32,
    }

    #[test]
    fn query_new() {
        let query: Query<MockModel> = Query::new();

        assert!(query.filter.is_none());
        assert!(query.limit.is_none());
        assert!(query.offset.is_none());
    }

    #[test]
    fn query_default() {
        let query: Query<MockModel> = Query::default();

        assert!(query.filter.is_none());
        assert!(query.limit.is_none());
        assert!(query.offset.is_none());
    }

    #[test]
    fn query_filter() {
        let mut query: Query<MockModel> = Query::new();

        query.filter(Expr::eq(Expr::field("name"), Expr::value("John")));

        assert!(query.filter.is_some());
    }

    #[test]
    fn query_limit() {
        let mut query: Query<MockModel> = Query::new();
        query.limit(10);
        assert!(query.limit.is_some());
        assert_eq!(query.limit.unwrap(), 10);
    }

    #[test]
    fn query_offset() {
        let mut query: Query<MockModel> = Query::new();
        query.offset(10);
        assert!(query.offset.is_some());
        assert_eq!(query.offset.unwrap(), 10);
    }

    #[cot::test]
    async fn query_all() {
        let mut db = MockDatabaseBackend::new();
        db.expect_query().returning(|_| Ok(Vec::<MockModel>::new()));
        let query: Query<MockModel> = Query::new();

        let result = query.all(&mut db).await;

        assert_eq!(result.unwrap(), Vec::<MockModel>::new());
    }

    #[cot::test]
    async fn query_get() {
        let mut db = MockDatabaseBackend::new();
        db.expect_get().returning(|_| Ok(Option::<MockModel>::None));
        let query: Query<MockModel> = Query::new();

        let result = query.get(&mut db).await;

        assert_eq!(result.unwrap(), Option::<MockModel>::None);
    }

    #[cot::test]
    async fn query_exists() {
        let mut db = MockDatabaseBackend::new();
        db.expect_exists()
            .returning(|_: &Query<MockModel>| Ok(false));

        let query: Query<MockModel> = Query::new();

        let result = query.exists(&mut db).await;
        assert!(result.is_ok());
    }

    #[cot::test]
    async fn query_delete() {
        let mut db = MockDatabaseBackend::new();
        db.expect_delete()
            .returning(|_: &Query<MockModel>| Ok(StatementResult::new(RowsNum(0))));
        let query: Query<MockModel> = Query::new();

        let result = query.delete(&mut db).await;

        assert!(result.is_ok());
    }
}