diff --git a/melib/src/sqlite3.rs b/melib/src/sqlite3.rs index 20475be2..5eb64078 100644 --- a/melib/src/sqlite3.rs +++ b/melib/src/sqlite3.rs @@ -23,6 +23,13 @@ use crate::{error::*, logging::log}; pub use rusqlite::{self, params, Connection}; use std::path::PathBuf; +#[derive(Copy, Clone, Debug)] +pub struct DatabaseDescription { + pub name: &'static str, + pub init_script: Option<&'static str>, + pub version: u32, +} + pub fn db_path(name: &str) -> Result { let data_dir = xdg::BaseDirectories::with_prefix("meli").map_err(|e| MeliError::new(e.to_string()))?; @@ -38,12 +45,23 @@ pub fn open_db(db_path: PathBuf) -> Result { Connection::open(&db_path).map_err(|e| MeliError::new(e.to_string())) } -pub fn open_or_create_db(name: &str, init_script: Option<&str>) -> Result { - let db_path = db_path(name)?; +pub fn open_or_create_db( + description: &DatabaseDescription, + identifier: Option<&str>, +) -> Result { + let db_path = if let Some(id) = identifier { + db_path(&format!("{}_{}", id, description.name)) + } else { + db_path(description.name) + }?; let mut set_mode = false; if !db_path.exists() { log( - format!("Creating {} database in {}", name, db_path.display()), + format!( + "Creating {} database in {}", + description.name, + db_path.display() + ), crate::INFO, ); set_mode = true; @@ -58,8 +76,18 @@ pub fn open_or_create_db(name: &str, init_script: Option<&str>) -> Result Result { - melib_sqlite3::db_path(DB_NAME) + melib_sqlite3::db_path(DB.name) } //#[inline(always)] @@ -141,7 +145,7 @@ pub fn insert( backend: &Arc>>, acc_name: &str, ) -> Result<()> { - let db_path = melib_sqlite3::db_path(DB_NAME)?; + let db_path = db_path()?; if !db_path.exists() { return Err(MeliError::new( "Database hasn't been initialised. Run `reindex` command", @@ -231,7 +235,7 @@ pub fn insert( } pub fn remove(env_hash: EnvelopeHash) -> Result<()> { - let db_path = melib_sqlite3::db_path(DB_NAME)?; + let db_path = db_path()?; if !db_path.exists() { return Err(MeliError::new( "Database hasn't been initialised. Run `reindex` command", @@ -271,7 +275,7 @@ pub fn index(context: &mut crate::state::Context, account_index: usize) -> Resul account.collection.envelopes.clone(), account.backend.clone(), ); - let conn = melib_sqlite3::open_or_create_db(DB_NAME, Some(INIT_SCRIPT))?; + let conn = melib_sqlite3::open_or_create_db(&DB, None)?; let env_hashes = acc_mutex .read() .unwrap() @@ -340,7 +344,7 @@ pub fn search( query: &Query, (sort_field, sort_order): (SortField, SortOrder), ) -> ResultFuture> { - let db_path = melib_sqlite3::db_path(DB_NAME)?; + let db_path = db_path()?; if !db_path.exists() { return Err(MeliError::new( "Database hasn't been initialised. Run `reindex` command",