Skip to main content

sqlx_mssql_odbc_core/
transaction.rs

1use crate::{Mssql, MssqlConnection};
2
3/// Transaction manager for MSSQL via ODBC.
4pub struct MssqlTransactionManager;
5
6impl sqlx_core::transaction::TransactionManager for MssqlTransactionManager {
7    type Database = Mssql;
8
9    async fn begin(
10        conn: &mut MssqlConnection,
11        _statement: Option<sqlx_core::sql_str::SqlStr>,
12    ) -> Result<(), sqlx_core::Error> {
13        // The blocking_begin command is sent to the actor synchronously via
14        // the channel. Since begin_blocking is a blocking send, we call it
15        // from within offload_blocking to avoid blocking the async runtime.
16        let depth = conn.transaction_depth();
17        let result = conn.begin_blocking();
18        if result.is_ok() {
19            conn.set_transaction_depth(depth + 1);
20        }
21        result
22    }
23
24    async fn commit(conn: &mut MssqlConnection) -> Result<(), sqlx_core::Error> {
25        let depth = conn.transaction_depth();
26        if depth == 0 {
27            return Ok(());
28        }
29        let result = conn.commit_blocking();
30        if result.is_ok() {
31            if depth == 1 {
32                conn.set_transaction_depth(0);
33            } else {
34                conn.set_transaction_depth(depth - 1);
35            }
36        }
37        result
38    }
39
40    async fn rollback(conn: &mut MssqlConnection) -> Result<(), sqlx_core::Error> {
41        let depth = conn.transaction_depth();
42        if depth == 0 {
43            return Ok(());
44        }
45        let result = conn.rollback_blocking();
46        if result.is_ok() {
47            if depth == 1 {
48                conn.set_transaction_depth(0);
49            } else {
50                conn.set_transaction_depth(depth - 1);
51            }
52        }
53        result
54    }
55
56    fn start_rollback(conn: &mut MssqlConnection) {
57        conn.start_rollback();
58    }
59
60    fn get_transaction_depth(conn: &MssqlConnection) -> usize {
61        conn.transaction_depth()
62    }
63}