1mod kvp;
2mod migrations;
3
4use std::fs;
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7
8use anyhow::Result;
9use log::error;
10use parking_lot::Mutex;
11use rusqlite::Connection;
12
13use migrations::MIGRATIONS;
14
15#[derive(Clone)]
16pub enum Db {
17 Real(Arc<RealDb>),
18 Null,
19}
20
21pub struct RealDb {
22 connection: Mutex<Connection>,
23 path: Option<PathBuf>,
24}
25
26impl Db {
27 /// Open or create a database at the given directory path.
28 pub fn open(db_dir: &Path, channel: &'static str) -> Self {
29 // Use 0 for now. Will implement incrementing and clearing of old db files soon TM
30 let current_db_dir = db_dir.join(Path::new(&format!("0-{}", channel)));
31 fs::create_dir_all(¤t_db_dir)
32 .expect("Should be able to create the database directory");
33 let db_path = current_db_dir.join(Path::new("db.sqlite"));
34
35 Connection::open(db_path)
36 .map_err(Into::into)
37 .and_then(|connection| Self::initialize(connection))
38 .map(|connection| {
39 Db::Real(Arc::new(RealDb {
40 connection,
41 path: Some(db_dir.to_path_buf()),
42 }))
43 })
44 .unwrap_or_else(|e| {
45 error!(
46 "Connecting to file backed db failed. Reverting to null db. {}",
47 e
48 );
49 Self::Null
50 })
51 }
52
53 /// Open a in memory database for testing and as a fallback.
54 #[cfg(any(test, feature = "test-support"))]
55 pub fn open_in_memory() -> Self {
56 Connection::open_in_memory()
57 .map_err(Into::into)
58 .and_then(|connection| Self::initialize(connection))
59 .map(|connection| {
60 Db::Real(Arc::new(RealDb {
61 connection,
62 path: None,
63 }))
64 })
65 .unwrap_or_else(|e| {
66 error!(
67 "Connecting to in memory db failed. Reverting to null db. {}",
68 e
69 );
70 Self::Null
71 })
72 }
73
74 fn initialize(mut conn: Connection) -> Result<Mutex<Connection>> {
75 MIGRATIONS.to_latest(&mut conn)?;
76
77 conn.pragma_update(None, "journal_mode", "WAL")?;
78 conn.pragma_update(None, "synchronous", "NORMAL")?;
79 conn.pragma_update(None, "foreign_keys", true)?;
80 conn.pragma_update(None, "case_sensitive_like", true)?;
81
82 Ok(Mutex::new(conn))
83 }
84
85 pub fn persisting(&self) -> bool {
86 self.real().and_then(|db| db.path.as_ref()).is_some()
87 }
88
89 pub fn real(&self) -> Option<&RealDb> {
90 match self {
91 Db::Real(db) => Some(&db),
92 _ => None,
93 }
94 }
95}
96
97impl Drop for Db {
98 fn drop(&mut self) {
99 match self {
100 Db::Real(real_db) => {
101 let lock = real_db.connection.lock();
102
103 let _ = lock.pragma_update(None, "analysis_limit", "500");
104 let _ = lock.pragma_update(None, "optimize", "");
105 }
106 Db::Null => {}
107 }
108 }
109}
110
111#[cfg(test)]
112mod tests {
113 use crate::migrations::MIGRATIONS;
114
115 #[test]
116 fn test_migrations() {
117 assert!(MIGRATIONS.validate().is_ok());
118 }
119}