/rusqlite_migration

↕️ Simple database schema migration library for rusqlite, written with performance in mind.

Primary LanguageRustApache License 2.0Apache-2.0

Rusqlite Migration

docs.rs Crates.io unsafe forbidden dependency status

Rusqlite Migration is a simple and performant schema migration library for rusqlite.

  • Performance:
    • Fast database opening: to keep track of the current migration state, most tools create one or more tables in the database. These tables require parsing by SQLite and are queried with SQL statements. This library uses the user_version value instead. It’s much lighter as it is just an integer at a fixed offset in the SQLite file.
    • Fast compilation: this crate is very small and does not use macros to define the migrations.
  • Simplicity: this crate strives for simplicity. Just define a set of SQL statements as strings in your Rust code. Add more SQL statements over time as needed. No external CLI required. Additionally, rusqlite_migration works especially well with other small libraries complementing rusqlite, like serde_rusqlite.

Example

Here, we define SQL statements to run with Migrations::new and run these (if necessary) with .to_latest().

use rusqlite::{params, Connection};
use rusqlite_migration::{Migrations, M};

// 1️⃣ Define migrations
let migrations = Migrations::new(vec![
    M::up("CREATE TABLE friend(name TEXT NOT NULL);"),
    // In the future, add more migrations here:
    //M::up("ALTER TABLE friend ADD COLUMN email TEXT;"),
]);

let mut conn = Connection::open_in_memory().unwrap();

// Apply some PRAGMA, often better to do it outside of migrations
conn.pragma_update(None, "journal_mode", &"WAL").unwrap();

// 2️⃣ Update the database schema, atomically
migrations.to_latest(&mut conn).unwrap();

// 3️⃣ Use the database 🥳
conn.execute("INSERT INTO friend (name) VALUES (?1)", params!["John"])
    .unwrap();

Please see the examples folder for more, in particular:

  • migrations with multiple SQL statements (using for instance r#"…" or include_str!(…))
  • use of lazy_static
  • migrations to previous versions (downward migrations)

I’ve also made a cheatsheet of SQLite pragma for improved performance and consistency.

Built-in tests

To test that the migrations are working, you can add this in your test module:

#[test]
fn migrations_test() {
    assert!(MIGRATIONS.validate().is_ok());
}

Contributing

Contributions (documentation or code improvements in particular) are welcome, see contributing!

Acknowledgments

I would like to thank all the contributors, as well as the authors of the dependencies this crate uses.