sqlx test
Learn how the sqlx test macro gives each test its own fresh Postgres database, runs migrations, applies fixtures, and cleans up afterwards
The #[sqlx::test] attribute marks an async test function and gives it a live database to work with. For every test it creates a brand new Postgres database, runs the project migrations in it, hands the test a connection pool for that database, and drops the database when the test passes. Each test starts with empty tables, so no test can see another test's rows.
Where This Fits
The last page set up one shared test database, and tests in that database share rows with each other. A test that inserts a user can break a second test that counts users, and the failure depends on the order the tests run in. This page removes that sharing. Instead of one database for all tests, each test gets its own database, created fresh and thrown away afterwards.
Think of exam desks with fresh answer sheets. Every student gets a blank sheet, writes on it, and hands it in. Nobody writes on anyone else's sheet, and nobody has to erase the last student's answers first. The macro is the invigilator handing out blank sheets.
The Smallest Working Version
The macro needs two features on sqlx that the setup page already turned on, macros and migrate, plus the Postgres driver and the Tokio runtime. The test function takes a pool as its argument, and the macro fills that argument in.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "=0.9.0", features = ["runtime-tokio", "postgres", "macros", "derive", "migrate"] }
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
The smallest test inserts a user and reads it back, using the pool the macro provides. There is no call to connect, and no call to run migrations. The macro did both before the test body ran.
use sqlx::{PgPool, Row};
#[sqlx::test]
async fn sqlx_test_gives_a_fresh_pool(pool: PgPool) -> sqlx::Result<()> {
let row = sqlx::query("SELECT COUNT(*) AS n FROM users")
.fetch_one(&pool)
.await?;
let count: i64 = row.get("n");
assert_eq!(count, 0);
sqlx::query("INSERT INTO users (name, email) VALUES ($1, $2)")
.bind("Asha")
.bind("t11-asha@example.com")
.execute(&pool)
.await?;
let row = sqlx::query("SELECT name FROM users WHERE email = $1")
.bind("t11-asha@example.com")
.fetch_one(&pool)
.await?;
let name: String = row.get("name");
assert_eq!(name, "Asha");
Ok(())
}
The test runs against a database the macro created for this one function. The count starts at zero because the database is fresh, and the insert and the read prove the migrations ran, because the users table exists. When the test passes, the macro drops the database.
Run it with DATABASE_URL set. The macro needs the variable to know which Postgres server to create the test databases on, and which database to create them next to.
DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests" cargo test --test sqlx_test
The output shows the test passing.
test sqlx_test_gives_a_fresh_pool ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Working Setup:
If that test passes, the macro is working. The database user can create databases, the migrations folder was found, and the fresh database was dropped after the pass. A second run passes exactly the same way, because nothing from the first run survives.
Understanding What the Macro Does
The macro does four jobs before the test body runs, and one job after it. Knowing the order explains most of the errors beginners meet.
Creating a database per test
For every annotated function, a new test database is created. The macro reads DATABASE_URL, connects to the server, and creates a database alongside the one named in the URL. The test database has a generated name, and the test never needs to know it. The pool the test receives points at that generated database, not at the database in the URL.
The user in DATABASE_URL must be allowed to create databases. That is the CREATEDB privilege from the last page. A user without it fails here with a permission error, before any test code runs. The fix is the ALTER ROLE axumdocs CREATEDB; command, not a change to the test.
Running migrations automatically
Migrations are applied automatically when a folder named migrations sits next to Cargo.toml, which is the directory the CARGO_MANIFEST_DIR variable points at. The macro finds the folder, runs the files in order, and the test starts with the users table already in place. This is the same migration the setup helper ran by hand, and the macro runs it without being asked.
The migration folder is the one from the last page, with the same users table.
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
Handing the test a pool
The pool argument is the only way the test reaches its database. The macro creates the pool, and the test uses it exactly like any other PgPool. Queries run against it, inserts land in it, and counts read from it. The pools of all running tests share one connection limit, so a run of many parallel tests does not open more connections than the server allows.
Dropping the database afterwards
Test databases are cleaned up automatically as tests succeed. A passing test leaves no database behind, which is why the database list after a run shows only the databases that existed before. A failing test leaves its database in place on purpose, so the developer can connect to it and inspect the rows that were there when the test failed. The next run of the same test binary deletes previously created test databases first, so the leftovers do not pile up forever.
A Failing Test Keeps Its Database:
A failed #[sqlx::test] test does not clean up, and that is deliberate. The database stays so the rows can be inspected with psql after the failure. The database name is generated, and the test output names it in the failure message. Connect to it, look at the rows, fix the code, and the next test run deletes it.
The Concept Behind One Database Per Test
Isolation is the idea that a test depends only on its own actions. A test that counts users must find the count its own inserts produced, not the count left behind by the test that ran before it. Sharing one database breaks isolation, because rows leak from one test into the next. Giving each test its own database restores it, because there is nothing to leak through.
The macro does not wrap the test in a transaction and roll it back. That is a different technique, and it has its own page. The macro creates a whole database, which is a stronger form of isolation. A transaction hides rows from other connections but keeps them in the same database. A fresh database has no other rows at all, not even hidden ones. The cost is time, because creating a database and running migrations takes longer than starting a transaction, and the benefit is that no test can ever interfere with another, no matter what it does.
Why the Macro Takes the Pool as an Argument
A plain #[tokio::test] function takes no arguments. The test has to build its own pool, which means every test repeats the connection and migration code. The #[sqlx::test] macro changes the shape of the function so the pool arrives as an argument, already connected and already migrated. The test body starts at the interesting part, the queries and the assertions, instead of the setup.
The argument also tells the macro what to do. A function with no argument runs like a plain async test, with no database management. A function with a PgPool argument gets a fresh database. The signature is the switch, and the macro reads it at compile time.
Test Function Signatures the Macro Accepts
The docs for sqlx 0.9.0 list three signatures that trigger database management. The return type is () or a Result, and the argument picks how much control the test wants.
The pool signature is the one most tests use. The test receives a ready pool and uses it directly.
#[sqlx::test]
async fn pool_signature(pool: PgPool) -> sqlx::Result<()> {
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users")
.fetch_one(&pool)
.await?;
assert_eq!(count, 0);
Ok(())
}
The single-connection signature hands the test one connection from the pool instead of the whole pool. It fits a test that runs one or two queries and never needs two connections at once. The type is PoolConnection<Postgres>, a single pooled connection, taken from sqlx::pool.
use sqlx::{Row, pool::PoolConnection};
#[sqlx::test]
async fn connection_signature(mut conn: PoolConnection<sqlx::Postgres>) -> sqlx::Result<()> {
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users")
.fetch_one(&mut *conn)
.await?;
assert_eq!(count, 0);
Ok(())
}
The test takes the connection as mut because queries borrow it mutably, and the &mut *conn dereference reaches through the pooled connection wrapper to the connection inside it, which is the type queries accept. The macro still creates the fresh database and still runs the migrations. Only the handle changes.
The options signature hands the test the pool options and the connection options, so the test can build its own pool with custom settings. It fits a test that needs a pool callback or a changed connection option, and it is the only signature where the test builds the pool itself.
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
#[sqlx::test]
async fn options_signature(
options: PgPoolOptions,
connect_options: PgConnectOptions,
) -> sqlx::Result<()> {
let pool = options.connect_with(connect_options).await?;
let (count,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users")
.fetch_one(&pool)
.await?;
assert_eq!(count, 0);
Ok(())
}
A test that returns () instead of a Result can use unwrap() or expect() on every fallible call. A test that returns sqlx::Result<()> can use ?, which is shorter and reads better when the test has many queries. Both shapes work, and the macro accepts both.
No Tokio Control Arguments:
The macro does not recognise the control arguments that #[tokio::test] accepts. Writing #[sqlx::test(flavor = "multi_thread")] fails to compile, because the macro was kept simple on purpose. A test that needs a specific runtime flavour has to build its own runtime instead of using the macro.
Proving Isolation with Two Tests
One test cannot prove isolation. Two tests can. The first inserts a row, and the second counts rows. If the tests shared a database, the second would see the first test's row and fail. With the macro, each test gets its own database, so the second still sees zero.
use sqlx::{PgPool, Row};
#[sqlx::test]
async fn sqlx_test_gives_a_fresh_pool(pool: PgPool) -> sqlx::Result<()> {
let row = sqlx::query("SELECT COUNT(*) AS n FROM users")
.fetch_one(&pool)
.await?;
let count: i64 = row.get("n");
assert_eq!(count, 0);
sqlx::query("INSERT INTO users (name, email) VALUES ($1, $2)")
.bind("Asha")
.bind("t11-asha@example.com")
.execute(&pool)
.await?;
let row = sqlx::query("SELECT name FROM users WHERE email = $1")
.bind("t11-asha@example.com")
.fetch_one(&pool)
.await?;
let name: String = row.get("name");
assert_eq!(name, "Asha");
Ok(())
}
#[sqlx::test]
async fn sqlx_test_second_test_sees_an_empty_table(pool: PgPool) -> sqlx::Result<()> {
let row = sqlx::query("SELECT COUNT(*) AS n FROM users")
.fetch_one(&pool)
.await?;
let count: i64 = row.get("n");
assert_eq!(count, 0);
Ok(())
}
Both tests pass together, in any order, because neither can see the other's database. Run them and check the database list afterwards. No test database remains, because both passed and the macro dropped both.
DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests" cargo test --test sqlx_test
test sqlx_test_gives_a_fresh_pool ... ok
test sqlx_test_second_test_sees_an_empty_table ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Fixtures for Shared Seed Data
A test that checks a read handler needs a row to read, and writing the same INSERT in every test gets repetitive. A fixture is a SQL file that inserts seed data, and the macro runs it after the migrations and before the test body. Fixtures are SQL scripts that work like migrations, except they only insert test data, and each test picks which ones it wants.
The fixture file lives in a fixtures folder next to the test file. For a test file at tests/sqlx_test.rs, the folder is tests/fixtures/, and the file is named after the fixture.
INSERT INTO users (name, email) VALUES ('Asha', 't11-fixture-asha@example.com');
The test names the fixture without the folder and without the extension. The macro resolves users to ./fixtures/users.sql, relative to the test file, and runs it.
#[sqlx::test(fixtures("users"))]
async fn sqlx_test_fixture_seeds_a_user(pool: PgPool) -> sqlx::Result<()> {
let row = sqlx::query("SELECT name FROM users WHERE email = $1")
.bind("t11-fixture-asha@example.com")
.fetch_one(&pool)
.await?;
let name: String = row.get("name");
assert_eq!(name, "Asha");
Ok(())
}
The row exists when the test body starts, because the fixture ran first. A second test without the fixture still sees an empty table, because fixtures are per test, not per project. Each test chooses its own seed data, and a test that needs none asks for none.
The macro supports three ways to name fixtures, and they can be mixed. The first passes fixture names, resolved as ./fixtures/{name}.sql. The second passes file paths with their extension, absolute or relative to the test file. The third passes a folder path plus a list of script names, resolved as {path}/{name}.sql.
// Fixture names, resolved under ./fixtures
#[sqlx::test(fixtures("users"))]
async fn names_form(pool: PgPool) -> sqlx::Result<()> {
Ok(())
}
// File paths with extensions, relative to this test file
#[sqlx::test(fixtures("./fixtures/users.sql"))]
async fn paths_form(pool: PgPool) -> sqlx::Result<()> {
Ok(())
}
// Folder path plus script names
#[sqlx::test(fixtures(path = "./fixtures", scripts("users")))]
async fn path_form(pool: PgPool) -> sqlx::Result<()> {
Ok(())
}
Fixtures run in the order they are listed. That order matters when one fixture depends on another, for example a posts fixture that references a user id the users fixture created. Each fixture is sent as one command string, so it runs inside its own implicit transaction. A fixture that fails leaves the database in place like any other failed test, so the rows can be inspected.
Fixtures Are Not Migrations:
A fixture runs only for the tests that name it, and it never runs for the application. A migration runs for every database the application touches. Seed data that the application needs belongs in a migration or in application code. Seed data that only a test needs belongs in a fixture.
Turning Migrations Off
A test that does not need the users table can skip migrations entirely. The migrations = false argument tells the macro to create the fresh database and stop there, and the test creates whatever it needs by hand.
use sqlx::Executor;
#[sqlx::test(migrations = false)]
async fn sqlx_test_without_migrations(pool: PgPool) -> sqlx::Result<()> {
let mut conn = pool.acquire().await?;
conn.execute("CREATE TABLE foo(bar text)").await?;
sqlx::query("INSERT INTO foo (bar) VALUES ($1)")
.bind("hello")
.execute(&mut *conn)
.await?;
let row = sqlx::query("SELECT bar FROM foo")
.fetch_one(&mut *conn)
.await?;
let bar: String = row.get("bar");
assert_eq!(bar, "hello");
Ok(())
}
The test acquires a connection from the pool, creates a small table, and uses it. The Executor trait import is what makes .execute() available on the connection. This form fits a test that checks one SQL idea in isolation, without the weight of the whole schema.
The migrations path can also be overridden. A project that keeps migrations in a different folder names it in the attribute, with the path relative to the crate root.
#[sqlx::test(migrations = "db/migrations")]
async fn custom_path(pool: PgPool) -> sqlx::Result<()> {
Ok(())
}
A project that already embeds its migrations in the library can name the migrator value instead. The migrator is a static built with sqlx::migrate!(), and the test refers to it by its full path.
// In src/db.rs
pub static MIGRATOR: Migrator = sqlx::migrate!();
// In the test
#[sqlx::test(migrator = "axum_project::db::MIGRATOR")]
async fn migrator_form(pool: PgPool) -> sqlx::Result<()> {
Ok(())
}
How the Macro Fits Together
The flow from attribute to assertion runs in a fixed order.
#[sqlx::test] on the function
|
v
Read DATABASE_URL, connect to the server
|
v
Create a fresh database for this one test
|
v
Run migrations from ./migrations in it
|
v
Run the named fixtures in order
|
v
Hand the test a PgPool for that database
|
v
Test body runs its queries and assertions
|
v
Pass: drop the database. Fail: leave it for inspection
The test body is the only part the developer writes. Everything above it is the macro, and everything below it is cleanup the macro does without being asked.
Testing the Macro
The test file for this page holds four tests. Two prove isolation, one proves fixtures, and one proves the migrations-off form. All four passed against Postgres 16.15 with sqlx 0.9.0.
DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests" cargo test --test sqlx_test
test sqlx_test_gives_a_fresh_pool ... ok
test sqlx_test_second_test_sees_an_empty_table ... ok
test sqlx_test_fixture_seeds_a_user ... ok
test sqlx_test_without_migrations ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
A check of the database list after the run shows no leftover test databases, because all four passed and the macro dropped each one.
Common Beginner Mistakes
Forgetting DATABASE_URL
// Wrong - running cargo test with no DATABASE_URL set
// error: DATABASE_URL must be set
The macro needs the variable at runtime to find the server, and it reads it through a helper that also looks in a .env file. The checked query macros need it at compile time to check SQL, when a project uses them. The error names the variable directly. The fix is the .env file or the exported variable from the last page.
Using a database user without CREATEDB
ERROR: permission denied to create database
The macro creates a database for every test, and a user that cannot create databases fails at that step. The fix is the privilege, not a code change. Run ALTER ROLE axumdocs CREATEDB; as a superuser and run the tests again.
Expecting the macro to roll back
// Wrong assumption - the macro does not wrap the test in a transaction
#[sqlx::test]
async fn my_test(pool: PgPool) -> sqlx::Result<()> {
// rows inserted here are not rolled back, the database is dropped instead
Ok(())
}
The macro isolates tests by giving each one a fresh database, not by rolling back a transaction. The effect looks similar, because the next test never sees the rows, but the mechanism is different. A test that needs a rollback inside one shared database uses the transaction technique from the rollback page, not this macro.
The Macro Needs the Migrate Feature:
Without the migrate feature on sqlx, the database management, the automatic migrations, and the fixtures all disappear, and the macro behaves like a plain async test. The compiler does not always say so clearly. If #[sqlx::test] creates no database and runs no migration, check the features list first. The migrate feature is the switch for the whole mechanism.
Naming a fixture that does not exist
// Wrong - there is no tests/fixtures/missing.sql
#[sqlx::test(fixtures("missing"))]
async fn my_test(pool: PgPool) -> sqlx::Result<()> {
Ok(())
}
The macro resolves fixture names to files at compile time, and a missing file fails the build. The fix is to check the file name and the folder. Fixtures for a test file in tests/ live in tests/fixtures/, not in a fixtures/ folder at the project root.
Sharing a pool between tests by hand
// Wrong - a static pool shared by tests defeats the macro
static POOL: OnceLock<PgPool> = OnceLock::new();
A shared pool means a shared database, and the macro's fresh database per test is wasted. The fix is to take the pool the macro hands to the test and use only that. The pool argument is the isolation, and working around it removes the isolation.
Final Complete Example
Everything on this page put together is one test file, one fixture, and the migration from the last page. The library code is unchanged, because the macro needs nothing from the application except the migrations folder.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "=0.9.0", features = ["runtime-tokio", "postgres", "macros", "derive", "migrate"] }
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
INSERT INTO users (name, email) VALUES ('Asha', 't11-fixture-asha@example.com');
use sqlx::{Executor, PgPool, Row};
#[sqlx::test]
async fn sqlx_test_gives_a_fresh_pool(pool: PgPool) -> sqlx::Result<()> {
let row = sqlx::query("SELECT COUNT(*) AS n FROM users")
.fetch_one(&pool)
.await?;
let count: i64 = row.get("n");
assert_eq!(count, 0);
sqlx::query("INSERT INTO users (name, email) VALUES ($1, $2)")
.bind("Asha")
.bind("t11-asha@example.com")
.execute(&pool)
.await?;
let row = sqlx::query("SELECT name FROM users WHERE email = $1")
.bind("t11-asha@example.com")
.fetch_one(&pool)
.await?;
let name: String = row.get("name");
assert_eq!(name, "Asha");
Ok(())
}
#[sqlx::test]
async fn sqlx_test_second_test_sees_an_empty_table(pool: PgPool) -> sqlx::Result<()> {
let row = sqlx::query("SELECT COUNT(*) AS n FROM users")
.fetch_one(&pool)
.await?;
let count: i64 = row.get("n");
assert_eq!(count, 0);
Ok(())
}
#[sqlx::test(fixtures("users"))]
async fn sqlx_test_fixture_seeds_a_user(pool: PgPool) -> sqlx::Result<()> {
let row = sqlx::query("SELECT name FROM users WHERE email = $1")
.bind("t11-fixture-asha@example.com")
.fetch_one(&pool)
.await?;
let name: String = row.get("name");
assert_eq!(name, "Asha");
Ok(())
}
#[sqlx::test(migrations = false)]
async fn sqlx_test_without_migrations(pool: PgPool) -> sqlx::Result<()> {
let mut conn = pool.acquire().await?;
conn.execute("CREATE TABLE foo(bar text)").await?;
sqlx::query("INSERT INTO foo (bar) VALUES ($1)")
.bind("hello")
.execute(&mut *conn)
.await?;
let row = sqlx::query("SELECT bar FROM foo")
.fetch_one(&mut *conn)
.await?;
let bar: String = row.get("bar");
assert_eq!(bar, "hello");
Ok(())
}
Run the file with the connection string set, and all four tests pass against a live Postgres 16.15 server.
DATABASE_URL="postgres://axumdocs:axumdocs@127.0.0.1:5432/ch19_tests" cargo test --test sqlx_test
Summary
The macro trades a little time for a lot of certainty. Creating a database per test is slower than sharing one, and the cost shows up on a large suite, but each test starts from the same blank state, and a test can never fail because of a row another test left behind. That trade is the right one while the suite is small and the tests are still being written, because a flaky test costs more time than a slow test.
The decision framework is short. If tests share one database and fail depending on order, reach for #[sqlx::test] and let each test own its database. If a test needs seed data, add a fixture instead of copying INSERT statements. If a test needs no schema at all, turn migrations off for that one test. And when the suite grows large enough that creating a database per test feels slow, the rollback technique is the faster isolation to reach for, because it reuses one database and undoes each test's work instead of throwing the database away.