use std::sync::Arc;
use fastauth_core::Api;
use fastauth_core::adapter::{DbError, DbResult};
use fastauth_core::events::DeferredEvents;
use sqlx_core::transaction::TransactionManager;
use tokio::sync::{Mutex, MutexGuard};
use crate::{Dialect, SharedConn, Sqlx};
pub struct SharedTx<DB: Dialect> {
tx: SharedConn<DB>,
events: DeferredEvents,
}
impl<DB: Dialect> std::fmt::Debug for SharedTx<DB> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SharedTx")
.field("events", &self.events)
.finish_non_exhaustive()
}
}
impl<DB: Dialect> SharedTx<DB> {
pub fn new(tx: sqlx::Transaction<'static, DB>) -> Self {
Self {
tx: Arc::new(Mutex::new(tx)),
events: DeferredEvents::default(),
}
}
pub async fn lock(&self) -> MutexGuard<'_, sqlx::Transaction<'static, DB>> {
self.tx.lock().await
}
pub async fn commit(self) -> DbResult<()> {
let tx = unwrap(self.tx)?;
if DB::TransactionManager::get_transaction_depth(&*tx) > 1 {
return Err(DbError::Other(
"a fastauth savepoint is still open in the transaction".into(),
));
}
tx.commit().await.map_err(DbError::other)?;
self.events.fire().await;
Ok(())
}
pub async fn rollback(self) -> DbResult<()> {
unwrap(self.tx)?.rollback().await.map_err(DbError::other)
}
}
fn unwrap<DB: Dialect>(tx: SharedConn<DB>) -> DbResult<sqlx::Transaction<'static, DB>> {
Arc::try_unwrap(tx)
.map(Mutex::into_inner)
.map_err(|_| DbError::Other("a fastauth call still holds the transaction".into()))
}
pub trait InTx<'a, DB: Dialect> {
fn in_tx(self, tx: &'a SharedTx<DB>) -> Self;
}
impl<'a, DB: Dialect> InTx<'a, DB> for Api<'a, Sqlx<DB>> {
fn in_tx(self, tx: &'a SharedTx<DB>) -> Self {
let db = self.adapter().bind(tx.tx.clone());
self.within(db, &tx.events)
}
}