[][src]Macro sqlx::query

macro_rules! query {
    ($query:literal) => { ... };
    ($query:literal, $($args:tt)*) => { ... };
}

Statically checked SQL query with println!() style syntax.

This expands to an instance of QueryAs that outputs an ad-hoc anonymous struct type, if the query has output columns, or () (unit) otherwise:

// let mut conn = <impl sqlx::Executor>;
let account = sqlx::query!("select (1) as id, 'Herp Derpinson' as name")
    .fetch_one(&mut conn)
    .await?;

// anonymous struct has `#[derive(Debug)]` for convenience
println!("{:?}", account);
println!("{}: {}", account.id, account.name);

Query Arguments

Like println!() and the other formatting macros, you can add bind parameters to your SQL and this macro will typecheck passed arguments and error on missing ones:

// let mut conn = <impl sqlx::Executor>;
let account = sqlx::query!(
        // just pretend "accounts" is a real table
        "select * from (select (1) as id, 'Herp Derpinson' as name) accounts where id = ?",
        1i32
    )
    .fetch_one(&mut conn)
    .await?;

println!("{:?}", account);
println!("{}: {}", account.id, account.name);

Bind parameters in the SQL string are specific to the database backend:

  • Postgres: $N where N is the 1-based positional argument index
  • MySQL: ? which matches arguments in order that it appears in the query

Requirements

  • The DATABASE_URL environment variable must be set at build-time to point to a database server with the schema that the query string will be checked against. (All variants of query!() use dotenv so this can be in a .env file instead.)

  • The query must be a string literal or else it cannot be introspected (and thus cannot be dynamic or the result of another macro).

  • The QueryAs instance will be bound to the same database type as query!() was compiled against (e.g. you cannot build against a Postgres database and then run the query against a MySQL database).

    • The schema of the database URL (e.g. postgres:// or mysql://) will be used to determine the database type.

See Also