Skip to main content

cot/db/
query.rs

1//! Database query builder.
2
3pub mod expr;
4
5use std::marker::PhantomData;
6
7use derive_more::with_trait::Debug;
8use thiserror::Error;
9
10use crate::db;
11pub use crate::db::query::expr::{Expr, ExprAdd, ExprDiv, ExprMul, ExprOrd, ExprSort, ExprSub};
12use crate::db::query::expr::{OrderByExpr, SqlQueryBuilder};
13use crate::db::{Auto, DatabaseBackend, ForeignKey, Model, StatementResult, ToDbFieldValue};
14const ERROR_PREFIX: &str = "expression error:";
15
16/// An error that can occur when building a query.
17#[derive(Debug, Error)]
18#[non_exhaustive]
19pub enum QueryBuildingError {
20    /// Error when building an expression.
21    #[error("{ERROR_PREFIX} unsupported expression: {0}")]
22    UnsupportedExpr(String),
23    /// Error when building a query.
24    #[error(transparent)]
25    SeaQuery(#[from] sea_query::error::Error),
26}
27
28/// A query that can be executed on a database. Can be used to filter, update,
29/// or delete rows.
30///
31/// # Example
32///
33/// ```
34/// use cot::db::model;
35/// use cot::db::query::Query;
36///
37/// #[model]
38/// struct User {
39///     #[model(primary_key)]
40///     id: i32,
41///     name: String,
42///     age: i32,
43/// }
44///
45/// let query = Query::<User>::new();
46/// ```
47pub struct Query<T> {
48    filter: Option<Expr>,
49    limit: Option<u64>,
50    order_by: Vec<OrderByExpr>,
51    offset: Option<u64>,
52    phantom_data: PhantomData<fn() -> T>,
53}
54
55// manual implementation to avoid `T: Debug` in the trait bounds
56impl<T> Debug for Query<T> {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        f.debug_struct("Query")
59            .field("filter", &self.filter)
60            .field("order_by", &self.order_by)
61            .field("limit", &self.limit)
62            .field("offset", &self.offset)
63            .field("phantom_data", &self.phantom_data)
64            .finish()
65    }
66}
67
68// manual implementation to avoid `T: Clone` in the trait bounds
69impl<T> Clone for Query<T> {
70    fn clone(&self) -> Self {
71        Self {
72            filter: self.filter.clone(),
73            limit: self.limit,
74            order_by: self.order_by.clone(),
75            offset: self.offset,
76            phantom_data: PhantomData,
77        }
78    }
79}
80
81// manual implementation to avoid `T: PartialEq` in the trait bounds
82impl<T> PartialEq for Query<T> {
83    fn eq(&self, other: &Self) -> bool {
84        self.filter == other.filter
85    }
86}
87
88impl<T: Model> Default for Query<T> {
89    fn default() -> Self {
90        Self::new()
91    }
92}
93
94impl<T: Model> Query<T> {
95    /// Create a new query.
96    ///
97    /// # Example
98    ///
99    /// ```
100    /// use cot::db::model;
101    /// use cot::db::query::Query;
102    ///
103    /// #[model]
104    /// struct User {
105    ///     #[model(primary_key)]
106    ///     id: i32,
107    ///     name: String,
108    ///     age: i32,
109    /// }
110    ///
111    /// let query = Query::<User>::new();
112    /// ```
113    #[must_use]
114    pub fn new() -> Self {
115        Self {
116            filter: None,
117            limit: None,
118            order_by: Vec::new(),
119            offset: None,
120            phantom_data: PhantomData,
121        }
122    }
123
124    /// Set the filter expression for the query.
125    ///
126    /// # Example
127    ///
128    /// ```
129    /// use cot::db::model;
130    /// use cot::db::query::{Expr, Query};
131    ///
132    /// #[model]
133    /// struct User {
134    ///     #[model(primary_key)]
135    ///     id: i32,
136    ///     name: String,
137    ///     age: i32,
138    /// }
139    ///
140    /// let query = Query::<User>::new().filter(Expr::eq(Expr::field("name"), Expr::value("John")));
141    /// ```
142    pub fn filter(&mut self, filter: Expr) -> &mut Self {
143        self.filter = Some(filter);
144        self
145    }
146
147    /// Set the limit for the query.
148    ///
149    /// # Example
150    ///
151    /// ```
152    /// use cot::db::model;
153    /// use cot::db::query::{Expr, Query};
154    ///
155    /// #[model]
156    /// struct User {
157    ///     #[model(primary_key)]
158    ///     id: i32,
159    ///     name: String,
160    ///     age: i32,
161    /// }
162    ///
163    /// let query = Query::<User>::new().limit(10);
164    /// ```
165    pub fn limit(&mut self, limit: u64) -> &mut Self {
166        self.limit = Some(limit);
167        self
168    }
169
170    /// Set an order for records from the query.
171    ///
172    /// # Example
173    ///
174    /// ```
175    /// use cot::db::model;
176    /// use cot::db::query::{ExprSort, Query};
177    ///
178    /// #[model]
179    /// struct User {
180    ///     #[model(primary_key)]
181    ///     id: i32,
182    ///     name: String,
183    /// }
184    ///
185    /// let mut query = Query::<User>::new();
186    /// query.order_by([
187    ///     <User as cot::db::Model>::Fields::id.asc(),
188    ///     <User as cot::db::Model>::Fields::name.desc().nulls_first(),
189    /// ]);
190    /// ```
191    pub fn order_by<I, O>(&mut self, order_by: I) -> &mut Self
192    where
193        O: Into<OrderByExpr>,
194        I: IntoIterator<Item = O>,
195    {
196        self.order_by = order_by.into_iter().map(Into::into).collect();
197        self
198    }
199
200    /// Set the offset for the query.
201    ///
202    /// # Example
203    ///
204    /// ```
205    /// use cot::db::model;
206    /// use cot::db::query::{Expr, Query};
207    ///
208    /// #[model]
209    /// struct User {
210    ///     #[model(primary_key)]
211    ///     id: i32,
212    ///     name: String,
213    ///     age: i32,
214    /// }
215    ///
216    /// let query = Query::<User>::new().offset(10);
217    /// ```
218    pub fn offset(&mut self, offset: u64) -> &mut Self {
219        self.offset = Some(offset);
220        self
221    }
222
223    /// Execute the query and return all results.
224    ///
225    /// # Errors
226    ///
227    /// Returns an error if the query fails.
228    pub async fn all<DB: DatabaseBackend>(&self, mut db: DB) -> db::Result<Vec<T>> {
229        db.query(self).await
230    }
231
232    /// Execute the query and return the first result.
233    ///
234    /// # Errors
235    ///
236    /// Returns an error if the query fails.
237    pub async fn get<DB: DatabaseBackend>(&self, mut db: DB) -> db::Result<Option<T>> {
238        // TODO panic/error if more than one result
239        db.get(self).await
240    }
241
242    /// Execute the query and return the number of results.
243    ///
244    /// # Errors
245    ///
246    /// Returns an error if the query fails.
247    pub async fn count<DB: DatabaseBackend>(&self, mut db: DB) -> db::Result<u64> {
248        db.count(self).await
249    }
250
251    /// Execute the query and check if any results exist.
252    ///
253    /// # Errors
254    ///
255    /// Returns an error if the query fails.
256    pub async fn exists<DB: DatabaseBackend>(&self, mut db: DB) -> db::Result<bool> {
257        db.exists(self).await
258    }
259
260    /// Delete all rows that match the query.
261    ///
262    /// # Errors
263    ///
264    /// Returns an error if the query fails.
265    pub async fn delete<DB: DatabaseBackend>(&self, mut db: DB) -> db::Result<StatementResult> {
266        db.delete(self).await
267    }
268
269    pub(super) fn add_filter_to_statement<S: sea_query::ConditionalStatement>(
270        &self,
271        statement: &mut S,
272        sql_builder: &dyn SqlQueryBuilder,
273    ) -> Result<(), QueryBuildingError> {
274        if let Some(filter) = &self.filter {
275            statement.and_where(filter.as_sea_query_expr(sql_builder)?);
276        }
277        Ok(())
278    }
279
280    pub(super) fn add_limit_to_statement(&self, statement: &mut sea_query::SelectStatement) {
281        if let Some(limit) = self.limit {
282            statement.limit(limit);
283        }
284    }
285
286    pub(super) fn add_order_by_to_statement(
287        &self,
288        statement: &mut sea_query::SelectStatement,
289        sql_builder: &dyn SqlQueryBuilder,
290    ) -> Result<(), QueryBuildingError> {
291        for order_by in &self.order_by {
292            order_by.add_to_statement(statement, sql_builder)?;
293        }
294        Ok(())
295    }
296
297    pub(super) fn add_offset_to_statement(&self, statement: &mut sea_query::SelectStatement) {
298        if let Some(offset) = self.offset {
299            statement.offset(offset);
300        }
301    }
302}
303
304/// A trait for database types that can be converted to the field type.
305///
306/// This trait is mostly a helper trait to make comparisons like `$id == 5`
307/// where `id` is of type [`Auto`] or [`ForeignKey`] easier to write and more
308/// readable.
309///
310/// # Example
311///
312/// ```
313/// use cot::db::query::Query;
314/// use cot::db::query::expr::{Expr, ExprEq};
315/// use cot::db::{Auto, model, query};
316///
317/// #[model]
318/// struct MyModel {
319///     #[model(primary_key)]
320///     id: Auto<i32>,
321/// };
322///
323/// // uses the `IntoField` trait to convert the `5` to `Auto<i32>`
324/// let expr = <MyModel as cot::db::Model>::Fields::id.eq(5);
325/// ```
326pub trait IntoField<T> {
327    /// Converts the type to the field type.
328    fn into_field(self) -> T;
329}
330
331impl<T: ToDbFieldValue> IntoField<T> for T {
332    fn into_field(self) -> T {
333        self
334    }
335}
336
337impl<T> IntoField<Auto<T>> for T {
338    fn into_field(self) -> Auto<T> {
339        Auto::fixed(self)
340    }
341}
342
343impl IntoField<String> for &str {
344    fn into_field(self) -> String {
345        self.to_string()
346    }
347}
348
349impl<T: Model + Send + Sync> IntoField<ForeignKey<T>> for T {
350    fn into_field(self) -> ForeignKey<T> {
351        ForeignKey::from(self)
352    }
353}
354
355impl<T: Model + Send + Sync> IntoField<ForeignKey<T>> for &T {
356    fn into_field(self) -> ForeignKey<T> {
357        ForeignKey::from(self)
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use cot_macros::model;
364
365    use super::*;
366    use crate::db::{MockDatabaseBackend, RowsNum};
367
368    #[model]
369    #[derive(std::fmt::Debug, PartialEq, Eq)]
370    struct MockModel {
371        #[model(primary_key)]
372        id: i32,
373    }
374
375    #[test]
376    fn query_new() {
377        let query: Query<MockModel> = Query::new();
378
379        assert!(query.filter.is_none());
380        assert!(query.limit.is_none());
381        assert!(query.offset.is_none());
382    }
383
384    #[test]
385    fn query_default() {
386        let query: Query<MockModel> = Query::default();
387
388        assert!(query.filter.is_none());
389        assert!(query.limit.is_none());
390        assert!(query.offset.is_none());
391    }
392
393    #[test]
394    fn query_filter() {
395        let mut query: Query<MockModel> = Query::new();
396
397        query.filter(Expr::eq(Expr::field("name"), Expr::value("John")));
398
399        assert!(query.filter.is_some());
400    }
401
402    #[test]
403    fn query_limit() {
404        let mut query: Query<MockModel> = Query::new();
405        query.limit(10);
406        assert!(query.limit.is_some());
407        assert_eq!(query.limit.unwrap(), 10);
408    }
409
410    #[test]
411    fn query_offset() {
412        let mut query: Query<MockModel> = Query::new();
413        query.offset(10);
414        assert!(query.offset.is_some());
415        assert_eq!(query.offset.unwrap(), 10);
416    }
417
418    #[cot::test]
419    async fn query_all() {
420        let mut db = MockDatabaseBackend::new();
421        db.expect_query().returning(|_| Ok(Vec::<MockModel>::new()));
422        let query: Query<MockModel> = Query::new();
423
424        let result = query.all(&mut db).await;
425
426        assert_eq!(result.unwrap(), Vec::<MockModel>::new());
427    }
428
429    #[cot::test]
430    async fn query_get() {
431        let mut db = MockDatabaseBackend::new();
432        db.expect_get().returning(|_| Ok(Option::<MockModel>::None));
433        let query: Query<MockModel> = Query::new();
434
435        let result = query.get(&mut db).await;
436
437        assert_eq!(result.unwrap(), Option::<MockModel>::None);
438    }
439
440    #[cot::test]
441    async fn query_exists() {
442        let mut db = MockDatabaseBackend::new();
443        db.expect_exists()
444            .returning(|_: &Query<MockModel>| Ok(false));
445
446        let query: Query<MockModel> = Query::new();
447
448        let result = query.exists(&mut db).await;
449        assert!(result.is_ok());
450    }
451
452    #[cot::test]
453    async fn query_delete() {
454        let mut db = MockDatabaseBackend::new();
455        db.expect_delete()
456            .returning(|_: &Query<MockModel>| Ok(StatementResult::new(RowsNum(0))));
457        let query: Query<MockModel> = Query::new();
458
459        let result = query.delete(&mut db).await;
460
461        assert!(result.is_ok());
462    }
463}