zero_mysql/sync/
transaction.rs

1use super::Conn;
2use crate::error::{Error, Result};
3
4/// A MySQL transaction for the synchronous 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    /// Create a new transaction (internal use only)
14    pub(crate) fn new(connection_id: u64) -> Self {
15        Self { connection_id }
16    }
17
18    /// Commit the transaction
19    ///
20    /// This consumes the transaction and sends a COMMIT statement to the server.
21    /// The connection must be passed as an argument to execute the commit.
22    ///
23    /// # Errors
24    ///
25    /// Returns `Error::ConnectionMismatch` if the connection is not the same
26    /// as the one that started the transaction.
27    pub fn commit(self, conn: &mut Conn) -> Result<()> {
28        let actual = conn.connection_id();
29        if self.connection_id != actual {
30            return Err(Error::ConnectionMismatch {
31                expected: self.connection_id,
32                actual,
33            });
34        }
35        conn.set_in_transaction(false);
36        conn.query_drop("COMMIT")
37    }
38
39    /// Rollback the transaction
40    ///
41    /// This consumes the transaction and sends a ROLLBACK statement to the server.
42    /// The connection must be passed as an argument to execute the rollback.
43    ///
44    /// # Errors
45    ///
46    /// Returns `Error::ConnectionMismatch` if the connection is not the same
47    /// as the one that started the transaction.
48    pub fn rollback(self, conn: &mut Conn) -> Result<()> {
49        let actual = conn.connection_id();
50        if self.connection_id != actual {
51            return Err(Error::ConnectionMismatch {
52                expected: self.connection_id,
53                actual,
54            });
55        }
56        conn.set_in_transaction(false);
57        conn.query_drop("ROLLBACK")
58    }
59}