use std::sync::Arc;
use luxid_core::error::{Error, Result};
use sea_orm::{DatabaseConnection, DatabaseTransaction, TransactionTrait};
#[derive(Clone)]
pub enum Handle {
Pool(Arc<DatabaseConnection>),
Transaction(Arc<DatabaseTransaction>),
}
impl std::fmt::Debug for Handle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Pool(_) => f.write_str("Handle::Pool"),
Self::Transaction(_) => f.write_str("Handle::Transaction"),
}
}
}
tokio::task_local! {
static CURRENT: Handle;
}
#[derive(Clone, Debug)]
pub struct Db {
pool: Arc<DatabaseConnection>,
}
impl Db {
pub async fn connect(url: impl Into<String>) -> Result<Self> {
let pool = sea_orm::Database::connect(url.into())
.await
.map_err(|err| Error::internal(format!("could not connect to the database: {err}")))?;
Ok(Self {
pool: Arc::new(pool),
})
}
pub async fn in_memory() -> Result<Self> {
let mut options = sea_orm::ConnectOptions::new("sqlite::memory:");
options.max_connections(1);
let pool = sea_orm::Database::connect(options).await.map_err(|err| {
Error::internal(format!("could not open an in-memory database: {err}"))
})?;
Ok(Self {
pool: Arc::new(pool),
})
}
pub fn from_connection(connection: DatabaseConnection) -> Self {
Self {
pool: Arc::new(connection),
}
}
pub fn connection(&self) -> &DatabaseConnection {
&self.pool
}
pub async fn scope<T>(&self, work: impl Future<Output = T>) -> T {
CURRENT
.scope(Handle::Pool(Arc::clone(&self.pool)), work)
.await
}
pub async fn rollback_scope<T>(&self, work: impl AsyncFnOnce() -> T) -> Result<T> {
let transaction = self
.pool
.begin()
.await
.map_err(|err| Error::internal(format!("could not begin a transaction: {err}")))?;
let handle = Handle::Transaction(Arc::new(transaction));
let outcome = CURRENT.scope(handle.clone(), work()).await;
if let Handle::Transaction(transaction) = handle
&& let Some(transaction) = Arc::into_inner(transaction)
{
transaction
.rollback()
.await
.map_err(|err| Error::internal(format!("could not roll back: {err}")))?;
}
Ok(outcome)
}
pub async fn transaction<T>(&self, work: impl AsyncFnOnce() -> Result<T>) -> Result<T> {
let transaction = self
.pool
.begin()
.await
.map_err(|err| Error::internal(format!("could not begin a transaction: {err}")))?;
let handle = Handle::Transaction(Arc::new(transaction));
let outcome = CURRENT.scope(handle.clone(), work()).await;
let Handle::Transaction(transaction) = handle else {
unreachable!("the handle was just constructed as a transaction");
};
let Some(transaction) = Arc::into_inner(transaction) else {
return Err(Error::internal(
"a database handle outlived its transaction; do not store `Handle` across scopes",
));
};
match outcome {
Ok(value) => {
transaction.commit().await.map_err(|err| {
Error::internal(format!("could not commit the transaction: {err}"))
})?;
Ok(value)
}
Err(error) => {
let _ = transaction.rollback().await;
Err(error)
}
}
}
}
pub fn current() -> Result<Handle> {
CURRENT.try_with(Handle::clone).map_err(|_| {
Error::internal(
"no database connection is in scope. Queries must run inside a request, \
a `Db::scope`, or a `#[luxid::test]`. A detached `tokio::spawn` does not \
inherit the scope — pass the handle in, or spawn inside `Db::scope`.",
)
})
}
#[macro_export]
macro_rules! with_connection {
($handle:expr, |$conn:ident| $body:expr) => {
match $handle {
$crate::db::Handle::Pool(pool) => {
let $conn = pool.as_ref();
$body
}
$crate::db::Handle::Transaction(transaction) => {
let $conn = transaction.as_ref();
$body
}
}
};
}
pub struct WithDatabase;
impl luxid_core::middleware::Middleware for WithDatabase {
fn handle<'a>(
&'a self,
ctx: luxid_core::HttpContext,
next: luxid_core::middleware::Next,
) -> luxid_core::middleware::BoxFuture<'a, Result<luxid_core::Response>> {
Box::pin(async move {
if current().is_ok() {
return next.run(ctx).await;
}
let db = ctx.services.get::<Db>()?;
db.scope(next.run(ctx)).await
})
}
}
pub struct WithRollbackDatabase;
impl luxid_core::middleware::Middleware for WithRollbackDatabase {
fn handle<'a>(
&'a self,
ctx: luxid_core::HttpContext,
next: luxid_core::middleware::Next,
) -> luxid_core::middleware::BoxFuture<'a, Result<luxid_core::Response>> {
Box::pin(async move {
if current().is_ok() {
return next.run(ctx).await;
}
let db = ctx.services.get::<Db>()?;
db.rollback_scope(async || next.run(ctx).await).await?
})
}
}