1use std::sync::Arc;
18
19use luxid_core::error::{Error, Result};
20use sea_orm::{DatabaseConnection, DatabaseTransaction, TransactionTrait};
21
22#[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 static CURRENT: Handle;
41}
42
43#[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 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 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 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 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 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
162pub 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#[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
194pub 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 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
229pub 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 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}