use super::{schema::Schema, DatabaseDriver};
use crate::{error::Error, BoxFuture};
use std::fmt::Display;
pub trait Transaction<K, Tx>: Schema<PrimaryKey = K>
where
K: Default + Display + PartialEq,
{
async fn transaction<F, T>(tx: F) -> Result<T, Error>
where
F: for<'a> FnOnce(&'a Tx) -> BoxFuture<'a, Result<T, Error>>;
}
#[cfg(feature = "orm-sqlx")]
impl<'c, M, K> Transaction<K, sqlx::Transaction<'c, DatabaseDriver>> for M
where
M: Schema<PrimaryKey = K>,
K: Default + Display + PartialEq,
{
async fn transaction<F, T>(tx: F) -> Result<T, Error>
where
F: for<'a> FnOnce(
&'a sqlx::Transaction<'c, DatabaseDriver>,
) -> BoxFuture<'a, Result<T, Error>>,
{
let pool = Self::acquire_writer().await?.pool();
let transaction = pool.begin().await?;
let data = tx(&transaction).await?;
transaction.commit().await?;
Ok(data)
}
}