expression

SQLite: apply a versioned schema migration

A migration changes an existing schema deliberately. SQLite reserves an application-controlled integer for tracking schema revisions. Apply the schema change and record the new revision inside one transaction. This minimal example assumes exclusive migration ownership; real deployments need migration coordination and a backup strategy. Run in the accompanying Cargo project. Expected stdout (not executed): version: 0 -> 1 Common mistake: Recording the version before executing the migration outside a transaction.

Formal Syntax & Structure

rust syntaxrust
PRAGMA user_version; PRAGMA user_version = 1;

Working Example

Example Snippetrust
fn main() -> Result<(), Box<dyn std::error::Error>> {    let mut db = rusqlite::Connection::open_in_memory()?;    let tx = db.transaction()?;    let before: i64 = tx.query_row("PRAGMA user_version", [], |r| r.get(0))?;    if before == 0 {        tx.execute_batch("CREATE TABLE item (id INTEGER PRIMARY KEY); PRAGMA user_version = 1;")?;    }    tx.commit()?;    let after: i64 = db.query_row("PRAGMA user_version", [], |r| r.get(0))?;    println!("version: {before} -> {after}");    Ok(())}
Rust Reference