zero_mysql/tokio/
transaction.rs

1use super::Conn;
2use crate::error::{Error, Result};
3
4/// A MySQL transaction for the asynchronous connection
5///
6/// This struct provides transaction control. The connection is passed
7/// to `commit` and `rollback` methods to execute the transaction commands.
8pub struct Transaction {
9    connection_id: u64,
10}
11
12impl Transaction {
13    pub(crate) fn new(connection_id: u64) -> Self {
14        Self { connection_id }
15    }
16
17    /// Commit the transaction
18    ///
19    /// Returns `Error::ConnectionMismatch` if the connection is not the same
20    /// as the one that started the transaction.
21    pub async fn commit(self, conn: &mut Conn) -> Result<()> {
22        let actual = conn.connection_id();
23        if self.connection_id != actual {
24            return Err(Error::ConnectionMismatch {
25                expected: self.connection_id,
26                actual,
27            });
28        }
29        conn.set_in_transaction(false);
30        conn.query_drop("COMMIT").await
31    }
32
33    /// Rollback the transaction
34    ///
35    /// Returns `Error::ConnectionMismatch` if the connection is not the same
36    /// as the one that started the transaction.
37    pub async fn rollback(self, conn: &mut Conn) -> Result<()> {
38        let actual = conn.connection_id();
39        if self.connection_id != actual {
40            return Err(Error::ConnectionMismatch {
41                expected: self.connection_id,
42                actual,
43            });
44        }
45        conn.set_in_transaction(false);
46        conn.query_drop("ROLLBACK").await
47    }
48}