Skip to main content

reifydb_sqlite/
pragma.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4use rusqlite::{Connection, ToSql};
5
6use crate::{
7	SqliteConfig,
8	error::{SqliteError, SqliteResult},
9};
10
11/// Apply the pragmas carried by `config` plus `auto_vacuum=INCREMENTAL` to `conn`.
12/// Returns on the first failing pragma.
13pub fn apply(conn: &Connection, config: &SqliteConfig) -> SqliteResult<()> {
14	set(conn, "page_size", config.page_size)?;
15	set(conn, "journal_mode", config.journal_mode.as_str())?;
16	set(conn, "synchronous", config.synchronous_mode.as_str())?;
17	set(conn, "temp_store", config.temp_store.as_str())?;
18	set(conn, "auto_vacuum", "INCREMENTAL")?;
19	set(conn, "cache_size", -(config.cache_size as i32))?;
20	set(conn, "wal_autocheckpoint", config.wal_autocheckpoint)?;
21	set(conn, "mmap_size", config.mmap_size as i64)?;
22	Ok(())
23}
24
25/// Run `PRAGMA incremental_vacuum` to return freed pages to the OS.
26pub fn incremental_vacuum(conn: &Connection) -> SqliteResult<()> {
27	let statement = "PRAGMA incremental_vacuum";
28	conn.execute(statement, []).map_err(|source| SqliteError::Execute {
29		statement: statement.into(),
30		source,
31	})?;
32	Ok(())
33}
34
35/// Release unused cache memory back to the allocator.
36pub fn shrink_memory(conn: &Connection) -> SqliteResult<()> {
37	set(conn, "shrink_memory", 0)
38}
39
40/// Explicitly checkpoint WAL and shrink the page cache.
41pub fn shutdown(conn: &Connection) -> SqliteResult<()> {
42	set(conn, "wal_checkpoint", "TRUNCATE")?;
43	set(conn, "cache_size", 0)?;
44	Ok(())
45}
46
47fn set<V: ToSql>(conn: &Connection, name: &str, value: V) -> SqliteResult<()> {
48	conn.pragma_update(None, name, value).map_err(|source| SqliteError::Pragma {
49		name: name.into(),
50		source,
51	})
52}