Skip to main content

sqlive/
sqlite_temporary.rs

1//! The folder SQLite keeps temporary tables in, for every database this
2//! process opens (§21.2).
3//!
4//! Temporary tables spill to files there once a connection's cache fills,
5//! so a staged snapshot waits on disk. SQLite finds a folder for itself
6//! everywhere but Android, where an app names one, such as its cache folder.
7
8use crate::authorization::HostError;
9use panic_as_error::locks::lock_unpoisoned;
10use std::path::{Path, PathBuf};
11use std::sync::Mutex;
12
13/// The folder an app names for SQLite's temporary tables (§21.2), outside
14/// the host's directories. The app creates it and names its path to
15/// `set_temporary_directory`.
16#[derive(Debug, PartialEq, Eq)]
17struct TemporaryFolder {
18    path: PathBuf,
19}
20
21impl TemporaryFolder {
22    /// The folder at `path`, when it names an existing folder, following
23    /// symlinks. A folder this process can't inspect counts as absent.
24    fn at(path: &Path) -> Option<Self> {
25        std::fs::metadata(path)
26            .is_ok_and(|metadata| metadata.is_dir())
27            .then(|| Self { path: path.to_owned() })
28    }
29
30    /// Its path.
31    fn path(&self) -> &Path {
32        &self.path
33    }
34}
35
36/// What this process has told SQLite, and whether a connection may be using it.
37struct Temporary {
38    directory: Option<TemporaryFolder>,
39    opened: bool,
40}
41
42static TEMPORARY: Mutex<Temporary> = Mutex::new(Temporary { directory: None, opened: false });
43
44/// Why the folder for temporary tables could not be named (E1).
45#[derive(Debug, thiserror::Error)]
46pub enum TemporaryDirectoryError {
47    /// A database opened in this process before the host named the folder.
48    /// SQLite reads the folder's name without a lock, so the host names the
49    /// folder before any database opens.
50    #[error("the temporary folder is named before any store opens")]
51    AfterOpening,
52    /// Another folder was named already. Naming the same one again is allowed.
53    #[error("the temporary folder is already {}", directory.display())]
54    AlreadyNamed {
55        /// The folder named first.
56        directory: PathBuf,
57    },
58    /// The path is not an existing folder, or SQLite cannot hold it: it is not
59    /// UTF-8, or contains a NUL.
60    #[error("{} is not a folder SQLite can keep temporary tables in", directory.display())]
61    NotAFolder {
62        /// The path given.
63        directory: PathBuf,
64    },
65}
66
67/// Keep SQLite's temporary tables in `directory`, for every database this
68/// process opens from now on. Call it before opening any database.
69pub fn set_temporary_directory(directory: &Path) -> Result<(), TemporaryDirectoryError> {
70    let mut temporary = lock_unpoisoned(&TEMPORARY);
71    if let Some(named) = &temporary.directory {
72        if named.path() == directory {
73            return Ok(());
74        }
75        return Err(TemporaryDirectoryError::AlreadyNamed { directory: named.path().to_owned() });
76    }
77    if temporary.opened {
78        return Err(TemporaryDirectoryError::AfterOpening);
79    }
80    let unusable = || TemporaryDirectoryError::NotAFolder { directory: directory.to_owned() };
81    let folder = TemporaryFolder::at(directory).ok_or_else(unusable)?;
82    let text = folder.path().to_str().ok_or_else(unusable)?;
83    let text = std::ffi::CString::new(text).map_err(|_nul| unusable())?;
84    // SAFETY: no connection exists yet, so nothing reads the variable while it
85    // changes, and later connections only read it. SQLite requires its value
86    // to come from sqlite3_mprintf.
87    unsafe {
88        let copy = rusqlite::ffi::sqlite3_mprintf(c"%s".as_ptr(), text.as_ptr());
89        if copy.is_null() {
90            return Err(unusable());
91        }
92        rusqlite::ffi::sqlite3_temp_directory = copy;
93    }
94    temporary.directory = Some(folder);
95    Ok(())
96}
97
98/// Every connection opens after this: the folder can no longer change. It
99/// refuses a SQLite built to keep temporary tables in memory unless a
100/// connection asks for files (`SQLITE_TEMP_STORE=2`) or whatever it asks
101/// (`=3`, libsqlite3-sys's Android default): the host's own temporary tables,
102/// such as a streamed write's staged rows, would then hold all of it in
103/// memory. It refuses one built without `SQLITE_ENABLE_MEMORY_MANAGEMENT`
104/// too: each connection would keep its unused pages apart, and releasing
105/// memory on one connection would leave every other's (§4).
106pub(crate) fn opening<F: HostError, R: HostError>() -> Result<(), crate::Error<F, R>> {
107    // SAFETY: the option is a NUL-terminated string that outlives the call.
108    if unsafe { rusqlite::ffi::sqlite3_compileoption_used(c"ENABLE_MEMORY_MANAGEMENT".as_ptr()) }
109        == 0
110    {
111        return Err(crate::Error::Invariant {
112            what: "SQLite keeps every connection's unused pages in one pool (SQLITE_ENABLE_MEMORY_MANAGEMENT)",
113        });
114    }
115    for option in [c"TEMP_STORE=2", c"TEMP_STORE=3"] {
116        // SAFETY: the option is a NUL-terminated string that outlives the call.
117        if unsafe { rusqlite::ffi::sqlite3_compileoption_used(option.as_ptr()) } != 0 {
118            return Err(crate::Error::Invariant {
119                what: "SQLite keeps temporary tables in files unless a connection asks for memory (SQLITE_TEMP_STORE below 2)",
120            });
121        }
122    }
123    lock_unpoisoned(&TEMPORARY).opened = true;
124    Ok(())
125}