Skip to main content

aidaemon_store_sqlite/
maintenance.rs

1//! Upkeep for a long-lived SQLite database: query-planner statistics and
2//! consistent snapshots.
3//!
4//! Both work on any pool, so an application that keeps its own tables in the
5//! same file as the run store (as the aidaemon daemon does) maintains the
6//! whole file with one call.
7//!
8//! ```no_run
9//! # async fn demo(pool: sqlx::SqlitePool) -> Result<(), aidaemon_store_sqlite::Error> {
10//! use aidaemon_store_sqlite::maintenance::{optimize, snapshot, Optimize};
11//!
12//! optimize(&pool, Optimize::AtOpen).await?;       // once, after migrations
13//! optimize(&pool, Optimize::Periodic).await?;     // every few hours
14//! snapshot(&pool, "backups/app.db".as_ref()).await?;
15//! # Ok(()) }
16//! ```
17
18use std::path::Path;
19
20use sqlx::SqlitePool;
21
22use crate::Error;
23
24/// Rows sampled per index when statistics are gathered. Bounds the cost of
25/// an analysis on a large table to milliseconds, as SQLite recommends for
26/// `PRAGMA optimize`; the estimates stay good enough to pick indexes.
27pub const ANALYSIS_LIMIT: u32 = 1000;
28
29/// When [`optimize`] runs.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum Optimize {
32    /// Right after opening and migrating: examines every table, including
33    /// ones never queried yet on this connection (`PRAGMA optimize=0x10002`).
34    AtOpen,
35    /// On a timer while the database is in use: refreshes statistics only
36    /// for tables whose size changed a lot since they were last analyzed.
37    Periodic,
38}
39
40/// Gather the query planner's statistics where they are missing or stale.
41///
42/// Without them SQLite picks indexes by rule of thumb, which goes wrong on
43/// tables that have grown unevenly. The pass is bounded by
44/// [`ANALYSIS_LIMIT`], and when nothing changed it does nothing.
45pub async fn optimize(pool: &SqlitePool, when: Optimize) -> Result<(), Error> {
46    // Both pragmas must run on the same connection: analysis_limit is
47    // per connection.
48    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
62/// Write a consistent, compacted copy of the database to `destination` with
63/// `VACUUM INTO`, while other connections keep reading and writing.
64///
65/// Unlike copying the file, the copy includes what is still in the WAL and
66/// never catches a half-written page. With SQLCipher the copy is encrypted
67/// with the source's key. `destination` must not exist.
68pub 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, &copy).await.unwrap();
140
141        let copy_pool = file_pool(&copy).await;
142        let body: String = sqlx::query_scalar("SELECT body FROM notes")
143            .fetch_one(&copy_pool)
144            .await
145            .unwrap();
146        assert_eq!(body, "synthetic note");
147        assert!(snapshot(&pool, &copy).await.is_err(), "never overwrites");
148    }
149}