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    /// # Errors
126    ///
127    /// Returns an error for unsupported URLs or failed database connections.
128    pub async fn connect(mut self, url: &str) -> Result<Database, DatabaseError> {
129        let backend = backend_from_url(url)?;
130        let inner = self
131            .inner
132            .connect(url)
133            .await
134            .map_err(DatabaseError::Toasty)?;
135        Ok(Database { inner, backend })
136    }
137
138    /// Build an isolated in-memory `SQLite` database.
139    ///
140    /// # Errors
141    ///
142    /// Returns an error when the `SQLite` driver cannot initialize.
143    pub async fn sqlite_memory(mut self) -> Result<Database, DatabaseError> {
144        let driver = toasty::db::Connect::new("sqlite::memory:").await?;
145        let inner = self
146            .inner
147            .build(driver)
148            .await
149            .map_err(DatabaseError::Toasty)?;
150        Ok(Database {
151            inner,
152            backend: Backend::SQLite,
153        })
154    }
155}
156
157fn backend_from_url(url: &str) -> Result<Backend, DatabaseError> {
158    let scheme = url.split_once(':').map_or(url, |(scheme, _)| scheme);
159    match scheme {
160        "sqlite" => Ok(Backend::SQLite),
161        "postgres" | "postgresql" => Ok(Backend::PostgreSQL),
162        "mysql" => Ok(Backend::MySQL),
163        _ => Err(DatabaseError::UnsupportedBackend(scheme.to_owned())),
164    }
165}
166
167/// A fresh `SQLite` database owned by one test.
168///
169/// Constructing one per test avoids shared files, global cleanup, and test
170/// ordering dependencies. Dropping it discards all rows.
171#[derive(Debug)]
172pub struct TestDatabase {
173    database: Database,
174}
175
176impl TestDatabase {
177    /// Create a fresh in-memory database and initialize the model schema.
178    ///
179    /// # Errors
180    ///
181    /// Returns an error when database or schema initialization fails.
182    pub async fn new(models: ModelSet) -> Result<Self, DatabaseError> {
183        let database = Database::sqlite_memory(models).await?;
184        database.initialize_schema().await?;
185        Ok(Self { database })
186    }
187
188    /// Consume the fixture and return its database handle.
189    #[must_use]
190    pub fn into_database(self) -> Database {
191        self.database
192    }
193}
194
195impl Deref for TestDatabase {
196    type Target = Database;
197
198    fn deref(&self) -> &Self::Target {
199        &self.database
200    }
201}
202
203impl DerefMut for TestDatabase {
204    fn deref_mut(&mut self) -> &mut Self::Target {
205        &mut self.database
206    }
207}
208
209/// Database setup error with stable Phoenix categories.
210#[derive(Debug, Error)]
211pub enum DatabaseError {
212    #[error("unsupported database URL scheme `{0}`; expected sqlite, postgresql, or mysql")]
213    UnsupportedBackend(String),
214    #[error("database operation failed: {0}")]
215    Toasty(#[from] toasty::Error),
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    #[derive(Debug, Model)]
223    struct User {
224        #[key]
225        #[auto]
226        id: u64,
227        name: String,
228    }
229
230    #[tokio::test]
231    async fn each_test_database_has_independent_rows() {
232        let mut first = TestDatabase::new(models!(User)).await.unwrap();
233        let mut second = TestDatabase::new(models!(User)).await.unwrap();
234
235        User::create()
236            .name("Ada")
237            .exec(first.toasty_mut())
238            .await
239            .unwrap();
240
241        assert_eq!(User::all().exec(first.toasty_mut()).await.unwrap().len(), 1);
242        assert!(
243            User::all()
244                .exec(second.toasty_mut())
245                .await
246                .unwrap()
247                .is_empty()
248        );
249    }
250
251    #[test]
252    fn accepts_only_supported_sql_url_schemes() {
253        assert_eq!(
254            backend_from_url("sqlite::memory:").unwrap(),
255            Backend::SQLite
256        );
257        assert_eq!(
258            backend_from_url("postgresql://db.invalid/app").unwrap(),
259            Backend::PostgreSQL
260        );
261        assert_eq!(
262            backend_from_url("mysql://db.invalid/app").unwrap(),
263            Backend::MySQL
264        );
265        assert!(backend_from_url("redis://db.invalid/app").is_err());
266    }
267}