expression
SQLx: choose an allowed query shape
Bind values, but choose identifiers and ordering from trusted fixed query strings. PostgreSQL parameters cannot stand in for arbitrary SQL keywords or table names. The offline example maps an accepted sort choice to a known statement and binds a limit. No database connection is required by this example. Expected stdout (not executed): SELECT name FROM item ORDER BY name, id LIMIT $1 Common mistake: Passing a raw request parameter into ORDER BY using format!.
Formal Syntax & Structure
rust syntaxrust
let sql = match sort { ... }; sqlx::query::<Postgres>(sql).bind(value);Working Example
Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), Box<dyn std::error::Error>> { use sqlx::{Execute, Postgres}; let sort = "name"; let sql = match sort { "name" => "SELECT name FROM item ORDER BY name, id LIMIT $1", "id" => "SELECT name FROM item ORDER BY id LIMIT $1", _ => return Err("unsupported sort".into()), }; let q = sqlx::query::<Postgres>(sql).bind(10_i64); println!("{}", q.sql()); Ok(())}