sql_support/
maintenance.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
5use crate::ConnExt;
6use rusqlite::{Connection, Result};
7
8/// Run maintenance on the DB
9///
10/// `run_maintenance()` is intended to be run during idle time and will take steps to clean up /
11/// shrink the database.
12pub fn run_maintenance(conn: &Connection) -> Result<()> {
13    vacuum(conn)?;
14    conn.execute_one("PRAGMA optimize")?;
15    conn.execute_one("PRAGMA wal_checkpoint(PASSIVE)")?;
16    Ok(())
17}
18
19/// Run vacuum on the DB
20fn vacuum(conn: &Connection) -> Result<()> {
21    let auto_vacuum_setting: u32 = conn.query_one("PRAGMA auto_vacuum")?;
22    if auto_vacuum_setting == 2 {
23        // Ideally, we run an incremental vacuum to delete 2 pages
24        conn.execute_one("PRAGMA incremental_vacuum(2)")?;
25    } else {
26        // If auto_vacuum=incremental isn't set, configure it and run a full vacuum.
27        error_support::warn!(
28            "run_maintenance_vacuum: Need to run a full vacuum to set auto_vacuum=incremental"
29        );
30        conn.execute_one("PRAGMA auto_vacuum=incremental")?;
31        conn.execute_one("VACUUM")?;
32    }
33    Ok(())
34}