db.rs

 1pub mod kvp;
 2
 3use std::fs;
 4use std::path::Path;
 5
 6#[cfg(any(test, feature = "test-support"))]
 7use anyhow::Result;
 8use indoc::indoc;
 9#[cfg(any(test, feature = "test-support"))]
10use sqlez::connection::Connection;
11use sqlez::domain::Domain;
12use sqlez::thread_safe_connection::ThreadSafeConnection;
13
14const INITIALIZE_QUERY: &'static str = indoc! {"
15    PRAGMA journal_mode=WAL;
16    PRAGMA synchronous=NORMAL;
17    PRAGMA foreign_keys=TRUE;
18    PRAGMA case_sensitive_like=TRUE;
19"};
20
21/// Open or create a database at the given directory path.
22pub fn open_file_db<D: Domain>() -> ThreadSafeConnection<D> {
23    // Use 0 for now. Will implement incrementing and clearing of old db files soon TM
24    let current_db_dir = (*util::paths::DB_DIR).join(Path::new(&format!(
25        "0-{}",
26        *util::channel::RELEASE_CHANNEL_NAME
27    )));
28    fs::create_dir_all(&current_db_dir).expect("Should be able to create the database directory");
29    let db_path = current_db_dir.join(Path::new("db.sqlite"));
30
31    ThreadSafeConnection::new(db_path.to_string_lossy().as_ref(), true)
32        .with_initialize_query(INITIALIZE_QUERY)
33}
34
35pub fn open_memory_db<D: Domain>(db_name: &str) -> ThreadSafeConnection<D> {
36    ThreadSafeConnection::new(db_name, false).with_initialize_query(INITIALIZE_QUERY)
37}
38
39#[cfg(any(test, feature = "test-support"))]
40pub fn write_db_to<D: Domain, P: AsRef<Path>>(
41    conn: &ThreadSafeConnection<D>,
42    dest: P,
43) -> Result<()> {
44    let destination = Connection::open_file(dest.as_ref().to_string_lossy().as_ref());
45    conn.backup_main(&destination)
46}