diff --git a/src/profile/search.rs b/src/profile/search.rs index e0d72c61..8abac06f 100644 --- a/src/profile/search.rs +++ b/src/profile/search.rs @@ -18,28 +18,36 @@ impl Search { // Constructors /// Create new `Self` - pub fn build(connection: &Rc>, profile_id: &Rc) -> Self { + pub fn build(connection: &Rc>, profile_id: &Rc) -> Result { // Init children components let database = Database::init(connection, profile_id); let memory = Memory::init(); // Build initial index - index(&database, &memory); + index(&database, &memory)?; // Return new `Self` - Self { database, memory } + Ok(Self { database, memory }) } // Actions /// Add new search provider record /// * requires valid [Uri](https://docs.gtk.org/glib/struct.Uri.html) - pub fn add(&self, query: Uri, is_default: bool) -> Result<(), Error> { + pub fn add(&self, query: &Uri, is_default: bool) -> Result<(), Error> { match self.database.add(query.to_string(), is_default) { Ok(_) => Ok(index(&self.database, &self.memory)?), Err(e) => Err(Error::Database(e)), } } + /// Add new search provider record + /// * requires valid [Uri](https://docs.gtk.org/glib/struct.Uri.html) + pub fn set_default(&self, profile_search_id: i64) -> Result<(), Error> { + match self.database.set_default(profile_search_id) { + Ok(_) => Ok(index(&self.database, &self.memory)?), + Err(e) => Err(Error::Database(e)), + } + } /// Get records from the memory index pub fn records(&self) -> Vec { diff --git a/src/profile/search/database.rs b/src/profile/search/database.rs index c7f12588..f5083cf6 100644 --- a/src/profile/search/database.rs +++ b/src/profile/search/database.rs @@ -75,6 +75,25 @@ impl Database { Err(e) => Err(e), } } + + /// Delete record from database + pub fn set_default(&self, id: i64) -> Result<(), Error> { + // Begin new transaction + let mut writable = self.connection.write().unwrap(); // @TODO + let tx = writable.transaction()?; + + // Make sure only one default provider in set + reset(&tx, *self.profile_id, false)?; + + // Delete record by ID + match set_default(&tx, *self.profile_id, id, true) { + Ok(_) => match tx.commit() { + Ok(_) => Ok(()), + Err(e) => Err(e), + }, + Err(e) => Err(e), + } + } } // Low-level DB API @@ -147,6 +166,18 @@ fn reset(tx: &Transaction, profile_id: i64, is_default: bool) -> Result Result { + tx.execute( + "UPDATE `profile_search` SET `is_default` = ? WHERE `profile_id` = ? AND `id` = ?", + (is_default, profile_id, id), + ) +} + fn last_insert_id(tx: &Transaction) -> i64 { tx.last_insert_rowid() }