use sqlx::{MySql, MySqlConnection, MySqlPool, Transaction};
use std::ops::DerefMut;
pub struct TransactionContext<'tx> {
tx: Option<Transaction<'tx, MySql>>,
}
impl<'tx> TransactionContext<'tx> {
pub async fn begin(pool: &MySqlPool) -> crate::Result<Self> {
Ok(Self {
tx: Some(pool.begin().await?),
})
}
pub async fn commit(mut self) -> crate::Result<()> {
if let Some(tx) = self.tx.take() {
tx.commit().await?;
}
Ok(())
}
pub async fn rollback(mut self) -> crate::Result<()> {
if let Some(tx) = self.tx.take() {
tx.rollback().await?;
}
Ok(())
}
pub fn as_executor(&mut self) -> &mut MySqlConnection {
self.tx
.as_mut()
.expect("Transaction has already been consumed")
.deref_mut()
}
#[allow(dead_code)]
pub fn into_inner(mut self) -> Transaction<'tx, MySql> {
self.tx
.take()
.expect("Transaction has already been consumed")
}
}
impl<'tx> Drop for TransactionContext<'tx> {
fn drop(&mut self) {
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_transaction_context_can_be_created() {
}
}