Skip to main content

sqlite_graphrag/
pragmas.rs

1//! SQLite PRAGMA helpers applied at connection open and on each transaction.
2
3use crate::errors::AppError;
4use rusqlite::Connection;
5
6pub fn apply_init_pragmas(conn: &Connection) -> Result<(), AppError> {
7    conn.execute_batch("PRAGMA auto_vacuum = INCREMENTAL;")?;
8    apply_connection_pragmas(conn)?;
9    conn.execute_batch(&format!(
10        "PRAGMA wal_autocheckpoint = {};",
11        crate::constants::WAL_AUTOCHECKPOINT_PAGES
12    ))?;
13    Ok(())
14}
15
16/// Re-asserts `PRAGMA journal_mode = WAL` after operations that may revert it
17/// (notably refinery-driven migrations, which can open internal handles that
18/// reset the journal mode in some scenarios). Idempotent and cheap; emits
19/// `tracing::warn!` if WAL fails to engage so degraded behaviour is observable.
20pub fn ensure_wal_mode(conn: &Connection) -> Result<(), AppError> {
21    let mode: String = conn.query_row("PRAGMA journal_mode = WAL;", [], |r| r.get(0))?;
22    if mode != "wal" {
23        tracing::warn!(mode = %mode, "journal_mode did not switch to WAL after re-assertion");
24    }
25    Ok(())
26}
27
28pub fn apply_connection_pragmas(conn: &Connection) -> Result<(), AppError> {
29    conn.execute_batch(&format!(
30        "PRAGMA synchronous   = NORMAL;
31         PRAGMA foreign_keys  = ON;
32         PRAGMA busy_timeout  = {busy};
33         PRAGMA cache_size    = {cache};
34         PRAGMA temp_store    = MEMORY;
35         PRAGMA mmap_size     = {mmap};",
36        busy = crate::constants::BUSY_TIMEOUT_MILLIS,
37        cache = crate::constants::CACHE_SIZE_KB,
38        mmap = crate::constants::MMAP_SIZE_BYTES,
39    ))?;
40    let mode: String = conn.query_row("PRAGMA journal_mode = WAL;", [], |r| r.get(0))?;
41    if mode != "wal" {
42        tracing::warn!(mode = %mode, "journal_mode did not switch to WAL");
43    }
44    Ok(())
45}