misc.rs
1 mod database; 2 mod memory; 3 4 use anyhow::Result; 5 use database::Database; 6 use memory::Memory; 7 use r2d2::Pool; 8 use r2d2_sqlite::SqliteConnectionManager; 9 use std::{cell::RefCell, collections::HashMap}; 10 11 pub struct Misc { 12 database: Database, 13 memory: RefCell<HashMap<String, Memory>>, 14 } 15 16 impl Misc { 17 // Constructors 18 19 pub fn init(database_pool: &Pool<SqliteConnectionManager>, profile_id: i64) -> Result<Self> { 20 let database = Database::init(database_pool, profile_id); 21 22 let rows = database.rows()?; 23 let memory = RefCell::new(HashMap::with_capacity(rows.len())); 24 25 { 26 // build in-memory index... 27 let mut m = memory.borrow_mut(); 28 // create initial preset (populate index with the default values) 29 let v = Memory::highlight_request_entry(true); 30 assert!(m.insert(v.key().to_string(), v).is_none()); 31 32 // update values from the DB (if exists) 33 for row in rows { 34 let v = Memory::from_db_row(&row.key, row.value).unwrap(); 35 assert!(m.insert(v.key().to_string(), v).is_some()); 36 // * panics if the DB was malformed or changed unexpectedly 37 } 38 } 39 40 Ok(Self { database, memory }) 41 } 42 43 // Setters 44 45 pub fn save(&self) -> Result<()> { 46 for (_, m) in self.memory.take() { 47 self.database.set(m.into_db_row())?; 48 } 49 Ok(()) 50 } 51 52 pub fn set_highlight_request_entry(&self, value: bool) -> Option<Memory> { 53 let v = Memory::highlight_request_entry(value); 54 self.memory.borrow_mut().insert(v.key().to_string(), v) 55 } 56 57 // Getters 58 59 pub fn is_highlight_request_entry(&self) -> bool { 60 if let Some(k) = self.memory.borrow().values().next() { 61 match k { 62 Memory::HighlightRequestEntry(v) => return v.is_true(), 63 } 64 } 65 false 66 } 67 } 68 69 // Tools 70 71 pub fn migrate(tx: &sqlite::Transaction) -> Result<()> { 72 // Migrate self components 73 database::init(tx)?; 74 75 // Delegate migration to childs 76 // nothing yet... 77 78 // Success 79 Ok(()) 80 }