Answer#
A transaction makes a group of statements succeed or fail as one. In sqlx the early return is the rollback: if the Transaction value goes out of scope without commit, sqlx rolls it back (the sqlx documentation states this).
use sqlx::{sqlite::SqlitePoolOptions, SqlitePool};
async fn transfer(pool: &SqlitePool, from: i64, to: i64, amount: i64) -> Result<(), sqlx::Error> {
let mut tx = pool.begin().await?;
sqlx::query("UPDATE accounts SET balance = balance - ? WHERE id = ?").bind(amount).bind(from).execute(&mut *tx).await?;
sqlx::query("UPDATE accounts SET balance = balance + ? WHERE id = ?").bind(amount).bind(to).execute(&mut *tx).await?;
// The CHECK constraint on `balance` makes the first UPDATE fail when the account is short;
// the `?` then returns early, `tx` is dropped, and the transaction is rolled back.
tx.commit().await
}
async fn balances(pool: &SqlitePool) -> Vec<(i64, i64)> {
sqlx::query_as("SELECT id, balance FROM accounts ORDER BY id").fetch_all(pool).await.unwrap()
}
#[tokio::main]
async fn main() {
let pool = SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await.unwrap();
sqlx::query("CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER NOT NULL CHECK (balance >= 0))").execute(&pool).await.unwrap();
sqlx::query("INSERT INTO accounts VALUES (1, 100), (2, 0)").execute(&pool).await.unwrap();
println!("start: {:?}", balances(&pool).await);
println!("transfer 30: {:?}", transfer(&pool, 1, 2, 30).await.is_ok());
println!("after: {:?}", balances(&pool).await);
let err = transfer(&pool, 1, 2, 500).await.unwrap_err();
println!("transfer 500: {err}");
println!("after the failure: {:?}", balances(&pool).await);
}start: [(1, 100), (2, 0)]
transfer 30: true
after: [(1, 70), (2, 30)]
transfer 500: error returned from database: (code: 275) CHECK constraint failed: balance >= 0
after the failure: [(1, 70), (2, 30)]The first transfer moved 30 and committed. The second tried to move 500 out of an account holding 70: the database refused the first UPDATE through the CHECK (balance >= 0) rule, ? returned the error, the transaction was dropped, and the balances afterwards are the same as before the call.
Common mistakes#
- Passing
&poolinstead of&mut *txto the statements in the transaction. Those statements then run on another connection, outside the transaction. - Forgetting
commit(). The work is silently rolled back when the value is dropped. - Holding a transaction open while waiting for a slow network call. Other writers wait for it.
Related questions#
Do I need a transaction for one statement?#
A single statement is already atomic. Use a transaction when several statements must succeed together.
Why max_connections(1) in the example?#
For an in-memory SQLite database in a small demonstration. See the thread on in-memory databases in tests.
Sources#
- sqlx,
Transaction: https://docs.rs/sqlx/0.8.6/sqlx/struct.Transaction.html (read 2026-12-05)