zero_postgres/tokio/transaction.rs
1//! Transaction support for asynchronous PostgreSQL connections.
2
3use super::Conn;
4use crate::error::{Error, Result};
5
6/// A PostgreSQL transaction for the asynchronous connection.
7///
8/// This struct provides transaction control. The connection is passed
9/// to `commit` and `rollback` methods to execute the transaction commands.
10pub struct Transaction {
11 connection_id: u32,
12}
13
14impl Transaction {
15 /// Create a new transaction (internal use only).
16 pub(crate) fn new(connection_id: u32) -> Self {
17 Self { connection_id }
18 }
19
20 /// Commit the transaction.
21 ///
22 /// This consumes the transaction and sends a COMMIT statement to the server.
23 /// The connection must be passed as an argument to execute the commit.
24 ///
25 /// # Errors
26 ///
27 /// Returns `Error::InvalidUsage` if the connection is not the same
28 /// as the one that started the transaction.
29 pub async fn commit(self, conn: &mut Conn) -> Result<()> {
30 let actual = conn.connection_id();
31 if self.connection_id != actual {
32 return Err(Error::InvalidUsage(format!(
33 "connection mismatch: expected {}, got {}",
34 self.connection_id, actual
35 )));
36 }
37 conn.query_drop("COMMIT").await?;
38 Ok(())
39 }
40
41 /// Rollback the transaction.
42 ///
43 /// This consumes the transaction and sends a ROLLBACK statement to the server.
44 /// The connection must be passed as an argument to execute the rollback.
45 ///
46 /// # Errors
47 ///
48 /// Returns `Error::InvalidUsage` if the connection is not the same
49 /// as the one that started the transaction.
50 pub async fn rollback(self, conn: &mut Conn) -> Result<()> {
51 let actual = conn.connection_id();
52 if self.connection_id != actual {
53 return Err(Error::InvalidUsage(format!(
54 "connection mismatch: expected {}, got {}",
55 self.connection_id, actual
56 )));
57 }
58 conn.query_drop("ROLLBACK").await?;
59 Ok(())
60 }
61}