Answer#
sqlx::query! is checked while the program compiles. The macro connects to the database named by DATABASE_URL, asks it to prepare the statement, and generates a struct with one typed field per result column.
DATABASE_URL=sqlite:dev.db(That line is the whole .env file used here; dev.db had been created by running the migrations from the migrations thread.)
use sqlx::SqlitePool;
#[tokio::main]
async fn main() -> Result<(), sqlx::Error> {
let db = SqlitePool::connect("sqlite::memory:").await?;
sqlx::migrate!("./migrations").run(&db).await?;
sqlx::query("INSERT INTO todos (title) VALUES ('write docs')").execute(&db).await?;
// Checked at compile time against the database named in DATABASE_URL.
let rows = sqlx::query!("SELECT id, title, done FROM todos WHERE done = ?", false)
.fetch_all(&db)
.await?;
for r in rows {
let (id, title, done): (i64, String, bool) = (r.id, r.title, r.done); // the types come from the schema
println!("{id} {title} {done}");
}
Ok(())
}1 write docs falser.id is an i64, r.title a String and r.done a bool, taken from the schema, with no struct written by hand.
A typo is caught by the compiler. With SELECT id, titel FROM todos:
error: error returned from database: (code: 1) no such column: titel
--> examples\f33.rs:6:16
|
6 | let rows = sqlx::query!("SELECT id, titel FROM todos").fetch_all(&db).await?;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...(A second, follow-on error about type annotations was left out.)
What it needs#
DATABASE_URLat build time, in the environment or in a.envfile (the sqlx documentation says all variants of the macro read.env).- A database that already has the schema. Run your migrations on a development database first.
- Offline mode for machines without that database (CI, other developers). The documentation describes installing
sqlx-cli, runningcargo sqlx prepareto write a.sqlxfolder that you commit, and building withoutDATABASE_URL. This thread did not run that tool.
Common mistakes#
- Changing the schema and forgetting to update the development database: the build then checks against old columns.
- Setting
DATABASE_URLwhile building with the offline files and expecting them to be used: the documentation says to omit the variable in that case. - Expecting
query!to be required.queryandquery_as(used in the other threads) are checked only at run time and need no database to compile.
Related questions#
Which is better, query! or query_as?#
query! finds mistakes earlier but adds the build-time database. query_as is simpler to build and test. Both are fine.
Sources#
- sqlx,
query!: https://docs.rs/sqlx/0.8.6/sqlx/macro.query.html (read 2026-12-05)