expression

Diesel: insert a typed record

An insert model can contain only the fields needed to create a row. Its borrowed label does not require an owned String. This example omits the nullable note, which becomes NULL under the fixture schema. In a real schema, defaults and required fields must match the migration. Uses a disposable in-memory SQLite database. Expected stdout (not executed): inserted 1: Cup Common mistake: Using a full read model for every insert even when fields are generated by the database.

Formal Syntax & Structure

rust syntaxrust
#[derive(Insertable)] struct NewItem<'a> { ... }

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(Insertable)]    #[diesel(table_name = items)]    struct NewItem<'a> { id: i32, label: &'a str }    let mut conn = sample_db()?;    let count = diesel::insert_into(items::table).values(NewItem { id: 3, label: "Cup" }).execute(&mut conn)?;    let label: String = items::table.find(3).select(items::label).first(&mut conn)?;    println!("inserted {count}: {label}");    Ok(())}
Rust Reference