macro_rules! sql {
($query:expr) => { ... };
}Expand description
Convert SQL with ? placeholders to the active backend’s placeholder style.
SQLite: returns the input &str directly — zero allocation, zero runtime cost.
PostgreSQL: rewrites ? to $1, $2, … and ?N (SQLite’s numbered
placeholder, e.g. ?1) to $N using rewrite_placeholders. Repeated
references to the same ?N collapse to the same $N. The rewrite runs at
most once per call site: the result is memoized in a call-site-local
LazyLock<String>, so a query executed in a loop or on a hot path incurs
the rewrite cost once per process lifetime rather than once per execution.
This requires $query to be a compile-time-constant expression (in
practice, always a string literal at every call site in this workspace) —
the closure passed to LazyLock::new captures $query and runs exactly
once, so a runtime-varying $query would silently freeze at its
first-seen value. Do NOT wrap PostgreSQL JSONB queries using ?/?|/?&
operators through this macro; use $N placeholders directly for those.
§Example
let rows = sqlx::query(sql!("SELECT id FROM messages WHERE conversation_id = ?"))
.bind(cid)
.fetch_all(&pool)
.await?;