|
|
@@ -1,4 +1,5 @@
|
|
|
-use r2d2::Pool;
|
|
|
+use r2d2::{Pool, PooledConnection};
|
|
|
+use r2d2_sqlite::rusqlite::params;
|
|
|
use r2d2_sqlite::SqliteConnectionManager;
|
|
|
|
|
|
/// Create a configured rusqlite connection to a SQLite database.
|
|
|
@@ -14,16 +15,18 @@ pub fn create_sqlite_pool(
|
|
|
};
|
|
|
|
|
|
let manager = manager.with_init(move |conn| {
|
|
|
- // Apply pragmas
|
|
|
- conn.pragma_update(None, "busy_timeout", 5000)?;
|
|
|
- conn.pragma_update(None, "journal_mode", "wal")?;
|
|
|
- conn.pragma_update(None, "synchronous", "normal")?;
|
|
|
- conn.pragma_update(None, "temp_store", "memory")?;
|
|
|
- conn.pragma_update(None, "mmap_size", 30000000000i64)?;
|
|
|
- conn.pragma_update(None, "cache", "shared")?;
|
|
|
-
|
|
|
#[cfg(feature = "sqlcipher")]
|
|
|
- conn.pragma_update(None, "key", password.clone())?;
|
|
|
+ conn.execute_batch(&format!("pragma key = {};", password))?;
|
|
|
+
|
|
|
+ conn.execute_batch(
|
|
|
+ r#"
|
|
|
+ pragma journal_mode = WAL;
|
|
|
+ pragma synchronous = normal;
|
|
|
+ pragma temp_store = memory;
|
|
|
+ pragma mmap_size = 30000000000;
|
|
|
+ pragma cache = shared;
|
|
|
+ "#,
|
|
|
+ )?;
|
|
|
|
|
|
Ok(())
|
|
|
});
|
|
|
@@ -32,3 +35,38 @@ pub fn create_sqlite_pool(
|
|
|
.max_size(if is_memory { 1 } else { 20 })
|
|
|
.build(manager)
|
|
|
}
|
|
|
+
|
|
|
+/// Migrates the migration generated by `build.rs`
|
|
|
+pub fn migrate(
|
|
|
+ mut conn: PooledConnection<SqliteConnectionManager>,
|
|
|
+ migrations: &[(&str, &str)],
|
|
|
+) -> Result<(), r2d2_sqlite::rusqlite::Error> {
|
|
|
+ let tx = conn.transaction()?;
|
|
|
+ tx.execute(
|
|
|
+ r#"
|
|
|
+ CREATE TABLE IF NOT EXISTS migrations (
|
|
|
+ name TEXT PRIMARY KEY,
|
|
|
+ applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
|
+ )
|
|
|
+ "#,
|
|
|
+ [],
|
|
|
+ )?;
|
|
|
+
|
|
|
+ // Apply each migration if it hasn’t been applied yet
|
|
|
+ for (name, sql) in migrations {
|
|
|
+ let already_applied: bool = tx.query_row(
|
|
|
+ "SELECT EXISTS(SELECT 1 FROM migrations WHERE name = ?1)",
|
|
|
+ params![name],
|
|
|
+ |row| row.get(0),
|
|
|
+ )?;
|
|
|
+
|
|
|
+ if !already_applied {
|
|
|
+ tx.execute_batch(sql)?;
|
|
|
+ tx.execute("INSERT INTO migrations (name) VALUES (?1)", params![name])?;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ tx.commit()?;
|
|
|
+
|
|
|
+ Ok(())
|
|
|
+}
|