expression
Diesel: nested transaction and savepoint
On SQLite, a nested Diesel transaction uses a savepoint. Rolling back the inner unit can preserve outer work when the outer closure handles the expected inner error and commits successfully. This is not a second independent connection. Uses a disposable in-memory SQLite database. Expected stdout (not executed): Ada updated; books: 3 Common mistake: Assuming an inner success commits independently of an outer rollback.
Formal Syntax & Structure
rust syntaxrust
tx.transaction::<(), diesel::result::Error, _>(|inner| { ... })Working Example
Example Snippetrust
use diesel::prelude::*;use diesel::sqlite::SqliteConnection;
diesel::table! { authors (id) { id -> Integer, name -> Text, }}diesel::table! { books (id) { id -> Integer, author_id -> Integer, title -> Text, }}diesel::joinable!(books -> authors (author_id));diesel::allow_tables_to_appear_in_same_query!(authors, books);
#[derive(Queryable, Identifiable)]#[diesel(table_name = authors)]struct Author { id: i32, name: String }#[derive(Queryable, Identifiable, Associations)]#[diesel(table_name = books)]#[diesel(belongs_to(Author))]struct Book { id: i32, author_id: i32, title: String }
fn sample_db() -> Result<SqliteConnection, Box<dyn std::error::Error>> { let mut conn = SqliteConnection::establish(":memory:")?; diesel::sql_query("PRAGMA foreign_keys = ON").execute(&mut conn)?; diesel::sql_query("CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT NOT NULL)").execute(&mut conn)?; diesel::sql_query("CREATE TABLE books (id INTEGER PRIMARY KEY, author_id INTEGER NOT NULL REFERENCES authors(id), title TEXT NOT NULL)").execute(&mut conn)?; diesel::sql_query("INSERT INTO authors VALUES (1, 'Ada'), (2, 'Lin'), (3, 'Sam')").execute(&mut conn)?; diesel::sql_query("INSERT INTO books VALUES (1, 1, 'One'), (2, 1, 'Two'), (3, 2, 'Three')").execute(&mut conn)?; Ok(conn)}
fn main() -> Result<(), Box<dyn std::error::Error>> { let mut conn = sample_db()?; conn.transaction::<_, diesel::result::Error, _>(|tx| { diesel::update(authors::table.find(1)).set(authors::name.eq("Ada updated")).execute(tx)?; let inner = tx.transaction::<(), diesel::result::Error, _>(|inner| { diesel::delete(books::table.find(1)).execute(inner)?; Err(diesel::result::Error::RollbackTransaction) }); match inner { Err(diesel::result::Error::RollbackTransaction) => Ok(()), other => other, } })?; let name: String = authors::table.find(1).select(authors::name).first(&mut conn)?; let n: i64 = books::table.count().get_result(&mut conn)?; println!("{name}; books: {n}"); Ok(())}