Skip to main content

sqlx_postgres/
transaction.rs

1use sqlx_core::database::Database;
2use sqlx_core::sql_str::SqlStr;
3
4use crate::error::Error;
5use crate::executor::Executor;
6
7use crate::{PgConnection, Postgres};
8
9pub(crate) use sqlx_core::transaction::*;
10
11/// Implementation of [`TransactionManager`] for PostgreSQL.
12pub struct PgTransactionManager;
13
14impl TransactionManager for PgTransactionManager {
15    type Database = Postgres;
16
17    async fn begin(conn: &mut PgConnection, statement: Option<SqlStr>) -> Result<(), Error> {
18        let depth = conn.inner.transaction_depth;
19
20        let statement = match statement {
21            // custom `BEGIN` statements are not allowed if we're already in
22            // a transaction (we need to issue a `SAVEPOINT` instead)
23            Some(_) if depth > 0 => return Err(Error::InvalidSavePointStatement),
24            Some(statement) => statement,
25            None => begin_ansi_transaction_sql(depth),
26        };
27
28        let rollback = Rollback::new(conn);
29        rollback.conn.queue_simple_query(statement.as_str())?;
30        // Claim the depth before the round trip, not after. `start_rollback` -- which both
31        // this guard and `Transaction`'s own drop guard call -- is a no-op while the depth is
32        // zero, so a future cancelled during the await below would otherwise leave the server
33        // in a transaction with nothing queued to end it. `Pool` then hands that connection
34        // to the next borrower, whose statements silently run inside it. Unwound just below
35        // if the BEGIN did not take.
36        rollback.conn.inner.transaction_depth += 1;
37        rollback.conn.wait_until_ready().await?;
38        if !rollback.conn.in_transaction() {
39            rollback.conn.inner.transaction_depth -= 1;
40            return Err(Error::BeginFailed);
41        }
42        rollback.defuse();
43
44        Ok(())
45    }
46
47    async fn commit(conn: &mut PgConnection) -> Result<(), Error> {
48        if conn.inner.transaction_depth > 0 {
49            conn.execute(commit_ansi_transaction_sql(conn.inner.transaction_depth))
50                .await?;
51
52            conn.inner.transaction_depth -= 1;
53        }
54
55        Ok(())
56    }
57
58    async fn rollback(conn: &mut PgConnection) -> Result<(), Error> {
59        if conn.inner.transaction_depth > 0 {
60            conn.execute(rollback_ansi_transaction_sql(conn.inner.transaction_depth))
61                .await?;
62
63            conn.inner.transaction_depth -= 1;
64        }
65
66        Ok(())
67    }
68
69    fn start_rollback(conn: &mut PgConnection) {
70        if conn.inner.transaction_depth > 0 {
71            conn.queue_simple_query(
72                rollback_ansi_transaction_sql(conn.inner.transaction_depth).as_str(),
73            )
74            .expect("BUG: Rollback query somehow too large for protocol");
75
76            conn.inner.transaction_depth -= 1;
77        }
78    }
79
80    fn get_transaction_depth(conn: &<Self::Database as Database>::Connection) -> usize {
81        conn.inner.transaction_depth
82    }
83}
84
85struct Rollback<'c> {
86    conn: &'c mut PgConnection,
87    defuse: bool,
88}
89
90impl Drop for Rollback<'_> {
91    fn drop(&mut self) {
92        if !self.defuse {
93            PgTransactionManager::start_rollback(self.conn)
94        }
95    }
96}
97
98impl<'c> Rollback<'c> {
99    fn new(conn: &'c mut PgConnection) -> Self {
100        Self {
101            conn,
102            defuse: false,
103        }
104    }
105    fn defuse(mut self) {
106        self.defuse = true;
107    }
108}