Skip to main content

luxid_orm/
db.rs

1//! The database handle and the request-scoped connection.
2//!
3//! The data layer's ergonomics — `User::find(id)`, `User::query().where_eq(..)`
4//! — depend
5//! on an *ambient* connection: those call sites have nowhere to pass a `&db`.
6//!
7//! Luxid makes it ambient with a tokio task-local rather than a global. That
8//! buys the Eloquent call shape without process-wide state, and it is the same
9//! mechanism that makes transaction-per-test rollback work: a test scopes a
10//! transaction handle, and every query inside that scope joins it
11//! automatically, with no cooperation from the code under test.
12//!
13//! The failure mode is a detached `tokio::spawn`, which does not inherit
14//! task-locals. That reports an error naming the fix rather than silently
15//! reaching for a different connection.
16
17use std::sync::Arc;
18
19use luxid_core::error::{Error, Result};
20use sea_orm::{DatabaseConnection, DatabaseTransaction, TransactionTrait};
21
22/// A connection or an open transaction. Queries do not care which.
23#[derive(Clone)]
24pub enum Handle {
25    Pool(Arc<DatabaseConnection>),
26    Transaction(Arc<DatabaseTransaction>),
27}
28
29impl std::fmt::Debug for Handle {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        match self {
32            Self::Pool(_) => f.write_str("Handle::Pool"),
33            Self::Transaction(_) => f.write_str("Handle::Transaction"),
34        }
35    }
36}
37
38tokio::task_local! {
39    /// The connection in scope for the current task.
40    static CURRENT: Handle;
41}
42
43/// The application's database, registered as a singleton in `providers()`.
44#[derive(Clone, Debug)]
45pub struct Db {
46    pool: Arc<DatabaseConnection>,
47}
48
49impl Db {
50    pub async fn connect(url: impl Into<String>) -> Result<Self> {
51        let pool = sea_orm::Database::connect(url.into())
52            .await
53            .map_err(|err| Error::internal(format!("could not connect to the database: {err}")))?;
54
55        Ok(Self {
56            pool: Arc::new(pool),
57        })
58    }
59
60    /// An isolated in-memory SQLite database.
61    ///
62    /// The pool is capped at one connection deliberately: SQLite gives every
63    /// *connection* its own `:memory:` database, so a larger pool would hand
64    /// out connections that cannot see each other's tables.
65    pub async fn in_memory() -> Result<Self> {
66        let mut options = sea_orm::ConnectOptions::new("sqlite::memory:");
67        options.max_connections(1);
68
69        let pool = sea_orm::Database::connect(options).await.map_err(|err| {
70            Error::internal(format!("could not open an in-memory database: {err}"))
71        })?;
72
73        Ok(Self {
74            pool: Arc::new(pool),
75        })
76    }
77
78    pub fn from_connection(connection: DatabaseConnection) -> Self {
79        Self {
80            pool: Arc::new(connection),
81        }
82    }
83
84    pub fn connection(&self) -> &DatabaseConnection {
85        &self.pool
86    }
87
88    /// Run `work` with this database ambient, so `User::find(..)` inside it
89    /// resolves. The request adapter wraps every action in one of these.
90    pub async fn scope<T>(&self, work: impl Future<Output = T>) -> T {
91        CURRENT
92            .scope(Handle::Pool(Arc::clone(&self.pool)), work)
93            .await
94    }
95
96    /// Run `work` inside a transaction that is **always rolled back**.
97    ///
98    /// This is the harness behind `#[luxid::test]`: tests share one database,
99    /// run in parallel, and leave nothing behind — no truncation, no fixtures,
100    /// no ordering constraints.
101    pub async fn rollback_scope<T>(&self, work: impl AsyncFnOnce() -> T) -> Result<T> {
102        let transaction = self
103            .pool
104            .begin()
105            .await
106            .map_err(|err| Error::internal(format!("could not begin a transaction: {err}")))?;
107
108        let handle = Handle::Transaction(Arc::new(transaction));
109        let outcome = CURRENT.scope(handle.clone(), work()).await;
110
111        // The Arc held by the scope is dropped by now, so unwrapping is
112        // infallible in practice; if user code stashed a clone, rolling back
113        // is skipped rather than panicking.
114        if let Handle::Transaction(transaction) = handle
115            && let Some(transaction) = Arc::into_inner(transaction)
116        {
117            transaction
118                .rollback()
119                .await
120                .map_err(|err| Error::internal(format!("could not roll back: {err}")))?;
121        }
122
123        Ok(outcome)
124    }
125
126    /// Run `work` in a transaction, committing on `Ok` and rolling back on
127    /// `Err`.
128    pub async fn transaction<T>(&self, work: impl AsyncFnOnce() -> Result<T>) -> Result<T> {
129        let transaction = self
130            .pool
131            .begin()
132            .await
133            .map_err(|err| Error::internal(format!("could not begin a transaction: {err}")))?;
134
135        let handle = Handle::Transaction(Arc::new(transaction));
136        let outcome = CURRENT.scope(handle.clone(), work()).await;
137
138        let Handle::Transaction(transaction) = handle else {
139            unreachable!("the handle was just constructed as a transaction");
140        };
141        let Some(transaction) = Arc::into_inner(transaction) else {
142            return Err(Error::internal(
143                "a database handle outlived its transaction; do not store `Handle` across scopes",
144            ));
145        };
146
147        match outcome {
148            Ok(value) => {
149                transaction.commit().await.map_err(|err| {
150                    Error::internal(format!("could not commit the transaction: {err}"))
151                })?;
152                Ok(value)
153            }
154            Err(error) => {
155                let _ = transaction.rollback().await;
156                Err(error)
157            }
158        }
159    }
160}
161
162/// The connection in scope, or a diagnosable error.
163pub fn current() -> Result<Handle> {
164    CURRENT.try_with(Handle::clone).map_err(|_| {
165        Error::internal(
166            "no database connection is in scope. Queries must run inside a request, \
167             a `Db::scope`, or a `#[luxid::test]`. A detached `tokio::spawn` does not \
168             inherit the scope — pass the handle in, or spawn inside `Db::scope`.",
169        )
170    })
171}
172
173/// Run a query against whichever handle is in scope.
174///
175/// A macro rather than a function because `Pool` and `Transaction` are
176/// different `ConnectionTrait` types, and unifying them behind `dyn` would
177/// forfeit SeaORM's generic execution path.
178#[macro_export]
179macro_rules! with_connection {
180    ($handle:expr, |$conn:ident| $body:expr) => {
181        match $handle {
182            $crate::db::Handle::Pool(pool) => {
183                let $conn = pool.as_ref();
184                $body
185            }
186            $crate::db::Handle::Transaction(transaction) => {
187                let $conn = transaction.as_ref();
188                $body
189            }
190        }
191    };
192}
193
194/// Middleware that puts the application's database in scope for the request.
195///
196/// `luxid-core` cannot depend on `luxid-orm` — the dependency runs the other
197/// way — so the connection scope arrives as middleware rather than as a field
198/// the adapter sets. Register it once globally:
199///
200/// ```ignore
201/// App::new()
202///     .providers(Providers::new().singleton(move |_| db.clone()))
203///     .middleware(WithDatabase)
204/// ```
205pub struct WithDatabase;
206
207impl luxid_core::middleware::Middleware for WithDatabase {
208    fn handle<'a>(
209        &'a self,
210        ctx: luxid_core::HttpContext,
211        next: luxid_core::middleware::Next,
212    ) -> luxid_core::middleware::BoxFuture<'a, Result<luxid_core::Response>> {
213        Box::pin(async move {
214            // If a handle is already in scope — a test running inside
215            // `rollback_scope`, say — join it rather than reaching for the
216            // pool. Overriding here would strand the request outside the
217            // caller's transaction, and with a single-connection pool it would
218            // deadlock against the connection that transaction holds.
219            if current().is_ok() {
220                return next.run(ctx).await;
221            }
222
223            let db = ctx.services.get::<Db>()?;
224            db.scope(next.run(ctx)).await
225        })
226    }
227}
228
229/// As [`WithDatabase`], but every request runs in a transaction that is rolled
230/// back afterwards. Intended for tests, never for production.
231pub struct WithRollbackDatabase;
232
233impl luxid_core::middleware::Middleware for WithRollbackDatabase {
234    fn handle<'a>(
235        &'a self,
236        ctx: luxid_core::HttpContext,
237        next: luxid_core::middleware::Next,
238    ) -> luxid_core::middleware::BoxFuture<'a, Result<luxid_core::Response>> {
239        Box::pin(async move {
240            // Already inside a transaction: nesting another would be a
241            // savepoint at best, and would fight an outer rollback.
242            if current().is_ok() {
243                return next.run(ctx).await;
244            }
245
246            let db = ctx.services.get::<Db>()?;
247            db.rollback_scope(async || next.run(ctx).await).await?
248        })
249    }
250}