Skip to main content

rbox_db/
model.rs

1// Copyright (C) 2026 Dylan Jones
2// SPDX-License-Identifier: GPL-3.0-only
3
4//! Basic query, insertion, update, and deletion traits shared by database models.
5
6use diesel::prelude::*;
7use std::fmt::Debug;
8
9/// A trait representing a generic model with basic database operations.
10///
11/// This trait defines the structure for models that can be queried from a database.
12/// It includes methods for retrieving all records, finding a specific record by its ID,
13/// and checking if a record with a given ID exists.
14///
15/// # Type Parameters
16/// * `Id`: The type of the ID of the model. Must implement `PartialEq` and `Debug`.
17///
18/// # Methods
19/// * `all`: Queries all records in the database table.
20/// * `find`: Queries a record by its primary key.
21/// * `id_exists`: Checks if a record with the given primary key exists in the database table.
22pub trait Model: Sized + Clone {
23    /// The type of the ID of the model.
24    type Id: ?Sized + PartialEq + Debug + ToOwned;
25
26    /// Queries all records in the database table.
27    ///
28    /// # Arguments
29    /// * `conn`: A mutable reference to the database connection.
30    ///
31    /// # Returns
32    /// A `QueryResult` containing a vector of all records.
33    fn all(conn: &mut SqliteConnection) -> QueryResult<Vec<Self>>;
34
35    /// Queries a record by its primary key.
36    ///
37    /// # Arguments
38    /// * `conn`: A mutable reference to the database connection.
39    /// * `id`: A reference to the ID of the record to find.
40    ///
41    /// # Returns
42    /// A `QueryResult` containing an `Option` with the record if found.
43    fn find(conn: &mut SqliteConnection, id: &Self::Id) -> QueryResult<Option<Self>>;
44
45    /// Checks if a record with the given primary key exists.
46    ///
47    /// # Arguments
48    /// - `conn`: A mutable reference to the database connection.
49    /// - `id`: A reference to the ID of the record to check.
50    ///
51    /// # Returns
52    /// A `QueryResult` containing a boolean indicating whether the record exists.
53    fn id_exists(conn: &mut SqliteConnection, id: &Self::Id) -> QueryResult<bool>;
54}
55
56/// A trait for models that support update operations.
57///
58/// This trait extends the `Model` trait and provides methods for updating
59/// individual and multiple records.
60///
61/// # Methods
62/// * `update`: Updates an existing record in the database table.
63/// * `update_all`: Updates multiple records in the database table.
64pub trait ModelUpdate: Model {
65    /// Updates an existing record in the database table.
66    ///
67    /// # Arguments
68    /// - `conn`: A mutable reference to the database connection.
69    ///
70    /// # Returns
71    /// A `QueryResult` containing the updated record.
72    fn update(self, conn: &mut SqliteConnection) -> QueryResult<Self>;
73
74    /// Updates multiple records in the database table.
75    ///
76    /// Apply updates in input order within one transaction. A failure rolls back the entire batch.
77    ///
78    /// # Arguments
79    /// - `conn`: A mutable reference to the database connection.
80    /// - `items`: A vector of records to update.
81    ///
82    /// # Returns
83    /// A `QueryResult` containing a vector of updated records.
84    fn update_all(conn: &mut SqliteConnection, items: Vec<Self>) -> QueryResult<Vec<Self>> {
85        conn.transaction(|conn| {
86            let mut results = Vec::with_capacity(items.len());
87            for item in items {
88                results.push(item.update(conn)?);
89            }
90            Ok(results)
91        })
92    }
93}
94
95/// A trait for models that support deletion operations.
96///
97/// This trait extends the `Model` trait and provides methods for deleting
98/// individual and multiple records.
99///
100/// # Methods
101/// * `delete`: Deletes a record from the database table.
102/// * `delete_all`: Deletes multiple records from the database table.
103pub trait ModelDelete: Model {
104    /// Deletes a record from the database table.
105    ///
106    /// # Arguments
107    /// - `conn`: A mutable reference to the database connection.
108    /// - `id`: A reference to the ID of the record to delete.
109    ///
110    /// # Returns
111    /// A `QueryResult` containing the number of rows affected.
112    fn delete(conn: &mut SqliteConnection, id: &Self::Id) -> QueryResult<usize>;
113
114    /// Deletes multiple records from the database table.
115    ///
116    /// Delete in input order within one transaction. A failure rolls back the entire batch.
117    /// Tree models override this to handle overlapping subtrees without deleting twice.
118    ///
119    /// # Arguments
120    /// - `conn`: A mutable reference to the database connection.
121    /// - `ids`: A vector of references to the IDs of the records to delete.
122    ///
123    /// # Returns
124    /// A `QueryResult` containing the total number of rows affected.
125    fn delete_all(conn: &mut SqliteConnection, ids: Vec<&Self::Id>) -> QueryResult<usize> {
126        conn.transaction(|conn| {
127            let mut result: usize = 0;
128            for id in ids {
129                result += Self::delete(conn, id)?;
130            }
131            Ok(result)
132        })
133    }
134}
135
136/// A trait for models that support insertion operations.
137///
138/// This trait provides methods for inserting individual and multiple records into the database.
139///
140/// # Type Parameters
141/// * `Model`: The associated model type that implements the `Model` trait.
142///
143/// # Methods
144/// * `insert`: Inserts a new record into the database table.
145/// * `insert_all`: Inserts multiple records into the database table.
146pub trait ModelInsert: Sized {
147    /// The associated model type that implements the `Model` trait.
148    type Model: Model;
149
150    /// Inserts a new record into the database table.
151    ///
152    /// # Arguments
153    /// - `conn`: A mutable reference to the database connection.
154    ///
155    /// # Returns
156    /// A `QueryResult` containing the inserted `Model` record.
157    fn insert(self, conn: &mut SqliteConnection) -> QueryResult<Self::Model>;
158
159    /// Inserts multiple records into the database table.
160    ///
161    /// Insert in input order within one transaction. A failure rolls back the entire batch.
162    ///
163    /// # Arguments
164    /// - `conn`: A mutable reference to the database connection.
165    /// - `items`: A vector of records to insert.
166    ///
167    /// # Returns
168    /// A `QueryResult` containing a vector of the inserted `Model` records.
169    fn insert_all(conn: &mut SqliteConnection, items: Vec<Self>) -> QueryResult<Vec<Self::Model>> {
170        conn.transaction(|conn| {
171            let mut results = Vec::with_capacity(items.len());
172            for item in items {
173                results.push(item.insert(conn)?);
174            }
175            Ok(results)
176        })
177    }
178}