1pub mod kvp;
2
3use std::fs;
4use std::ops::Deref;
5use std::path::Path;
6
7use anyhow::Result;
8use indoc::indoc;
9use sqlez::connection::Connection;
10use sqlez::domain::Domain;
11use sqlez::thread_safe_connection::ThreadSafeConnection;
12
13const INITIALIZE_QUERY: &'static str = indoc! {"
14 PRAGMA journal_mode=WAL;
15 PRAGMA synchronous=NORMAL;
16 PRAGMA foreign_keys=TRUE;
17 PRAGMA case_sensitive_like=TRUE;
18"};
19
20#[derive(Clone)]
21pub struct Db<D: Domain>(ThreadSafeConnection<D>);
22
23impl<D: Domain> Deref for Db<D> {
24 type Target = sqlez::connection::Connection;
25
26 fn deref(&self) -> &Self::Target {
27 &self.0.deref()
28 }
29}
30
31impl<D: Domain> Db<D> {
32 /// Open or create a database at the given directory path.
33 pub fn open(db_dir: &Path, channel: &'static str) -> Self {
34 // Use 0 for now. Will implement incrementing and clearing of old db files soon TM
35 let current_db_dir = db_dir.join(Path::new(&format!("0-{}", channel)));
36 fs::create_dir_all(¤t_db_dir)
37 .expect("Should be able to create the database directory");
38 let db_path = current_db_dir.join(Path::new("db.sqlite"));
39
40 Db(
41 ThreadSafeConnection::new(db_path.to_string_lossy().as_ref(), true)
42 .with_initialize_query(INITIALIZE_QUERY),
43 )
44 }
45
46 /// Open a in memory database for testing and as a fallback.
47 pub fn open_in_memory(db_name: &str) -> Self {
48 Db(ThreadSafeConnection::new(db_name, false).with_initialize_query(INITIALIZE_QUERY))
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 pub fn open_as<D2: Domain>(&self) -> Db<D2> {
61 Db(self.0.for_domain())
62 }
63}