sql_support/
lib.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5#![allow(unknown_lints)]
6#![warn(rust_2018_idioms)]
7
8//! A crate with various sql/sqlcipher helpers.
9
10mod conn_ext;
11
12// XXX - temporarily disable our debug_tools, to avoid pulling in:
13// prettytable-rs = { version = "0.10", optional = true }
14// while vendoring into m-c :(
15pub mod debug_tools {
16    pub fn define_debug_functions(_c: &rusqlite::Connection) -> rusqlite::Result<()> {
17        Ok(())
18    }
19}
20
21mod each_chunk;
22mod lazy;
23mod maintenance;
24mod maybe_cached;
25pub mod open_database;
26mod repeat;
27
28pub use conn_ext::*;
29pub use each_chunk::*;
30pub use lazy::*;
31pub use maintenance::run_maintenance;
32pub use maybe_cached::*;
33pub use repeat::*;
34
35// reexport logging helpers.
36use error_support::{debug, info, warn};
37
38/// In PRAGMA foo='bar', `'bar'` must be a constant string (it cannot be a
39/// bound parameter), so we need to escape manually. According to
40/// <https://www.sqlite.org/faq.html>, the only character that must be escaped is
41/// the single quote, which is escaped by placing two single quotes in a row.
42pub fn escape_string_for_pragma(s: &str) -> String {
43    s.replace('\'', "''")
44}
45
46/// Default SQLite pragmas
47///
48/// Most components should just stick to these defaults.
49pub fn setup_sqlite_defaults(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
50    conn.execute_batch(
51        "
52        PRAGMA temp_store = 2;
53        PRAGMA journal_mode = WAL;
54        ",
55    )?;
56    let page_size: usize = conn.query_row("PRAGMA page_size", (), |row| row.get(0))?;
57    // Aim to checkpoint at 512Kb
58    let target_checkpoint_size = 2usize.pow(19);
59    // Truncate the journal if it more than 3x larger than the target size
60    let journal_size_limit = target_checkpoint_size * 3;
61    conn.execute_batch(&format!(
62        "
63        PRAGMA wal_autocheckpoint = {};
64        PRAGMA journal_size_limit = {};
65        ",
66        target_checkpoint_size / page_size,
67        journal_size_limit,
68    ))?;
69
70    Ok(())
71}
72
73#[cfg(test)]
74mod test {
75    use super::*;
76    #[test]
77    fn test_escape_string_for_pragma() {
78        assert_eq!(escape_string_for_pragma("foobar"), "foobar");
79        assert_eq!(escape_string_for_pragma("'foo'bar'"), "''foo''bar''");
80        assert_eq!(escape_string_for_pragma("''"), "''''");
81    }
82
83    #[test]
84    fn test_sqlite_defaults() {
85        let conn = rusqlite::Connection::open_in_memory().unwrap();
86        // Simulate a default page size,
87        // On Mobile, these are set by the OS.  On Desktop, these are set by the build system when
88        // we compile SQLite.
89        conn.execute("PRAGMA page_size = 8192", ()).unwrap();
90        setup_sqlite_defaults(&conn).unwrap();
91        let autocheckpoint: usize = conn
92            .query_row("PRAGMA wal_autocheckpoint", (), |row| row.get(0))
93            .unwrap();
94        // We should aim to auto-checkpoint at 512kb, which is 64 pages when the page size is 8k
95        assert_eq!(autocheckpoint, 64);
96        // We could also check the journal size limit, but that's harder to query with a pragma.
97        // If we go the math right once, we should get it for the other case.
98    }
99}