sqlsrv/
utils.rs

1//! Utility functions around SQL commands.
2
3use rusqlite::{params, Connection};
4
5#[cfg(feature = "tpool")]
6use threadpool::ThreadPool;
7
8#[cfg(feature = "tpool")]
9use super::ConnPool;
10
11/// Return the number of pages in the freelist.
12///
13/// # Errors
14/// Returns [`rusqlite::Error`].
15pub fn freelist_count(conn: &Connection) -> Result<usize, rusqlite::Error> {
16  conn.query_row_and_then("PRAGMA freelist_count;'", [], |row| row.get(0))
17}
18
19/// Run an incremental vacuum.
20///
21/// If `n` is `None` the entrire list of free pages will be processed.  If it
22/// is `Some(n)` then only up to `n` pages will be processed.
23///
24/// # Errors
25/// Returns [`rusqlite::Error`].
26#[allow(clippy::option_if_let_else)]
27pub fn incremental_vacuum(
28  conn: &Connection,
29  n: Option<usize>
30) -> Result<(), rusqlite::Error> {
31  if let Some(n) = n {
32    conn.execute("PRAGMA incremental_vacuum(?);", params![n])
33  } else {
34    conn.execute("PRAGMA incremental_vacuum;", params![])
35  }
36  .map(|_| ())
37}
38
39#[cfg(feature = "tpool")]
40#[cfg_attr(docsrs, doc(cfg(feature = "tpool")))]
41#[must_use]
42pub fn pooled_incremental_vacuum(
43  cpool: &ConnPool,
44  tpool: &ThreadPool,
45  n: Option<usize>
46) -> swctx::WaitCtx<(), (), rusqlite::Error> {
47  let (sctx, wctx) = swctx::mkpair();
48
49  let conn = cpool.writer();
50
51  // Kick off incremental vacuum on the thread pool.  Ignore any errors caused
52  // by returning the results.
53  tpool.execute(move || match conn.incremental_vacuum(n) {
54    Ok(()) => {
55      let _ = sctx.set(());
56    }
57    Err(e) => {
58      let _ = sctx.fail(e);
59    }
60  });
61
62  wctx
63}
64
65// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :