db.rs

 1pub mod items;
 2pub mod kvp;
 3mod migrations;
 4pub mod pane;
 5pub mod workspace;
 6
 7use std::fs;
 8use std::ops::Deref;
 9use std::path::Path;
10
11use anyhow::Result;
12use indoc::indoc;
13use sqlez::connection::Connection;
14use sqlez::thread_safe_connection::ThreadSafeConnection;
15
16pub use workspace::*;
17
18#[derive(Clone)]
19struct Db(ThreadSafeConnection);
20
21impl Deref for Db {
22    type Target = sqlez::connection::Connection;
23
24    fn deref(&self) -> &Self::Target {
25        &self.0.deref()
26    }
27}
28
29impl Db {
30    /// Open or create a database at the given directory path.
31    pub fn open(db_dir: &Path, channel: &'static str) -> Self {
32        // Use 0 for now. Will implement incrementing and clearing of old db files soon TM
33        let current_db_dir = db_dir.join(Path::new(&format!("0-{}", channel)));
34        fs::create_dir_all(&current_db_dir)
35            .expect("Should be able to create the database directory");
36        let db_path = current_db_dir.join(Path::new("db.sqlite"));
37
38        Db(
39            ThreadSafeConnection::new(db_path.to_string_lossy().as_ref(), true)
40                .with_initialize_query(indoc! {"
41                    PRAGMA journal_mode=WAL;
42                    PRAGMA synchronous=NORMAL;
43                    PRAGMA foreign_keys=TRUE;
44                    PRAGMA case_sensitive_like=TRUE;
45                "}),
46        )
47    }
48
49    pub fn persisting(&self) -> bool {
50        self.persistent()
51    }
52
53    /// Open a in memory database for testing and as a fallback.
54    pub fn open_in_memory() -> Self {
55        Db(
56            ThreadSafeConnection::new("Zed DB", false).with_initialize_query(indoc! {"
57                    PRAGMA journal_mode=WAL;
58                    PRAGMA synchronous=NORMAL;
59                    PRAGMA foreign_keys=TRUE;
60                    PRAGMA case_sensitive_like=TRUE;
61                    "}),
62        )
63    }
64
65    pub fn write_to<P: AsRef<Path>>(&self, dest: P) -> Result<()> {
66        let destination = Connection::open_file(dest.as_ref().to_string_lossy().as_ref());
67        self.backup(&destination)
68    }
69}
70
71impl Drop for Db {
72    fn drop(&mut self) {
73        self.exec(indoc! {"
74            PRAGMA analysis_limit=500;
75            PRAGMA optimize"})
76            .ok();
77    }
78}