expression

Diesel: map rows with Queryable and Selectable

A Rust result struct can describe the fields to decode. Selectable supplies a selection matching the field mapping; Queryable decodes the result. The backend check attribute improves diagnostics for field type mismatches. This does not ensure the real database has the declared columns. Uses a disposable in-memory SQLite database. Expected stdout (not executed): 2: Book (blue) Common mistake: Relying on an implicit column order after changing the Rust model or actual SQL schema.

Formal Syntax & Structure

rust syntaxrust
#[derive(Queryable, Selectable)] struct Item { ... }

Working Example

Example Snippetrust
use diesel::prelude::*;use diesel::sqlite::SqliteConnection;
diesel::table! {    items (id) {        id -> Integer,        label -> Text,        note -> Nullable<Text>,    }}
fn sample_db() -> Result<SqliteConnection, Box<dyn std::error::Error>> {    let mut conn = SqliteConnection::establish(":memory:")?;    diesel::sql_query("CREATE TABLE items (id INTEGER PRIMARY KEY, label TEXT NOT NULL, note TEXT)")        .execute(&mut conn)?;    diesel::insert_into(items::table)        .values((items::id.eq(1), items::label.eq("Pen")))        .execute(&mut conn)?;    diesel::insert_into(items::table)        .values((items::id.eq(2), items::label.eq("Book"), items::note.eq(Some("blue"))))        .execute(&mut conn)?;    Ok(conn)}
fn main() -> Result<(), Box<dyn std::error::Error>> {    #[derive(Queryable, Selectable)]    #[diesel(table_name = items)]    #[diesel(check_for_backend(diesel::sqlite::Sqlite))]    struct Item { id: i32, label: String, note: Option<String> }    let mut conn = sample_db()?;    let row = items::table.find(2).select(Item::as_select()).first(&mut conn)?;    println!("{}: {} ({})", row.id, row.label, row.note.as_deref().unwrap_or("none"));    Ok(())}
Rust Reference