flawopen.com/SQL Injection in Rust/sqlx

Does sqlx's compile-time query checking prevent SQL injection?

Reference page — draft, pending review
Short answer

It validates that a parameterized query's shape matches your real database schema — it doesn't retroactively make an unparameterized, format!-built query safe.

UNSAFE — format! first, then query
let q = format!(
  "SELECT * FROM users WHERE id = {}",
  user_id
);
sqlx::query(&q).fetch_one(&pool).await?
SAFE — sqlx::query! macro
sqlx::query!(
  "SELECT * FROM users WHERE id = ?",
  user_id
).fetch_one(&pool).await?

What the compile-time check actually validates

query! connects to your database at compile time (or uses a cached schema) to confirm the query is syntactically valid and its parameter/result types match your Rust types. This catches typos and schema drift — it has nothing to do with whether the query string was built safely in the first place. Building the string with format! before passing it to a non-macro query() call sidesteps the check entirely.

How to check your codebase

grep -rn "format!(" --include="*.rs" . | grep -B2 "sqlx::query"

FAQ

Should I always use the query! macro over query()?

Prefer it when possible — it gets you both the compile-time schema check and forces the parameterized form, closing off the format!-first mistake by construction.

References