FAQ - Help and questions

How does the sqlx query! macro check SQL at compile time, and what does it need?

#sqlx#database#compile-time#macrospublished 0 replies5 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

query! sends your SQL to a real database while compiling, so it needs DATABASE_URL (a .env file works) pointing at a database with the current schema. In return, wrong column names fail the build and result columns get Rust types. Offline mode lets builds run without that database.

Checked with rustc 1.93.0, sqlx 0.8.6 with macros and migrate (SQLite), Windows 11; DATABASE_URL=sqlite:dev.db in a .env file next to Cargo.toml

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

text
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.)

src/main.rsrust
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(())
}
text
1 write docs false

r.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:

text
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_URL at build time, in the environment or in a .env file (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, running cargo sqlx prepare to write a .sqlx folder that you commit, and building without DATABASE_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_URL while 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. query and query_as (used in the other threads) are checked only at run time and need no database to compile.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet