db_rs/
config.rs

1use crate::errors::{DbError, DbResult};
2use std::path::{Path, PathBuf};
3
4/// db-rs's config that describes where the log file should be and how the database should behave.
5/// use [Config::in_folder] as a starting point.
6#[derive(Clone, Debug)]
7pub struct Config {
8    /// folder where db-rs can write it's log
9    pub path: PathBuf,
10
11    /// should db-rs create parent folders that don't exist? Default: true
12    pub create_path: bool,
13
14    /// should db-rs create a log if one doesn't exist? Default: true
15    pub create_db: bool,
16
17    /// should db-rs only read and not write? (good for analysis tooling) Default: false
18    pub read_only: bool,
19
20    /// should db-rs avoid all IO? (good for tests) Default: false
21    pub no_io: bool,
22
23    /// should db-rs guard it's log file with a file lock? (good for CLIs) Default: true
24    pub fs_locks: bool,
25
26    /// if using fs_locks, should we block while trying to aquire a lock? Default: false
27    pub fs_locks_block: bool,
28
29    #[doc(hidden)]
30    pub schema_name: Option<String>,
31}
32
33impl Config {
34    fn base() -> Self {
35        Self {
36            path: Default::default(),
37            schema_name: None,
38            create_path: true,
39            create_db: true,
40            read_only: false,
41            no_io: false,
42            fs_locks: true,
43            fs_locks_block: false,
44        }
45    }
46
47    pub fn no_io() -> Self {
48        Self {
49            path: Default::default(),
50            schema_name: None,
51            create_path: false,
52            create_db: false,
53            read_only: true,
54            no_io: true,
55            fs_locks: false,
56            fs_locks_block: false,
57        }
58    }
59
60    pub fn in_folder<P>(p: P) -> Self
61    where
62        P: AsRef<Path>,
63    {
64        Self { path: PathBuf::from(p.as_ref()), ..Self::base() }
65    }
66
67    pub fn db_location_v2(&self) -> DbResult<PathBuf> {
68        let name = self.schema_name.as_ref().ok_or(DbError::Unexpected(
69            "Schema name not populated! db-rs-derive should have done this",
70        ))?;
71        let mut pathbuf = self.path.clone();
72        pathbuf.push(format!("{name}.db"));
73        Ok(pathbuf)
74    }
75
76    pub fn db_location_v1(&self) -> DbResult<PathBuf> {
77        let name = self.schema_name.as_ref().ok_or(DbError::Unexpected(
78            "Schema name not populated! db-rs-derive should have done this",
79        ))?;
80        let mut pathbuf = self.path.clone();
81        pathbuf.push(name);
82        Ok(pathbuf)
83    }
84
85    pub fn compaction_location(&self) -> DbResult<PathBuf> {
86        let name = self.schema_name.as_ref().ok_or(DbError::Unexpected(
87            "Schema name not populated! db-rs-derive should have done this",
88        ))?;
89        let mut pathbuf = self.path.clone();
90        pathbuf.push(format!("{name}.db.tmp"));
91        Ok(pathbuf)
92    }
93}