Skip to content

Commit ce878ce

Browse files
authored
Correctly ROLLBACK transaction when dropped during BEGIN. (#3980)
Previously if the transaction was dropped while the transaction was being set up it was possible that the transaction was successfully opened but not closed. In common usage this would result in returning an open transaction to the connection pool which would have unexpected effects ranging from errors due to trying to nest transaction or serious bugs such as intended changes not occurring as they were unexpectedly inside a transaction that would never commit. This resolves the issue by constructing the `Transaction` object (which activates the drop handler) before starting to open the transaction. In the worst case this could result in trying to `ROLLBACK` a transaction that was never started but this just results in a harmless error which is much better than leaving an unexpected open transaction active on the connection. Fixes: #3932
1 parent a096548 commit ce878ce

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

sqlx-core/src/transaction.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -100,15 +100,19 @@ where
100100
conn: impl Into<MaybePoolConnection<'c, DB>>,
101101
statement: Option<SqlStr>,
102102
) -> BoxFuture<'c, Result<Self, Error>> {
103-
let mut conn = conn.into();
103+
let conn = conn.into();
104104

105105
Box::pin(async move {
106-
DB::TransactionManager::begin(&mut conn, statement).await?;
107-
108-
Ok(Self {
106+
let mut tx = Self {
109107
connection: conn,
108+
109+
// If the call to `begin` fails or doesn't complete we want to attempt a rollback in case the transaction was started.
110110
open: true,
111-
})
111+
};
112+
113+
DB::TransactionManager::begin(&mut tx.connection, statement).await?;
114+
115+
Ok(tx)
112116
})
113117
}
114118

0 commit comments

Comments
 (0)