SQLx verifies yourDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/launchbadge/sqlx/llms.txt
Use this file to discover all available pages before exploring further.
query!, query_as!, and related macros against the database at compile time. This is powerful, but it means a live database connection is ordinarily required to run cargo build. The cargo sqlx prepare command solves this by connecting to the database once, capturing the type information for every query in the project, and writing it to a .sqlx directory. Once that directory is committed to version control, the project can be built anywhere — including CI — without a database.
This command must be invoked as
cargo sqlx prepare, not sqlx prepare. Cargo passes the CARGO environment variable to the subprocess, which cargo sqlx prepare depends on to locate your project metadata.cargo sqlx prepare
Connects to the database, runscargo check against your project, and writes one query-*.json file per query! invocation to the .sqlx directory in the current package.
cargo sqlx prepare —workspace
For workspaces that contain multiple crates all using SQLx macros, pass--workspace to generate a single .sqlx directory at the workspace root rather than one per crate.
cargo sqlx prepare —check
Validates that the data in.sqlx is current. Exits with status 0 if everything is up to date and with status 1 if any query file is missing or differs from what would be generated against the current schema. Use this in CI to catch stale offline data.
Including feature-flagged queries
Queries guarded by Cargo feature flags or inside test modules are not compiled during a plaincargo check. Pass additional arguments after -- to forward them to Cargo:
query! invocation in the codebase is captured.
Building offline with SQLX_OFFLINE
WhenDATABASE_URL is set, SQLx defaults to verifying queries against the live database even if .sqlx is present. Set SQLX_OFFLINE=true to force the compiler to use only the cached metadata, regardless of whether a database URL is available:
.env file to make offline mode the default for all local builds:
.env
cargo sqlx prepare always connects to the database regardless of this variable, so your cached data stays fresh.
Committing .sqlx to version control
The.sqlx directory must be committed so that teammates and CI systems can build without a database. A typical workflow looks like this:
Commit the .sqlx directory
Add the generated files and commit them alongside the code change that introduced or modified a query:
Flags reference
| Flag | Description |
|---|---|
--workspace | Generate a single .sqlx directory at the workspace root |
--check | Exit non-zero if .sqlx is missing or out of date |
--all | Include queries in dependencies that live outside the current crate or workspace |
--database-url <URL> | Override DATABASE_URL for this invocation |
-- <CARGO ARGS> | Extra arguments forwarded to cargo rustc (e.g. --all-targets --all-features) |