expression

Diesel table!: declare a typed schema

The table macro declares Rust query symbols and their expected SQL types. It is not a migration and does not create the database table. This fixture creates the real table separately using fixed SQL and selects one typed column. The declared schema and actual database schema must stay aligned. Uses a disposable in-memory SQLite database. Expected stdout (not executed): Pen, Book Common mistake: Assuming table! changes the physical schema or validates a deployed database during compilation.

Formal Syntax & Structure

rust syntaxrust
diesel::table! { items (id) { id -> Integer, label -> Text, note -> Nullable<Text>, } }

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>> {    let mut conn = sample_db()?;    let labels: Vec<String> = items::table.select(items::label).order(items::id).load(&mut conn)?;    println!("{}", labels.join(", "));    Ok(())}
Rust Reference