diff --git a/geoffrey_db/src/database.rs b/geoffrey_db/src/database.rs index b608e46..6648e86 100644 --- a/geoffrey_db/src/database.rs +++ b/geoffrey_db/src/database.rs @@ -2,12 +2,22 @@ use crate::error::{GeoffreyDBError, Result}; use crate::migration::do_migration; use geoffrey_models::models::db_metadata::DBMetadata; use geoffrey_models::GeoffreyDatabaseModel; +use sled::IVec; use std::convert::TryInto; use std::path::Path; const DB_VERSION: u64 = 3; const DB_METADATA_ID: u64 = 1; +fn option_bytes_to_model(bytes: Option, id: u64) -> Result { + if let Some(bytes) = bytes { + Ok(T::try_from_bytes(&bytes)?) + } else { + log::debug!("{} of id {} was not found in the database", T::tree(), id); + Err(GeoffreyDBError::NotFound) + } +} + pub struct Database { pub(crate) db: sled::Db, } @@ -66,14 +76,7 @@ impl Database { T: GeoffreyDatabaseModel, { let tree = self.get_tree::()?; - let id_bytes = id.to_be_bytes(); - - if let Some(bytes) = tree.get(id_bytes)? { - Ok(T::try_from_bytes(&bytes)?) - } else { - log::debug!("{} of id {} was not found in the database", T::tree(), id); - Err(GeoffreyDBError::NotFound) - } + option_bytes_to_model(tree.get(id.to_be_bytes())?, id) } pub fn clear_tree(&self) -> Result<()> @@ -110,6 +113,14 @@ impl Database { })) } + pub fn remove(&self, id: u64) -> Result + where + T: GeoffreyDatabaseModel, + { + let tree = self.db.open_tree(T::tree())?; + option_bytes_to_model(tree.remove(id.to_be_bytes())?, id) + } + pub fn tree_iter(&self) -> Result where T: GeoffreyDatabaseModel, @@ -228,6 +239,21 @@ mod tests { cleanup(); } + #[test] + fn test_remove() { + let _lock = LOCK.lock().unwrap(); + cleanup(); + let player = Player::new("CoolZero123", UserID::DiscordUUID { discord_uuid: 0u64 }); + + let p2 = DB.insert::(player.clone()).unwrap(); + + let p3 = DB.remove::(p2.id.unwrap()).unwrap(); + + assert!(DB.get::(p3.id.unwrap()).is_err()); + assert_eq!(p3.id.unwrap(), p2.id.unwrap()); + cleanup(); + } + #[test] fn test_insert_speed() { let _lock = LOCK.lock().unwrap();