ORM-08: Add Database::transaction with savepoint nesting #8

Closed
opened 2026-10-13 12:49:39 +01:00 by NoctisWolfshadow · 1 comment
Owner

Depends on: #6

Context

Model calls inside a transaction closure use the ambient connection, so nested model calls must work. rusqlite's Transaction needs &mut Connection, which would block that. Instead the transaction is driven with explicit SQL through &Connection, with a thread-local depth counter: the outermost call is a real transaction, nested calls are savepoints.

Tasks

  • Database::transaction(|| -> Result<T>) -> Result<T>. Outermost: BEGIN IMMEDIATE / COMMIT / ROLLBACK. Nested: SAVEPOINT sp{n} / RELEASE / ROLLBACK TO + RELEASE.
  • Panic safety: a guard whose Drop rolls back unless the closure completed.
  • Database::transaction_depth() -> usize (#11 needs it).

Example

Database::transaction(|| {
    let mut user = User::new("dana", None, 28, true);
    user.save()?;

    // Becomes SAVEPOINT sp1. The error rolls back only the inner work.
    let inner: Result<()> = Database::transaction(|| {
        Post::create(Post::new(user.id, "draft", false))?;
        Err(Error::NotFound)
    });
    assert!(inner.is_err());

    Ok(()) // dana is committed, the draft post is not
})?;

SQL sent for the example above:

BEGIN IMMEDIATE
  INSERT INTO users ...
  SAVEPOINT sp1
    INSERT INTO posts ...
  ROLLBACK TO sp1
  RELEASE sp1
COMMIT
#[test]
fn a_panic_rolls_back_and_leaves_the_thread_usable() {
    Database::connect_thread(Config::memory()).unwrap();
    Database::execute_batch("CREATE TABLE t (id INTEGER)").unwrap();

    let r = std::panic::catch_unwind(|| {
        Database::transaction(|| {
            Database::execute("INSERT INTO t VALUES (1)", [])?;
            panic!("boom");
            #[allow(unreachable_code)]
            Ok(())
        })
    });
    assert!(r.is_err());

    let n: i64 = Database::with(|c| c.query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0))).unwrap();
    assert_eq!(n, 0);
    assert_eq!(Database::transaction_depth(), 0);
}

Acceptance criteria

  • Ok commits; Err rolls back.
  • A caught panic rolls back and the depth counter returns to 0.
  • An inner Err handled by the outer closure rolls back only the inner work.
  • An outer Err undoes a successful inner call.
  • The closure's return value is passed through.
**Depends on:** #6 ## Context Model calls inside a transaction closure use the ambient connection, so nested model calls must work. rusqlite's `Transaction` needs `&mut Connection`, which would block that. Instead the transaction is driven with explicit SQL through `&Connection`, with a thread-local depth counter: the outermost call is a real transaction, nested calls are savepoints. ## Tasks - [ ] `Database::transaction(|| -> Result<T>) -> Result<T>`. Outermost: `BEGIN IMMEDIATE` / `COMMIT` / `ROLLBACK`. Nested: `SAVEPOINT sp{n}` / `RELEASE` / `ROLLBACK TO` + `RELEASE`. - [ ] Panic safety: a guard whose `Drop` rolls back unless the closure completed. - [ ] `Database::transaction_depth() -> usize` (#11 needs it). ## Example ```rust Database::transaction(|| { let mut user = User::new("dana", None, 28, true); user.save()?; // Becomes SAVEPOINT sp1. The error rolls back only the inner work. let inner: Result<()> = Database::transaction(|| { Post::create(Post::new(user.id, "draft", false))?; Err(Error::NotFound) }); assert!(inner.is_err()); Ok(()) // dana is committed, the draft post is not })?; ``` SQL sent for the example above: ``` BEGIN IMMEDIATE INSERT INTO users ... SAVEPOINT sp1 INSERT INTO posts ... ROLLBACK TO sp1 RELEASE sp1 COMMIT ``` ```rust #[test] fn a_panic_rolls_back_and_leaves_the_thread_usable() { Database::connect_thread(Config::memory()).unwrap(); Database::execute_batch("CREATE TABLE t (id INTEGER)").unwrap(); let r = std::panic::catch_unwind(|| { Database::transaction(|| { Database::execute("INSERT INTO t VALUES (1)", [])?; panic!("boom"); #[allow(unreachable_code)] Ok(()) }) }); assert!(r.is_err()); let n: i64 = Database::with(|c| c.query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0))).unwrap(); assert_eq!(n, 0); assert_eq!(Database::transaction_depth(), 0); } ``` ## Acceptance criteria - [ ] Ok commits; Err rolls back. - [ ] A caught panic rolls back and the depth counter returns to 0. - [ ] An inner Err handled by the outer closure rolls back only the inner work. - [ ] An outer Err undoes a successful inner call. - [ ] The closure's return value is passed through.
Author
Owner

Not needed because of the Database Interface changes and reworks.

Not needed because of the Database Interface changes and reworks.
Sign in to join this conversation.
No description provided.