Skip to main content

query

Macro query 

Source
query!() { /* proc-macro */ }
Expand description

Validate a SQL query against PostgreSQL at compile time and generate typed Rust code for executing it.

§Syntax

bsql::query! {
    SELECT column1, column2
    FROM table
    WHERE column1 = $param_name: RustType
}

Parameters are declared inline as $name: Type. The macro replaces them with positional $1, $2, … and verifies type compatibility against the database schema.

§Execution methods

The macro returns an executor with these methods:

  • .fetch_all(executor) — returns all rows as Vec<T>
  • .fetch_one(executor) — returns exactly one row (errors on 0 or 2+)
  • .fetch_optional(executor) — returns Option<T> (errors on 2+)
  • .execute(executor) — returns affected row count (u64)

§Compile-time guarantees

  • Table and column names are verified against the live database
  • Parameter types are checked against PostgreSQL’s expected types
  • Nullable columns are automatically mapped to Option<T>
  • Invalid SQL produces a compile error, not a runtime error