[][src]Macro sqlx::query_as

macro_rules! query_as {
    ($out_struct:path, $query:literal) => { ... };
    ($out_struct:path, $query:literal, $($args:expr),*) => { ... };
}

A variant of query! which takes a path to an explicitly defined struct as the output type.

This lets you return the struct from a function or add your own trait implementations.

No trait implementations are required; the macro maps rows using a struct literal where the names of columns in the query are expected to be the same as the fields of the struct (but the order does not need to be the same). The types of the columns are based on the query and not the corresponding fields of the struct, so this is type-safe as well.

This enforces a few things:

  • The query must output at least one column.
  • The column names of the query must match the field names of the struct.
  • Neither the query nor the struct may have unused fields.

The only modification to the syntax is that the struct name is given before the SQL string:

#[derive(Debug)]
struct Account {
    id: i32,
    name: String
}

// let mut conn = <impl sqlx::Executor>;
let account = sqlx::query_as!(
        Account,
        "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);