sqlive/
sqlite_temporary.rs1use crate::authorization::HostError;
9use panic_as_error::locks::lock_unpoisoned;
10use std::path::{Path, PathBuf};
11use std::sync::Mutex;
12
13#[derive(Debug, PartialEq, Eq)]
17struct TemporaryFolder {
18 path: PathBuf,
19}
20
21impl TemporaryFolder {
22 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 fn path(&self) -> &Path {
32 &self.path
33 }
34}
35
36struct Temporary {
38 directory: Option<TemporaryFolder>,
39 opened: bool,
40}
41
42static TEMPORARY: Mutex<Temporary> = Mutex::new(Temporary { directory: None, opened: false });
43
44#[derive(Debug, thiserror::Error)]
46pub enum TemporaryDirectoryError {
47 #[error("the temporary folder is named before any store opens")]
51 AfterOpening,
52 #[error("the temporary folder is already {}", directory.display())]
54 AlreadyNamed {
55 directory: PathBuf,
57 },
58 #[error("{} is not a folder SQLite can keep temporary tables in", directory.display())]
61 NotAFolder {
62 directory: PathBuf,
64 },
65}
66
67pub 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 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
98pub(crate) fn opening<F: HostError, R: HostError>() -> Result<(), crate::Error<F, R>> {
107 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 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}