Transaction rollback strategy
Learn how to isolate database tests by wrapping each test in a transaction and rolling it back, so test rows never reach the shared test database
A transaction rollback strategy isolates tests by wrapping each test's writes in a database transaction and undoing them at the end. The test begins a transaction, inserts and updates rows inside it, checks the results, and then rolls the transaction back instead of committing it. The database ends the test exactly as it started it, and the next test sees a clean table.
Where This Fits
The earlier pages isolated tests in two ways. One page gave the tests a separate database, and another gave each test its own fresh database. Both work, and both cost something. A separate database still shares rows between tests, and a fresh database per test takes time to create and migrate. The rollback strategy is the third way. It reuses one database, and it undoes each test's work instead of throwing the database away.
Think of writing on a whiteboard with a promise to erase it. The writing is real while it is there, and anyone in the room can read it, but the eraser at the end leaves the board blank for the next person. A transaction is the writing, and the rollback is the eraser.
The Smallest Working Version
A transaction starts with pool.begin(), which checks a connection out of the pool and starts a transaction on it. Queries run against the transaction instead of the pool, and the test ends by calling rollback() on it. The rows written inside the transaction disappear, and the connection returns to the pool.
use axum_project::db::setup_test_pool;
use sqlx::PgPool;
const TEST_DATABASE_URL: &str = "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests";
async fn count_with_email(pool: &PgPool, email: &str) -> i64 {
let (count,): (i64,) =
sqlx::query_as("SELECT COUNT(*) FROM users WHERE email = $1")
.bind(email)
.fetch_one(pool)
.await
.unwrap();
count
}
#[tokio::test]
async fn rollback_removes_the_inserted_row() {
let pool = setup_test_pool(TEST_DATABASE_URL).await;
let email = "t14-rollback@example.com";
sqlx::query("DELETE FROM users WHERE email = $1")
.bind(email)
.execute(&pool)
.await
.unwrap();
let mut tx = pool.begin().await.unwrap();
sqlx::query("INSERT INTO users (name, email) VALUES ($1, $2)")
.bind("Asha")
.bind(email)
.execute(&mut *tx)
.await
.unwrap();
let (inside,): (i64,) = sqlx::query_as(
"SELECT COUNT(*) FROM users WHERE email = $1",
)
.bind(email)
.fetch_one(&mut *tx)
.await
.unwrap();
assert_eq!(inside, 1);
tx.rollback().await.unwrap();
assert_eq!(count_with_email(&pool, email).await, 0);
}
The test inserts a row inside the transaction and counts it twice. The count inside the transaction is one, because the transaction sees its own writes. The count after the rollback is zero, because the rollback undid the insert. The two counts together prove the strategy works. The row was real enough to read, and it is gone afterwards.
Run it with the connection string set.
DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests" cargo test --test rollback
The output shows the test passing.
test rollback_removes_the_inserted_row ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Working Setup:
If that test passes, the rollback works. The insert was visible inside the transaction and invisible after it, which is the whole mechanism. Every other test on this page is a variation on the same two counts.
Understanding the Transaction Piece by Piece
Three parts of the smallest test are new, and each one has a job that is easy to get wrong. The begin call, the &mut *tx argument, and the rollback call all look like plumbing, and each one changes what the database does.
Beginning the transaction
let mut tx = pool.begin().await.unwrap();
The begin() call takes one connection out of the pool and sends a BEGIN statement on it. From that moment, every query on that connection runs inside the transaction. The variable is mut because queries borrow it mutably, and because rollback() and commit() both take it by value at the end. The transaction value owns the connection, and the connection returns to the pool only when the transaction ends.
Running queries inside the transaction
.execute(&mut *tx)
A query that should run inside the transaction must be given the transaction, not the pool. The &mut *tx expression dereferences the transaction to the connection inside it and borrows that connection mutably. The * reaches through the transaction wrapper to the connection, and the &mut lends it to the query for one call. A query given &pool instead runs outside the transaction, on a different connection, and its rows are written at once. That mistake is the most common one on this page, and the test below shows how to catch it.
Rolling back
tx.rollback().await.unwrap();
The rollback() call sends a ROLLBACK statement and returns the connection to the pool. Every write inside the transaction is undone, in reverse order, as if it never happened. The call takes the transaction by value, so the variable cannot be used afterwards. That is deliberate. A transaction that has been rolled back is finished, and the type system stops the test from running more queries on it by accident.
The Concept Behind a Transaction
A transaction is a group of database statements that succeed or fail together. Postgres treats the group as one unit. Either every statement in it becomes permanent when the transaction commits, or none of them does when it rolls back. There is no middle state where half the statements stuck.
A test exploits that rule. It does its writes inside a transaction and never commits, so the database treats the whole test as a unit that failed. The writes happened, the test read them, and then they were undone. The next test starts from the same state as the last one, because no test ever committed anything.
The key detail is visibility. A transaction sees its own writes, and other connections do not see them until the transaction commits. The test reads its own rows through the transaction, and a second connection reading the same table sees nothing. That is why the smallest test counts through the transaction first and through the pool second. The two counts read the same table from two different points of view.
Why Rollback Instead of a Fresh Database
The fresh-database approach from the macro page is stronger isolation, because each test gets a whole database nobody else touches. The rollback approach is faster, because creating a database and running migrations takes time, and beginning a transaction takes almost none. A suite with many tests runs noticeably faster on rollbacks, and the speed matters when the suite runs on every change.
The trade is that rollback isolation is weaker in two ways. A test that commits by accident leaves rows behind, and a test that runs queries against the pool instead of the transaction writes rows that no rollback can undo. Both mistakes break isolation silently, and the failure shows up later as a flaky test in a different file. The fresh-database approach cannot fail that way, because there is no shared database to pollute.
The decision is practical, not moral. A small suite where each test is quick to write uses the macro, because the isolation is automatic. A large suite where database creation dominates the run time uses rollback, because the speed is worth the care. A suite can mix them, with the macro for tests that need a truly empty database and rollback for the rest.
Dropping a Transaction Rolls Back Too
A transaction that is dropped without a commit or a rollback rolls back on its own. Dropping means the value goes out of scope, and sqlx sends a rollback when the transaction value is destroyed. A test can rely on that, and the code reads shorter without an explicit rollback call.
#[tokio::test]
async fn dropped_transaction_rolls_back() {
let pool = setup_test_pool(TEST_DATABASE_URL).await;
let email = "t14-dropped@example.com";
sqlx::query("DELETE FROM users WHERE email = $1")
.bind(email)
.execute(&pool)
.await
.unwrap();
{
let mut tx = pool.begin().await.unwrap();
sqlx::query("INSERT INTO users (name, email) VALUES ($1, $2)")
.bind("Asha")
.bind(email)
.execute(&mut *tx)
.await
.unwrap();
}
assert_eq!(count_with_email(&pool, email).await, 0);
}
The block opens a scope, the transaction lives inside it, and the closing brace drops the transaction. No rollback() call appears, and the row is still gone. The explicit call is better in a test, because it says what the test means, and a reader does not have to know the drop rule to understand it. The drop rule matters most when a test fails early. A panic or an early return drops the transaction on the way out, and the rollback still happens, so a failing test does not leave rows behind either.
Drop Is a Safety Net, Not the Plan:
Relying on the drop to roll back works, and it saves a failing test from polluting the database. Writing the rollback explicitly is still better, because the test then states its intent. A reader who sees tx.rollback().await knows the test meant to undo its work. A reader who sees a closing brace has to know the drop rule to reach the same conclusion.
An Error Return Rolls Back Too
A helper that returns early with ? drops its transaction on the way out, and the drop rolls back. A test can use that shape to check that a failed operation leaves nothing behind, which is a real behaviour worth testing. A handler that inserts a user and then fails on a second step must not leave the first insert in the database.
async fn insert_then_fail(pool: &PgPool, email: &str) -> Result<(), sqlx::Error> {
let mut tx = pool.begin().await?;
sqlx::query("INSERT INTO users (name, email) VALUES ($1, $2)")
.bind("Asha")
.bind(email)
.execute(&mut *tx)
.await?;
Err(sqlx::Error::RowNotFound)
}
#[tokio::test]
async fn error_return_drops_the_transaction_and_rolls_back() {
let pool = setup_test_pool(TEST_DATABASE_URL).await;
let email = "t14-error@example.com";
sqlx::query("DELETE FROM users WHERE email = $1")
.bind(email)
.execute(&pool)
.await
.unwrap();
let result = insert_then_fail(&pool, email).await;
assert!(result.is_err());
assert_eq!(count_with_email(&pool, email).await, 0);
}
The helper inserts a row and then returns an error. The ? operators would do the same thing on a real failure. The transaction value is dropped when the function returns, the rollback runs, and the row is gone. The test asserts the error and then asserts the count, because both halves matter. An operation that reports failure and still writes a row is worse than an operation that reports failure cleanly.
Commit Is the Opposite Choice
A rollback test never commits, but the commit path is worth one test, because it proves the test understands the difference. The same insert, followed by commit(), leaves the row in the database, and the count after the commit is one.
#[tokio::test]
async fn commit_keeps_the_inserted_row() {
let pool = setup_test_pool(TEST_DATABASE_URL).await;
let email = "t14-commit@example.com";
sqlx::query("DELETE FROM users WHERE email = $1")
.bind(email)
.execute(&pool)
.await
.unwrap();
let mut tx = pool.begin().await.unwrap();
sqlx::query("INSERT INTO users (name, email) VALUES ($1, $2)")
.bind("Asha")
.bind(email)
.execute(&mut *tx)
.await
.unwrap();
tx.commit().await.unwrap();
assert_eq!(count_with_email(&pool, email).await, 1);
sqlx::query("DELETE FROM users WHERE email = $1")
.bind(email)
.execute(&pool)
.await
.unwrap();
}
The test deletes the row at the end by hand, because the commit made it permanent and no rollback will remove it. That manual delete is the cost of committing in a test. Every committed row needs a cleanup step, and a forgotten cleanup breaks the next run. The rollback tests need no cleanup step, because the rollback is the cleanup.
Forgetting Commit Is a Silent Rollback:
A transaction that ends without commit() rolls back, even when the test meant to keep the rows. The code compiles, the queries run, and the rows vanish when the transaction drops. A test that inserts rows and then reads them through the pool, expecting to find them, fails with a count of zero, and the failure looks like the insert never ran. The fix is the explicit commit() call, and the lesson is that a transaction keeps nothing unless it is told to.
Using a Transaction Through the Handlers
A rollback test that only runs raw SQL proves the mechanism, and a test that runs the handlers through the same transaction proves the application can use it. The handlers on this project take a PgPool, not a transaction, so they cannot run inside a test transaction as written. That is a design limit worth naming. A handler that needs transactional tests takes the transaction as its database handle, or the test wraps the handler calls in a transaction at a lower level.
The practical shape is a helper that runs the test logic inside a transaction and rolls back at the end. The helper begins the transaction, hands it to the test body, and rolls back when the body returns, so the test body never sees the begin or the rollback lines. A simpler and fully working pattern keeps the transaction in the test body, as the tests on this page do. The test begins the transaction, runs its queries with &mut *tx, and rolls back. No helper is needed until several tests repeat the same shape, and at that point the helper earns its place by removing the repeated begin and rollback lines.
How the Strategy Fits Together
The flow for one test runs in a fixed order, and the rollback is the step that makes the next test possible.
Test begins a transaction on one pooled connection
|
v
Queries run with &mut *tx, rows visible inside only
|
v
Assertions read through the transaction
|
v
Test calls tx.rollback(), rows undone
|
v
Connection returns to the pool, table unchanged
|
v
Next test begins its own transaction on a clean table
The table never changes across the run, because every test undoes its own work. A check of the row count before the suite and after the suite shows the same number, and that equality is the proof the strategy held.
Testing the Strategy
The test file for this page holds four tests, and all four passed against Postgres 16.15 with sqlx 0.9.0. The rollback test, the drop test, the error test, and the commit test each check one half of the mechanism.
DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests" cargo test --test rollback
test rollback_removes_the_inserted_row ... ok
test dropped_transaction_rolls_back ... ok
test error_return_drops_the_transaction_and_rolls_back ... ok
test commit_keeps_the_inserted_row ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
The commit test is the only one that writes a row permanently, and it deletes that row by hand at the end. The other three leave nothing behind, and the database holds the same rows after the run as it held before it.
Common Beginner Mistakes
Querying the pool instead of the transaction
// Wrong - this insert runs outside the transaction and is permanent
let mut tx = pool.begin().await.unwrap();
sqlx::query("INSERT INTO users (name, email) VALUES ($1, $2)")
.bind("Asha")
.bind(email)
.execute(&pool)
.await
.unwrap();
tx.rollback().await.unwrap();
The insert goes to the pool, which checks out a different connection, and that connection is not in a transaction. The row is written at once, and the rollback undoes nothing, because the transaction never held the row. The test then fails its final count, and the failure looks like the rollback is broken. The fix is &mut *tx on every query that belongs inside the transaction, and the rule is simple. A query that runs against the pool is permanent, and a query that runs against the transaction is undoable.
Reading through the pool inside the test
// Wrong - the pool cannot see uncommitted rows from another connection
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users WHERE email = $1")
.bind(email)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(count, 1);
The pool hands the query a different connection, and that connection cannot see the transaction's uncommitted rows. The count is zero, and the assertion fails, even though the insert succeeded. The fix is to count through &mut *tx, the same connection that ran the insert, because only that connection sees the uncommitted work.
Holding a transaction across unrelated work
// Wrong - the transaction stays open while the test does slow work
let mut tx = pool.begin().await.unwrap();
// a long wait, or many unrelated queries, happens here
tx.rollback().await.unwrap();
An open transaction holds a connection out of the pool, and Postgres keeps the old row versions the transaction might still read. A long-lived transaction slows other tests that wait for a connection, and it can block cleanup work on the table. The fix is to keep the transaction short. Begin it, run the queries, assert, and roll back, with nothing slow in between.
Using the transaction after rollback or commit
// Wrong - tx is moved by rollback, so this does not compile
tx.rollback().await.unwrap();
sqlx::query("SELECT 1").execute(&mut *tx).await.unwrap();
The rollback call takes the transaction by value, so the variable is gone afterwards. The compiler rejects the second use, and the error names the move. The fix is to run every query before the rollback, and to treat the rollback as the last line of the test.
A Rollback Test That Commits by Accident Pollutes the Database:
A test that calls commit() where it meant rollback() leaves its rows behind, and the next test that counts rows or inserts the same email fails. The failure appears in a different test from the one that made the mistake, which makes it hard to trace. The fix is to read the last line of each rollback test before running the suite, and to keep the commit test in its own file where its manual cleanup is visible.
Final Complete Example
Everything on this page put together is one test file and the pool module from the setup page. The handlers and the error type are unchanged, because the rollback strategy lives in the tests, not in the application.
use sqlx::{PgPool, migrate::Migrator, postgres::PgPoolOptions};
pub static MIGRATOR: Migrator = sqlx::migrate!();
pub async fn create_pool(database_url: &str) -> Result<PgPool, sqlx::Error> {
PgPoolOptions::new()
.max_connections(5)
.connect(database_url)
.await
}
pub async fn setup_test_pool(database_url: &str) -> PgPool {
let pool = create_pool(database_url)
.await
.expect("could not connect to the test database");
MIGRATOR
.run(&pool)
.await
.expect("could not run test migrations");
pool
}
use axum_project::db::setup_test_pool;
use sqlx::PgPool;
const TEST_DATABASE_URL: &str = "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests";
async fn count_with_email(pool: &PgPool, email: &str) -> i64 {
let (count,): (i64,) =
sqlx::query_as("SELECT COUNT(*) FROM users WHERE email = $1")
.bind(email)
.fetch_one(pool)
.await
.unwrap();
count
}
async fn insert_then_fail(pool: &PgPool, email: &str) -> Result<(), sqlx::Error> {
let mut tx = pool.begin().await?;
sqlx::query("INSERT INTO users (name, email) VALUES ($1, $2)")
.bind("Asha")
.bind(email)
.execute(&mut *tx)
.await?;
Err(sqlx::Error::RowNotFound)
}
#[tokio::test]
async fn rollback_removes_the_inserted_row() {
let pool = setup_test_pool(TEST_DATABASE_URL).await;
let email = "t14-rollback@example.com";
sqlx::query("DELETE FROM users WHERE email = $1")
.bind(email)
.execute(&pool)
.await
.unwrap();
let mut tx = pool.begin().await.unwrap();
sqlx::query("INSERT INTO users (name, email) VALUES ($1, $2)")
.bind("Asha")
.bind(email)
.execute(&mut *tx)
.await
.unwrap();
let (inside,): (i64,) = sqlx::query_as(
"SELECT COUNT(*) FROM users WHERE email = $1",
)
.bind(email)
.fetch_one(&mut *tx)
.await
.unwrap();
assert_eq!(inside, 1);
tx.rollback().await.unwrap();
assert_eq!(count_with_email(&pool, email).await, 0);
}
#[tokio::test]
async fn dropped_transaction_rolls_back() {
let pool = setup_test_pool(TEST_DATABASE_URL).await;
let email = "t14-dropped@example.com";
sqlx::query("DELETE FROM users WHERE email = $1")
.bind(email)
.execute(&pool)
.await
.unwrap();
{
let mut tx = pool.begin().await.unwrap();
sqlx::query("INSERT INTO users (name, email) VALUES ($1, $2)")
.bind("Asha")
.bind(email)
.execute(&mut *tx)
.await
.unwrap();
}
assert_eq!(count_with_email(&pool, email).await, 0);
}
#[tokio::test]
async fn error_return_drops_the_transaction_and_rolls_back() {
let pool = setup_test_pool(TEST_DATABASE_URL).await;
let email = "t14-error@example.com";
sqlx::query("DELETE FROM users WHERE email = $1")
.bind(email)
.execute(&pool)
.await
.unwrap();
let result = insert_then_fail(&pool, email).await;
assert!(result.is_err());
assert_eq!(count_with_email(&pool, email).await, 0);
}
#[tokio::test]
async fn commit_keeps_the_inserted_row() {
let pool = setup_test_pool(TEST_DATABASE_URL).await;
let email = "t14-commit@example.com";
sqlx::query("DELETE FROM users WHERE email = $1")
.bind(email)
.execute(&pool)
.await
.unwrap();
let mut tx = pool.begin().await.unwrap();
sqlx::query("INSERT INTO users (name, email) VALUES ($1, $2)")
.bind("Asha")
.bind(email)
.execute(&mut *tx)
.await
.unwrap();
tx.commit().await.unwrap();
assert_eq!(count_with_email(&pool, email).await, 1);
sqlx::query("DELETE FROM users WHERE email = $1")
.bind(email)
.execute(&pool)
.await
.unwrap();
}
Run the file with the connection string set, and all four tests pass.
DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests" cargo test --test rollback
Summary
The rollback strategy turns the database into a scratch pad. Each test writes what it needs, reads it back through the same transaction, and erases it with one call. The table never changes across the run, and no test can break another with a leftover row, as long as every query runs against the transaction and no test commits by accident.
The choice between the three isolation techniques is a trade between strength and speed. A fresh database per test is the strongest and the slowest. A shared database with a rollback per test is fast and needs care, because a query against the pool instead of the transaction escapes the rollback. A shared database with no isolation at all is fast and fragile, and it fails the moment two tests disagree about the rows. The rule that ties them together is simple. A test must leave the database as it found it, and the mechanism it uses to keep that promise is the only thing that changes.