use anyhow::Result; use include_dir::{include_dir, Dir}; use lazy_static::lazy_static; use rusqlite::Connection; use rusqlite_migration::{Migrations, M};
static MIGRATIONS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations");
// Update the database schema, atomically MIGRATIONS.to_latest(&mut conn)?;
// Apply some PRAGMA. These are often better applied outside of migrations, as some needs to be // executed for each connection (like `foreign_keys`) or to be executed outside transactions // (`journal_mode` is a noop in a transaction). conn.pragma_update(None, "journal_mode", "WAL").unwrap(); conn.pragma_update(None, "foreign_keys", "ON").unwrap();
Ok(conn) }
// Test that migrations are working #[cfg(test)] mod tests { use super::*;
use crate::entity::person::Person; use crate::storage::migration::init_db; use crate::storage::person::{add_person, get_persons}; use boost_rs::logger; use boost_rs::logger::log::info;
[DEBUG]: rusqlite_migration - some migrations defined, try to migrate [DEBUG]: rusqlite_migration - some migrations to run, target_db_version: 1, current_version: 0 [TRACE]: rusqlite_migration - start migration transaction [DEBUG]: rusqlite_migration - Running: CREATE TABLE person ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER NOT NULL DEFAULT 0, data BLOB );
[TRACE]: rusqlite_migration - set user version to: 1 [TRACE]: rusqlite_migration - commited migration transaction [ INFO]: rusqlite_migration - Database migrated to version 1 [ INFO]: rust_learn - Ok([Person { id: 1, name: "John", age: 18, data: Some([116, 101, 115, 116]) }])
再次执行一次:
1 2 3
[DEBUG]: rusqlite_migration - some migrations defined, try to migrate [DEBUG]: rusqlite_migration - no migration to run, db already up to date [ INFO]: rust_learn - Ok([Person { id: 1, name: "John", age: 18, data: Some([116, 101, 115, 116]) }, Person { id: 2, name: "John", age: 18, data: Some([116, 101, 115, 116]) }])