Skip to main content

ic_sqlite_vfs/db/
pragmas.rs

1//! Required SQLite PRAGMA setup.
2//!
3//! These settings keep rollback journal and temp storage in heap memory while the
4//! database image itself remains the only stable-memory payload.
5
6use crate::db::connection::Connection;
7use crate::db::DbError;
8
9pub fn apply_read_write(connection: &Connection, apply_page_size: bool) -> Result<(), DbError> {
10    if apply_page_size {
11        connection.execute_batch_nul_terminated(READ_WRITE_SQL)?;
12    } else {
13        connection.execute_batch_nul_terminated(READ_WRITE_EXISTING_SQL)?;
14    }
15    Ok(())
16}
17
18pub fn apply_read_only(connection: &Connection) -> Result<(), DbError> {
19    connection.execute_batch_nul_terminated(READ_ONLY_SQL)?;
20    Ok(())
21}
22
23const READ_WRITE_SQL: &[u8] = b"PRAGMA page_size = 16384;
24PRAGMA journal_mode = MEMORY;
25PRAGMA synchronous = OFF;
26PRAGMA temp_store = MEMORY;
27PRAGMA locking_mode = EXCLUSIVE;
28PRAGMA foreign_keys = ON;
29PRAGMA cache_size = -32768;\0";
30
31const READ_WRITE_EXISTING_SQL: &[u8] = b"PRAGMA journal_mode = MEMORY;
32PRAGMA synchronous = OFF;
33PRAGMA temp_store = MEMORY;
34PRAGMA locking_mode = EXCLUSIVE;
35PRAGMA foreign_keys = ON;
36PRAGMA cache_size = -32768;\0";
37
38const READ_ONLY_SQL: &[u8] = b"PRAGMA cache_size = -32768;
39PRAGMA query_only = ON;
40PRAGMA locking_mode = EXCLUSIVE;
41PRAGMA foreign_keys = ON;
42PRAGMA temp_store = MEMORY;\0";
43
44#[cfg(test)]
45mod tests {
46    use super::{READ_ONLY_SQL, READ_WRITE_EXISTING_SQL, READ_WRITE_SQL};
47    use crate::config::{SQLITE_CACHE_SIZE_KIB, SQLITE_PAGE_SIZE};
48
49    #[test]
50    fn static_pragma_sql_matches_config_values() {
51        let read_write = std::str::from_utf8(READ_WRITE_SQL)
52            .unwrap()
53            .trim_end_matches('\0');
54        let read_only = std::str::from_utf8(READ_ONLY_SQL)
55            .unwrap()
56            .trim_end_matches('\0');
57
58        assert!(read_write.contains(&format!("page_size = {SQLITE_PAGE_SIZE}")));
59        assert!(read_write.contains(&format!("cache_size = -{SQLITE_CACHE_SIZE_KIB}")));
60        assert!(!std::str::from_utf8(READ_WRITE_EXISTING_SQL)
61            .unwrap()
62            .contains("page_size"));
63        assert!(std::str::from_utf8(READ_WRITE_EXISTING_SQL)
64            .unwrap()
65            .contains(&format!("cache_size = -{SQLITE_CACHE_SIZE_KIB}")));
66        assert!(read_only.contains(&format!("cache_size = -{SQLITE_CACHE_SIZE_KIB}")));
67        assert!(read_only.contains("locking_mode = EXCLUSIVE"));
68        assert_eq!(READ_WRITE_SQL.last(), Some(&0));
69        assert_eq!(READ_WRITE_EXISTING_SQL.last(), Some(&0));
70        assert_eq!(READ_ONLY_SQL.last(), Some(&0));
71    }
72}