| 1 | use std::path::{Path, PathBuf}; |
| 2 | use std::sync::{Mutex, MutexGuard}; |
| 3 | |
| 4 | use directories::ProjectDirs; |
| 5 | use rusqlite::Connection; |
| 6 | |
| 7 | use crate::error::{Error, Result}; |
| 8 | use crate::migrations; |
| 9 | |
| 10 | pub const DATA_DIR_NAME: &str = "ms-teams-linux"; |
| 11 | const DATABASE_FILE: &str = "cache.sqlite3"; |
| 12 | |
| 13 | pub fn default_database_path() -> Result<PathBuf> { |
| 14 | let directories = ProjectDirs::from("", "", DATA_DIR_NAME).ok_or(Error::NoDataDirectory)?; |
| 15 | Ok(directories.data_dir().join(DATABASE_FILE)) |
| 16 | } |
| 17 | |
| 18 | pub struct Store { |
| 19 | connection: Mutex<Connection>, |
| 20 | } |
| 21 | |
| 22 | impl Store { |
| 23 | pub fn open_default() -> Result<Self> { |
| 24 | Self::open(&default_database_path()?) |
| 25 | } |
| 26 | |
| 27 | pub fn open(path: &Path) -> Result<Self> { |
| 28 | if let Some(parent) = path |
| 29 | .parent() |
| 30 | .filter(|parent| !parent.as_os_str().is_empty()) |
| 31 | { |
| 32 | std::fs::create_dir_all(parent).map_err(|source| Error::DataDirectory { |
| 33 | path: parent.display().to_string(), |
| 34 | source, |
| 35 | })?; |
| 36 | } |
| 37 | let connection = Connection::open(path)?; |
| 38 | connection.pragma_update(None, "journal_mode", "WAL")?; |
| 39 | Self::from_connection(connection) |
| 40 | } |
| 41 | |
| 42 | pub fn open_in_memory() -> Result<Self> { |
| 43 | Self::from_connection(Connection::open_in_memory()?) |
| 44 | } |
| 45 | |
| 46 | fn from_connection(mut connection: Connection) -> Result<Self> { |
| 47 | connection.pragma_update(None, "foreign_keys", "ON")?; |
| 48 | connection.pragma_update(None, "synchronous", "NORMAL")?; |
| 49 | migrations::migrate(&mut connection)?; |
| 50 | Ok(Store { |
| 51 | connection: Mutex::new(connection), |
| 52 | }) |
| 53 | } |
| 54 | |
| 55 | pub fn schema_version(&self) -> Result<i64> { |
| 56 | Ok(self |
| 57 | .lock()? |
| 58 | .pragma_query_value(None, "user_version", |row| row.get(0))?) |
| 59 | } |
| 60 | |
| 61 | pub(crate) fn lock(&self) -> Result<MutexGuard<'_, Connection>> { |
| 62 | self.connection.lock().map_err(|_| Error::Poisoned) |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | pub(crate) fn json_ids(ids: &[String]) -> String { |
| 67 | serde_json::to_string(ids).unwrap_or_else(|_| "[]".to_owned()) |
| 68 | } |