sqlx Offline Mode for Tests

2025-07-03

I've been using sqlx as my main DB client in Rust for my personal projects.

And today I needed to add some tests that would interact with the DB. I'd been trying to do more integration tests, without reading the DB directly, but to test a certain bug it was the best way to go.

I had a #[tokio::test] that would connect to the DB and run the specs. It was working great locally, but in CI it was failing to compile since sqlx didn't know about the queries in the test files, as they were not in the .sqlx files that the CLI generated.

Running cargo sqlx prepare --workspace --all was NOT enough to get it to 'see' the test queries.

The fix was to run the following

cargo sqlx prepare --workspace --all -- --all-targets

The -- --all-targets is the magic flag that sqlx passes to Cargo, and the --all-targets will build the tests and docs, as well as the main project.

TLDR: So now I added a scripts/sqlx.sh script that simply runs cargo sqlx prepare --workspace --all -- --all-targets.

Bonus content! I also found out about #[sqlx::test] which does all the testing DB setup and tear down for me! Was able to remove a good chunk of test setup code when I found this macro today.

coreyja weekly

My weekly newsletter tailored at developers who are eager to grow with me!
Every week will be unique, but expect topics focusing around Web Development and Rust