1pub mod kvp;
2mod migrations;
3pub mod workspace;
4
5use std::fs;
6use std::ops::Deref;
7use std::path::Path;
8
9use anyhow::Result;
10use indoc::indoc;
11use kvp::KVP_MIGRATION;
12use sqlez::connection::Connection;
13use sqlez::thread_safe_connection::ThreadSafeConnection;
14
15use workspace::pane::PANE_MIGRATIONS;
16pub use workspace::*;
17
18#[derive(Clone)]
19pub struct 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(¤t_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 .with_migrations(&[KVP_MIGRATION, WORKSPACES_MIGRATION, PANE_MIGRATIONS]),
47 )
48 }
49
50 pub fn persisting(&self) -> bool {
51 self.persistent()
52 }
53
54 /// Open a in memory database for testing and as a fallback.
55 pub fn open_in_memory(db_name: &str) -> Self {
56 Db(ThreadSafeConnection::new(db_name, false)
57 .with_initialize_query(indoc! {"
58 PRAGMA journal_mode=WAL;
59 PRAGMA synchronous=NORMAL;
60 PRAGMA foreign_keys=TRUE;
61 PRAGMA case_sensitive_like=TRUE;
62 "})
63 .with_migrations(&[KVP_MIGRATION, WORKSPACES_MIGRATION, PANE_MIGRATIONS]))
64 }
65
66 pub fn write_to<P: AsRef<Path>>(&self, dest: P) -> Result<()> {
67 let destination = Connection::open_file(dest.as_ref().to_string_lossy().as_ref());
68 self.backup_main(&destination)
69 }
70}