expression

rusqlite: commit an atomic group of writes

A transaction groups changes into a unit. Commit only after every required operation succeeds. Here inventory moves from one location to another without changing the total. The mutable connection borrow prevents starting a second ordinary transaction through the same handle. Run in the accompanying Cargo project. Expected stdout (not executed): stock: 3, 3 Common mistake: Committing after the first update rather than after both. Real transfers must also check affected-row counts.

Formal Syntax & Structure

rust syntaxrust
let tx = db.transaction()?; ...; tx.commit()?;

Working Example

Example Snippetrust
fn main() -> Result<(), Box<dyn std::error::Error>> {    let mut db = rusqlite::Connection::open_in_memory()?;    db.execute_batch("CREATE TABLE stock (id INTEGER PRIMARY KEY, qty INTEGER CHECK(qty >= 0)); INSERT INTO stock VALUES (1, 5), (2, 1);")?;    let tx = db.transaction()?;    tx.execute("UPDATE stock SET qty = qty - 2 WHERE id = 1", [])?;    tx.execute("UPDATE stock SET qty = qty + 2 WHERE id = 2", [])?;    tx.commit()?;    let a: i64 = db.query_row("SELECT qty FROM stock WHERE id = 1", [], |r| r.get(0))?;    let b: i64 = db.query_row("SELECT qty FROM stock WHERE id = 2", [], |r| r.get(0))?;    println!("stock: {a}, {b}");    Ok(())}
Rust Reference