expression
SQLite: roll back a failed schema migration
Ordinary SQLite table creation and application version changes can be rolled back together. The example deliberately fails a later statement and explicitly rolls back. Not all administrative operations are valid inside a transaction; migration scripts must be reviewed individually. Run in the accompanying Cargo project. Expected stdout (not executed): version: 0; tables: 0 Common mistake: Assuming an SQL batch automatically undoes earlier successful statements without an explicit transaction.
Formal Syntax & Structure
rust syntaxrust
tx.execute_batch(migration_sql)?; tx.commit()?;Working Example
Example Snippetrust
fn main() -> Result<(), Box<dyn std::error::Error>> { let mut db = rusqlite::Connection::open_in_memory()?; let tx = db.transaction()?; tx.execute_batch("CREATE TABLE item (id INTEGER); PRAGMA user_version = 1;")?; let failure = tx.execute("INSERT INTO missing VALUES (1)", []); assert!(failure.is_err()); tx.rollback()?; let version: i64 = db.query_row("PRAGMA user_version", [], |r| r.get(0))?; let tables: i64 = db.query_row("SELECT COUNT(*) FROM sqlite_schema WHERE name = 'item'", [], |r| r.get(0))?; println!("version: {version}; tables: {tables}"); Ok(())}