Compile-time checked SQL with sqlx offline mode
sqlx can check your SQL against a real database while the Rust code compiles. That catches typos and type mismatches before the program runs, but it creates a build problem.
The problem
The query! macros connect to the database named in DATABASE_URL at compile time. That works on your laptop. It fails on a CI runner or a hosting provider's build step, where no database is reachable.
Offline mode
Run cargo sqlx prepare locally while the database is up. sqlx writes the query metadata into a .sqlx directory. Commit that directory. Builds with SQLX_OFFLINE=true then read the saved metadata and never touch the network.
Keeping it honest
- Re-run
preparewhenever you change a query or a migration. - Use
cargo sqlx prepare --checkin CI so stale metadata fails the build. - Commit the
.sqlxfiles in the same change as the query edit.
Why I use it
My Rust backend template uses axum, sqlx and Postgres, and BillSplit's server came from it. Offline mode lets Render build the service without a database connection while I still get checked queries.