Skip to main content

phoenix_database/
lib.rs

1//! Phoenix's stable integration boundary around the Toasty ORM.
2//!
3//! Models and queries remain native Toasty types. Phoenix owns connection
4//! configuration, backend selection, migrations, and isolated test databases.
5
6use std::ops::{Deref, DerefMut};
7
8use thiserror::Error;
9use toasty::Db;
10
11mod migration;
12
13pub use migration::{Migration, MigrationError, MigrationPlan, MigrationRunner, MigrationStatus};
14
15pub use toasty::{
16    Deferred, Embed, Executor, Model, ModelSet, Statement, Transaction, TransactionBuilder, batch,
17    create, models, query, sql, stmt, update,
18};
19
20/// SQL backend selected for this database handle.
21#[derive(Clone, Copy, Debug, Eq, PartialEq)]
22pub enum Backend {
23    SQLite,
24    PostgreSQL,
25    MySQL,
26}
27
28/// A Toasty database handle with Phoenix deployment metadata.
29#[derive(Clone, Debug)]
30pub struct Database {
31    inner: Db,
32    backend: Backend,
33}
34
35impl Database {
36    /// Start configuring a database with the application's Toasty models.
37    #[must_use]
38    pub fn builder(models: ModelSet) -> DatabaseBuilder {
39        DatabaseBuilder::new(models)
40    }
41
42    /// Create a single-connection, isolated in-memory `SQLite` database.
43    ///
44    /// The schema is not created until [`Self::initialize_schema`] is called.
45    ///
46    /// # Errors
47    ///
48    /// Returns an error when the `SQLite` driver cannot initialize.
49    pub async fn sqlite_memory(models: ModelSet) -> Result<Self, DatabaseError> {
50        DatabaseBuilder::new(models).sqlite_memory().await
51    }
52
53    /// Return the configured database backend.
54    #[must_use]
55    pub const fn backend(&self) -> Backend {
56        self.backend
57    }
58
59    /// Create all Toasty model tables in a new, empty database.
60    ///
61    /// # Errors
62    ///
63    /// Returns an error when Toasty cannot apply the compiled model schema.
64    pub async fn initialize_schema(&self) -> Result<(), DatabaseError> {
65        self.inner
66            .push_schema()
67            .await
68            .map_err(DatabaseError::Toasty)
69    }
70
71    /// Borrow the native Toasty database handle.
72    #[must_use]
73    pub const fn toasty(&self) -> &Db {
74        &self.inner
75    }
76
77    /// Mutably borrow the native Toasty database handle.
78    pub const fn toasty_mut(&mut self) -> &mut Db {
79        &mut self.inner
80    }
81}
82
83impl Deref for Database {
84    type Target = Db;
85
86    fn deref(&self) -> &Self::Target {
87        &self.inner
88    }
89}
90
91impl DerefMut for Database {
92    fn deref_mut(&mut self) -> &mut Self::Target {
93        &mut self.inner
94    }
95}
96
97/// Connection and pool configuration shared by SQL backends.
98pub struct DatabaseBuilder {
99    inner: toasty::db::Builder,
100}
101
102impl DatabaseBuilder {
103    fn new(models: ModelSet) -> Self {
104        let mut inner = Db::builder();
105        inner.models(models);
106        Self { inner }
107    }
108
109    /// Set the maximum number of pooled connections.
110    #[must_use]
111    pub fn max_connections(mut self, maximum: usize) -> Self {
112        self.inner.max_pool_size(maximum);
113        self
114    }
115
116    /// Set a prefix for every model table managed by Toasty.
117    #[must_use]
118    pub fn table_prefix(mut self, prefix: &str) -> Self {
119        self.inner.table_name_prefix(prefix);
120        self
121    }
122
123    /// Connect using a `sqlite:`, `postgresql:`, or `mysql:` URL.
124    ///
125    /// Only drivers enabled through this crate's `sqlite`, `pgsql` /
126    /// `postgresql`, or `mysql` Cargo feature are linked into the binary.
127    ///
128    /// # Errors
129    ///
130    /// Returns an error for unsupported URLs or failed database connections.
131    pub async fn connect(mut self, url: &str) -> Result<Database, DatabaseError> {
132        let backend = backend_from_url(url)?;
133        let inner = self
134            .inner
135            .connect(url)
136            .await
137            .map_err(DatabaseError::Toasty)?;
138        Ok(Database { inner, backend })
139    }
140
141    /// Build an isolated in-memory `SQLite` database.
142    ///
143    /// # Errors
144    ///
145    /// Returns an error when the `SQLite` driver cannot initialize.
146    pub async fn sqlite_memory(mut self) -> Result<Database, DatabaseError> {
147        let driver = toasty::db::Connect::new("sqlite::memory:").await?;
148        let inner = self
149            .inner
150            .build(driver)
151            .await
152            .map_err(DatabaseError::Toasty)?;
153        Ok(Database {
154            inner,
155            backend: Backend::SQLite,
156        })
157    }
158}
159
160fn backend_from_url(url: &str) -> Result<Backend, DatabaseError> {
161    let scheme = url.split_once(':').map_or(url, |(scheme, _)| scheme);
162    let backend = match scheme {
163        "sqlite" => Backend::SQLite,
164        "postgres" | "postgresql" => Backend::PostgreSQL,
165        "mysql" => Backend::MySQL,
166        _ => return Err(DatabaseError::UnsupportedBackend(scheme.to_owned())),
167    };
168    ensure_backend_compiled(backend)?;
169    Ok(backend)
170}
171
172fn ensure_backend_compiled(backend: Backend) -> Result<(), DatabaseError> {
173    let (compiled, name, feature) = match backend {
174        Backend::SQLite => (cfg!(feature = "sqlite"), "sqlite", "sqlite"),
175        Backend::PostgreSQL => (cfg!(feature = "postgresql"), "postgresql", "pgsql"),
176        Backend::MySQL => (cfg!(feature = "mysql"), "mysql", "mysql"),
177    };
178    if compiled {
179        Ok(())
180    } else {
181        Err(DatabaseError::BackendNotCompiled {
182            backend: name,
183            feature,
184        })
185    }
186}
187
188/// A fresh `SQLite` database owned by one test.
189///
190/// Constructing one per test avoids shared files, global cleanup, and test
191/// ordering dependencies. Dropping it discards all rows.
192#[derive(Debug)]
193pub struct TestDatabase {
194    database: Database,
195}
196
197impl TestDatabase {
198    /// Create a fresh in-memory database and initialize the model schema.
199    ///
200    /// # Errors
201    ///
202    /// Returns an error when database or schema initialization fails.
203    pub async fn new(models: ModelSet) -> Result<Self, DatabaseError> {
204        let database = Database::sqlite_memory(models).await?;
205        database.initialize_schema().await?;
206        Ok(Self { database })
207    }
208
209    /// Consume the fixture and return its database handle.
210    #[must_use]
211    pub fn into_database(self) -> Database {
212        self.database
213    }
214}
215
216impl Deref for TestDatabase {
217    type Target = Database;
218
219    fn deref(&self) -> &Self::Target {
220        &self.database
221    }
222}
223
224impl DerefMut for TestDatabase {
225    fn deref_mut(&mut self) -> &mut Self::Target {
226        &mut self.database
227    }
228}
229
230/// Database setup error with stable Phoenix categories.
231#[derive(Debug, Error)]
232pub enum DatabaseError {
233    #[error("unsupported database URL scheme `{0}`; expected sqlite, postgresql, or mysql")]
234    UnsupportedBackend(String),
235    #[error("database backend `{backend}` is not compiled; enable Cargo feature `{feature}`")]
236    BackendNotCompiled {
237        backend: &'static str,
238        feature: &'static str,
239    },
240    #[error("database operation failed: {0}")]
241    Toasty(#[from] toasty::Error),
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247
248    #[derive(Debug, Model)]
249    struct User {
250        #[key]
251        #[auto]
252        id: u64,
253        name: String,
254    }
255
256    #[tokio::test]
257    async fn each_test_database_has_independent_rows() {
258        let mut first = TestDatabase::new(models!(User)).await.unwrap();
259        let mut second = TestDatabase::new(models!(User)).await.unwrap();
260
261        User::create()
262            .name("Ada")
263            .exec(first.toasty_mut())
264            .await
265            .unwrap();
266
267        assert_eq!(User::all().exec(first.toasty_mut()).await.unwrap().len(), 1);
268        assert!(
269            User::all()
270                .exec(second.toasty_mut())
271                .await
272                .unwrap()
273                .is_empty()
274        );
275    }
276
277    #[test]
278    fn accepts_only_supported_sql_url_schemes() {
279        assert_eq!(
280            backend_from_url("sqlite::memory:").is_ok(),
281            cfg!(feature = "sqlite")
282        );
283        assert_eq!(
284            backend_from_url("postgresql://db.invalid/app").is_ok(),
285            cfg!(feature = "postgresql")
286        );
287        assert_eq!(
288            backend_from_url("mysql://db.invalid/app").is_ok(),
289            cfg!(feature = "mysql")
290        );
291        assert!(backend_from_url("redis://db.invalid/app").is_err());
292    }
293
294    #[test]
295    fn reports_the_feature_for_a_driver_that_is_not_compiled() {
296        let candidate = [
297            (Backend::SQLite, "sqlite"),
298            (Backend::PostgreSQL, "pgsql"),
299            (Backend::MySQL, "mysql"),
300        ]
301        .into_iter()
302        .find(|(backend, _)| ensure_backend_compiled(*backend).is_err());
303        if let Some((backend, expected_feature)) = candidate {
304            let DatabaseError::BackendNotCompiled { feature, .. } =
305                ensure_backend_compiled(backend).unwrap_err()
306            else {
307                panic!("expected an uncompiled-backend error");
308            };
309            assert_eq!(feature, expected_feature);
310        }
311    }
312}