use std::path::PathBuf;
use std::time::Duration;
use crate::error::{SqliteError, SqliteResult};
#[derive(Debug, Clone)]
pub struct SqliteConfig {
pub path: Option<PathBuf>,
pub max_readers: usize,
pub busy_timeout: Duration,
pub cache_kib: u32,
pub synchronous_full: bool,
}
impl Default for SqliteConfig {
fn default() -> Self {
Self {
path: None,
max_readers: 4,
busy_timeout: Duration::from_secs(5),
cache_kib: 2048,
synchronous_full: false,
}
}
}
impl SqliteConfig {
pub fn in_memory() -> Self {
Self {
max_readers: 0,
..Self::default()
}
}
pub fn at(path: impl Into<PathBuf>) -> Self {
Self {
path: Some(path.into()),
..Self::default()
}
}
pub fn from_env() -> SqliteResult<Self> {
let in_memory = wabot_core::env::flag("SQLITE_IN_MEMORY");
let path = wabot_core::env::optional::<String>("SQLITE_PATH");
let base = match (in_memory, path) {
(true, _) => Self::in_memory(),
(false, Some(path)) => Self::at(path),
(false, None) => {
return Err(SqliteError::Config(
"set SQLITE_PATH to the database file, or SQLITE_IN_MEMORY=1".into(),
))
}
};
Ok(Self {
max_readers: wabot_core::env::or("WABOT_SQLITE_MAX_READERS", base.max_readers),
busy_timeout: Duration::from_millis(wabot_core::env::or(
"WABOT_SQLITE_BUSY_TIMEOUT_MS",
base.busy_timeout.as_millis() as u64,
)),
cache_kib: wabot_core::env::or("WABOT_SQLITE_CACHE_KIB", base.cache_kib),
synchronous_full: wabot_core::env::flag("WABOT_SQLITE_SYNCHRONOUS_FULL"),
..base
})
}
pub fn with_max_readers(mut self, max_readers: usize) -> Self {
self.max_readers = max_readers;
self
}
pub(crate) fn is_in_memory(&self) -> bool {
self.path.is_none()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_in_memory_database_has_no_reader_pool() {
assert_eq!(SqliteConfig::in_memory().max_readers, 0);
assert!(SqliteConfig::in_memory().is_in_memory());
assert!(!SqliteConfig::at("/tmp/x.db").is_in_memory());
}
#[test]
fn from_env_refuses_to_guess_a_path() {
if std::env::var_os("SQLITE_PATH").is_some()
|| std::env::var_os("SQLITE_IN_MEMORY").is_some()
{
return;
}
assert!(matches!(
SqliteConfig::from_env(),
Err(SqliteError::Config(_))
));
}
}