sql_middleware/sqlite/connection/
tx.rs

1use crate::middleware::SqlMiddlewareDbError;
2
3use super::{SqliteConnection, run_blocking};
4
5impl SqliteConnection {
6    /// Begin a transaction, transitioning this connection into transactional mode.
7    ///
8    /// # Errors
9    /// Returns `SqlMiddlewareDbError` if the transaction cannot be started or is already active.
10    pub async fn begin(&mut self) -> Result<(), SqlMiddlewareDbError> {
11        if self.in_transaction {
12            return Err(SqlMiddlewareDbError::ExecutionError(
13                "SQLite transaction already in progress".into(),
14            ));
15        }
16        run_blocking(self.conn_handle(), move |guard| {
17            guard
18                .execute_batch("BEGIN")
19                .map_err(SqlMiddlewareDbError::SqliteError)
20        })
21        .await?;
22        self.in_transaction = true;
23        Ok(())
24    }
25
26    /// Commit an open transaction.
27    ///
28    /// # Errors
29    /// Returns `SqlMiddlewareDbError` if committing fails or no transaction is active.
30    pub async fn commit(&mut self) -> Result<(), SqlMiddlewareDbError> {
31        if !self.in_transaction {
32            return Err(SqlMiddlewareDbError::ExecutionError(
33                "SQLite transaction not active".into(),
34            ));
35        }
36        run_blocking(self.conn_handle(), move |guard| {
37            guard
38                .execute_batch("COMMIT")
39                .map_err(SqlMiddlewareDbError::SqliteError)
40        })
41        .await?;
42        self.in_transaction = false;
43        Ok(())
44    }
45
46    /// Roll back an open transaction.
47    ///
48    /// # Errors
49    /// Returns `SqlMiddlewareDbError` if rolling back fails or no transaction is active.
50    pub async fn rollback(&mut self) -> Result<(), SqlMiddlewareDbError> {
51        if !self.in_transaction {
52            return Err(SqlMiddlewareDbError::ExecutionError(
53                "SQLite transaction not active".into(),
54            ));
55        }
56        run_blocking(self.conn_handle(), move |guard| {
57            guard
58                .execute_batch("ROLLBACK")
59                .map_err(SqlMiddlewareDbError::SqliteError)
60        })
61        .await?;
62        self.in_transaction = false;
63        Ok(())
64    }
65}