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