ORM-11: Implement Migrator::run() #11

Open
opened 2026-10-13 12:49:39 +01:00 by NoctisWolfshadow · 0 comments
Owner

Depends on: #8, #10

Context

run() applies pending migrations safely: each migration is atomic with its tracking row, history edits are refused, and two processes starting at the same time cannot both apply the same migration.

Tasks

  • Pre-flight: any Modified or Missing migration returns MigrationError::Drift { .. } and applies nothing.
  • For each pending migration in ascending order: BEGIN IMMEDIATE, execute_batch(up), insert the tracking row, COMMIT. Any failure rolls back and returns MigrationError::Failed { version, name, source }. IMMEDIATE stops two processes from both applying the same migration.
  • Return MigrationReport { applied: Vec<i64> }.
  • Return an error if called while Database::transaction_depth() > 0.

Example

fn main() -> tessera_orm::Result<()> {
    Database::connect(Config::file("app.db"))?;
    let report = Migrator::new(migrations()).run()?;
    println!("applied {:?}", report.applied); // applied [1, 2]
    Ok(())
}

Per-migration SQL sequence:

BEGIN IMMEDIATE
  <migration up SQL>
  INSERT INTO _tessera_migrations (version, name, checksum) VALUES (?, ?, ?)
COMMIT

Error messages (Display):

migration 2 (add_email) was modified after it was applied
migration 7 is recorded in the database but not in this build (the database is newer than the code)
migration 3 (create_posts) failed: near "THIS": syntax error
#[test]
fn a_failing_migration_leaves_no_partial_ddl() {
    Database::connect_thread(Config::memory()).unwrap();
    let list = MigrationList::new(vec![
        Migration::new(1, "ok", "CREATE TABLE a (id INTEGER);"),
        Migration::new(2, "broken", "CREATE TABLE b (id INTEGER); THIS IS NOT SQL;"),
    ])
    .unwrap();

    assert!(Migrator::new(list).run().is_err());

    // migration 1 stays applied; nothing of migration 2 exists or is recorded
    let tables: Vec<String> = Database::with(|c| {
        c.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('a', 'b')")?
            .query_map([], |r| r.get(0))?
            .collect()
    })
    .unwrap();
    assert_eq!(tables, ["a"]);
}

Acceptance criteria

  • A fresh apply works and a re-run is a no-op (applied is empty).
  • A failing migration leaves no partial DDL and no tracking row; earlier migrations stay applied.
  • Editing an applied migration gives a drift error and applies nothing.
  • A database with an applied version the code does not know gives a drift error.
  • Calling run() inside Database::transaction returns an error.
**Depends on:** #8, #10 ## Context `run()` applies pending migrations safely: each migration is atomic with its tracking row, history edits are refused, and two processes starting at the same time cannot both apply the same migration. ## Tasks - [ ] Pre-flight: any `Modified` or `Missing` migration returns `MigrationError::Drift { .. }` and applies nothing. - [ ] For each pending migration in ascending order: `BEGIN IMMEDIATE`, `execute_batch(up)`, insert the tracking row, `COMMIT`. Any failure rolls back and returns `MigrationError::Failed { version, name, source }`. `IMMEDIATE` stops two processes from both applying the same migration. - [ ] Return `MigrationReport { applied: Vec<i64> }`. - [ ] Return an error if called while `Database::transaction_depth() > 0`. ## Example ```rust fn main() -> tessera_orm::Result<()> { Database::connect(Config::file("app.db"))?; let report = Migrator::new(migrations()).run()?; println!("applied {:?}", report.applied); // applied [1, 2] Ok(()) } ``` Per-migration SQL sequence: ``` BEGIN IMMEDIATE <migration up SQL> INSERT INTO _tessera_migrations (version, name, checksum) VALUES (?, ?, ?) COMMIT ``` Error messages (`Display`): ``` migration 2 (add_email) was modified after it was applied migration 7 is recorded in the database but not in this build (the database is newer than the code) migration 3 (create_posts) failed: near "THIS": syntax error ``` ```rust #[test] fn a_failing_migration_leaves_no_partial_ddl() { Database::connect_thread(Config::memory()).unwrap(); let list = MigrationList::new(vec![ Migration::new(1, "ok", "CREATE TABLE a (id INTEGER);"), Migration::new(2, "broken", "CREATE TABLE b (id INTEGER); THIS IS NOT SQL;"), ]) .unwrap(); assert!(Migrator::new(list).run().is_err()); // migration 1 stays applied; nothing of migration 2 exists or is recorded let tables: Vec<String> = Database::with(|c| { c.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('a', 'b')")? .query_map([], |r| r.get(0))? .collect() }) .unwrap(); assert_eq!(tables, ["a"]); } ``` ## Acceptance criteria - [ ] A fresh apply works and a re-run is a no-op (`applied` is empty). - [ ] A failing migration leaves no partial DDL and no tracking row; earlier migrations stay applied. - [ ] Editing an applied migration gives a drift error and applies nothing. - [ ] A database with an applied version the code does not know gives a drift error. - [ ] Calling `run()` inside `Database::transaction` returns an error.
Sign in to join this conversation.
No description provided.