use std::path::Path;
use sqlx::SqlitePool;
use crate::Error;
pub const ANALYSIS_LIMIT: u32 = 1000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Optimize {
AtOpen,
Periodic,
}
pub async fn optimize(pool: &SqlitePool, when: Optimize) -> Result<(), Error> {
let mut connection = pool.acquire().await?;
sqlx::query(sqlx::AssertSqlSafe(format!(
"PRAGMA analysis_limit = {ANALYSIS_LIMIT}"
)))
.execute(&mut *connection)
.await?;
let statement = match when {
Optimize::AtOpen => "PRAGMA optimize = 0x10002",
Optimize::Periodic => "PRAGMA optimize",
};
sqlx::query(statement).execute(&mut *connection).await?;
Ok(())
}
pub async fn snapshot(pool: &SqlitePool, destination: &Path) -> Result<(), Error> {
let destination = destination
.to_str()
.ok_or_else(|| sqlx::Error::Configuration("snapshot path is not valid UTF-8".into()))?;
sqlx::query("VACUUM INTO ?")
.bind(destination)
.execute(pool)
.await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions};
async fn file_pool(path: &Path) -> SqlitePool {
SqlitePoolOptions::new()
.max_connections(4)
.connect_with(
SqliteConnectOptions::new()
.filename(path)
.create_if_missing(true)
.journal_mode(SqliteJournalMode::Wal),
)
.await
.unwrap()
}
#[tokio::test]
async fn optimize_gathers_statistics_for_an_indexed_table() {
let dir = tempfile::tempdir().unwrap();
let pool = file_pool(&dir.path().join("a.db")).await;
sqlx::query("CREATE TABLE items (id INTEGER PRIMARY KEY, kind TEXT)")
.execute(&pool)
.await
.unwrap();
sqlx::query("CREATE INDEX items_kind ON items(kind)")
.execute(&pool)
.await
.unwrap();
for i in 0..2000 {
sqlx::query("INSERT INTO items (kind) VALUES (?)")
.bind(format!("kind-{}", i % 7))
.execute(&pool)
.await
.unwrap();
}
optimize(&pool, Optimize::AtOpen).await.unwrap();
let analyzed: i64 =
sqlx::query_scalar("SELECT COUNT(*) FROM sqlite_stat1 WHERE tbl = 'items'")
.fetch_one(&pool)
.await
.unwrap();
assert!(analyzed > 0, "optimize should have analyzed items");
optimize(&pool, Optimize::Periodic).await.unwrap();
}
#[tokio::test]
async fn snapshot_includes_uncheckpointed_writes() {
let dir = tempfile::tempdir().unwrap();
let pool = file_pool(&dir.path().join("live.db")).await;
sqlx::query("CREATE TABLE notes (body TEXT)")
.execute(&pool)
.await
.unwrap();
sqlx::query("INSERT INTO notes VALUES ('synthetic note')")
.execute(&pool)
.await
.unwrap();
let copy = dir.path().join("copy.db");
snapshot(&pool, ©).await.unwrap();
let copy_pool = file_pool(©).await;
let body: String = sqlx::query_scalar("SELECT body FROM notes")
.fetch_one(©_pool)
.await
.unwrap();
assert_eq!(body, "synthetic note");
assert!(snapshot(&pool, ©).await.is_err(), "never overwrites");
}
}