aidaemon_store_sqlite/
maintenance.rs1use std::path::Path;
19
20use sqlx::SqlitePool;
21
22use crate::Error;
23
24pub const ANALYSIS_LIMIT: u32 = 1000;
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum Optimize {
32 AtOpen,
35 Periodic,
38}
39
40pub async fn optimize(pool: &SqlitePool, when: Optimize) -> Result<(), Error> {
46 let mut connection = pool.acquire().await?;
49 sqlx::query(sqlx::AssertSqlSafe(format!(
50 "PRAGMA analysis_limit = {ANALYSIS_LIMIT}"
51 )))
52 .execute(&mut *connection)
53 .await?;
54 let statement = match when {
55 Optimize::AtOpen => "PRAGMA optimize = 0x10002",
56 Optimize::Periodic => "PRAGMA optimize",
57 };
58 sqlx::query(statement).execute(&mut *connection).await?;
59 Ok(())
60}
61
62pub async fn snapshot(pool: &SqlitePool, destination: &Path) -> Result<(), Error> {
69 let destination = destination
70 .to_str()
71 .ok_or_else(|| sqlx::Error::Configuration("snapshot path is not valid UTF-8".into()))?;
72 sqlx::query("VACUUM INTO ?")
73 .bind(destination)
74 .execute(pool)
75 .await?;
76 Ok(())
77}
78
79#[cfg(test)]
80mod tests {
81 use super::*;
82 use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions};
83
84 async fn file_pool(path: &Path) -> SqlitePool {
85 SqlitePoolOptions::new()
86 .max_connections(4)
87 .connect_with(
88 SqliteConnectOptions::new()
89 .filename(path)
90 .create_if_missing(true)
91 .journal_mode(SqliteJournalMode::Wal),
92 )
93 .await
94 .unwrap()
95 }
96
97 #[tokio::test]
98 async fn optimize_gathers_statistics_for_an_indexed_table() {
99 let dir = tempfile::tempdir().unwrap();
100 let pool = file_pool(&dir.path().join("a.db")).await;
101 sqlx::query("CREATE TABLE items (id INTEGER PRIMARY KEY, kind TEXT)")
102 .execute(&pool)
103 .await
104 .unwrap();
105 sqlx::query("CREATE INDEX items_kind ON items(kind)")
106 .execute(&pool)
107 .await
108 .unwrap();
109 for i in 0..2000 {
110 sqlx::query("INSERT INTO items (kind) VALUES (?)")
111 .bind(format!("kind-{}", i % 7))
112 .execute(&pool)
113 .await
114 .unwrap();
115 }
116 optimize(&pool, Optimize::AtOpen).await.unwrap();
117 let analyzed: i64 =
118 sqlx::query_scalar("SELECT COUNT(*) FROM sqlite_stat1 WHERE tbl = 'items'")
119 .fetch_one(&pool)
120 .await
121 .unwrap();
122 assert!(analyzed > 0, "optimize should have analyzed items");
123 optimize(&pool, Optimize::Periodic).await.unwrap();
124 }
125
126 #[tokio::test]
127 async fn snapshot_includes_uncheckpointed_writes() {
128 let dir = tempfile::tempdir().unwrap();
129 let pool = file_pool(&dir.path().join("live.db")).await;
130 sqlx::query("CREATE TABLE notes (body TEXT)")
131 .execute(&pool)
132 .await
133 .unwrap();
134 sqlx::query("INSERT INTO notes VALUES ('synthetic note')")
135 .execute(&pool)
136 .await
137 .unwrap();
138 let copy = dir.path().join("copy.db");
139 snapshot(&pool, ©).await.unwrap();
140
141 let copy_pool = file_pool(©).await;
142 let body: String = sqlx::query_scalar("SELECT body FROM notes")
143 .fetch_one(©_pool)
144 .await
145 .unwrap();
146 assert_eq!(body, "synthetic note");
147 assert!(snapshot(&pool, ©).await.is_err(), "never overwrites");
148 }
149}