easy_sql/database_structs/
transaction.rs1use std::ops::{Deref, DerefMut};
2
3use anyhow::Context;
4use easy_macros::always_context;
5use sqlx::Database;
6use std::fmt::Debug;
7
8use crate::{
9 Driver, EasyExecutor,
10 traits::{DriverConnection, InternalDriver, SetupSql},
11};
12#[derive(Debug)]
16pub struct Transaction<'a, D: Driver> {
17 internal: sqlx::Transaction<'a, D::InternalDriver>,
18}
19
20#[always_context]
21impl<'a, D: Driver> Transaction<'a, D> {
22 pub fn new(internal: sqlx::Transaction<'a, D::InternalDriver>) -> Self {
23 Transaction { internal }
24 }
25
26 pub async fn commit(self) -> anyhow::Result<()> {
27 self.internal.commit().await?;
28 Ok(())
29 }
30
31 pub async fn rollback(self) -> anyhow::Result<()> {
32 self.internal.rollback().await?;
33 Ok(())
34 }
35}
36
37#[always_context]
38impl<'c, D: Driver> EasyExecutor<D> for &mut Transaction<'c, D>
39where
40 for<'b> &'b mut DriverConnection<D>: sqlx::Executor<'b, Database = D::InternalDriver>,
41{
42 type InternalExecutor<'b>
43 = &'b mut DriverConnection<D>
44 where
45 Self: 'b;
46 type IntoInternalExecutor<'b>
47 = &'b mut DriverConnection<D>
48 where
49 Self: 'b;
50 async fn query_setup<O: SetupSql<D> + Send + Sync>(
51 &mut self,
52 sql: O,
53 ) -> anyhow::Result<O::Output>
54 where
55 DriverConnection<D>: Send + Sync,
56 {
57 sql.query(self).await
58 }
59
60 fn executor<'a>(&'a mut self) -> Self::InternalExecutor<'a> {
61 &mut *self.internal
62 }
63 fn into_executor<'a>(self) -> Self::IntoInternalExecutor<'a>
64 where
65 Self: 'a,
66 {
67 &mut *self.internal
68 }
69}
70impl<'c, D: Driver> Deref for Transaction<'c, D> {
71 type Target = <InternalDriver<D> as Database>::Connection;
72
73 fn deref(&self) -> &Self::Target {
74 &self.internal
75 }
76}
77
78impl<'c, D: Driver> DerefMut for Transaction<'c, D> {
79 fn deref_mut(&mut self) -> &mut Self::Target {
80 &mut self.internal
81 }
82}