expression
SQLx QueryBuilder: optional filters
Build the shape of a query from fixed SQL fragments. Append a condition only if the optional filter exists, and bind its value instead of inserting it into SQL text. This offline example inspects SQL, not the result of execution. No database connection is required by this example. Expected stdout (not executed): SELECT id FROM items WHERE TRUE AND category = $1 ORDER BY id Common mistake: Using push() for untrusted filter values.
Formal Syntax & Structure
rust syntaxrust
QueryBuilder::<Postgres>::new(sql).push_bind(value)Working Example
Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), Box<dyn std::error::Error>> { use sqlx::{Postgres, QueryBuilder}; let category = Some("O'Neil"); let mut q = QueryBuilder::<Postgres>::new("SELECT id FROM items WHERE TRUE"); if let Some(value) = category { q.push(" AND category = ").push_bind(value); } q.push(" ORDER BY id"); println!("{}", q.sql()); Ok(())}