delete
Some checks failed
ci/woodpecker/push/test Pipeline failed

This commit is contained in:
JMARyA 2025-05-05 08:13:11 +02:00
parent dd4cb7fcc6
commit a858f0838a
Signed by: jmarya
GPG key ID: 901B2ADDF27C2263
2 changed files with 44 additions and 0 deletions

View file

@ -170,6 +170,25 @@ impl Database {
query_t(predicate, self)
}
/// Delete an entry
pub fn delete<
X: Into<IdRef<T>>,
T: 'static + Serialize + Identifiable + Send + Sync + Clone,
>(
&self,
entry: X,
) {
// delete from cache
let entry: IdRef<T> = entry.into();
let col = T::model_id();
let id = entry.id.trim_start_matches(&format!("{col}::")).to_string();
self.del_cache::<T>(id.clone());
// delete from vfs
self.storage
.remove_file(&format!("/collection/{col}/{id}"))
.unwrap();
}
/// Update every model in `entries` according to `u(_)`
pub fn update<T: 'static + Serialize + Identifiable + Send + Sync + Clone, F: Fn(&mut T)>(
&self,
@ -231,6 +250,10 @@ impl Database {
.insert(id, Box::new(model.clone()));
}
pub fn del_cache<T: Serialize + Identifiable + Send + Sync + 'static>(&self, id: String) {
self.records.entry(T::model_id()).or_default().remove(&id);
}
/// Get a model `T` from `id`
pub fn get<
T: Identifiable + Serialize + Send + Sync + for<'b> Deserialize<'b> + 'static,

View file

@ -22,3 +22,24 @@ fn save_load_db() {
let get_model: Model<TestModel> = db.get(data.as_str()).unwrap();
assert_eq!(get_model.read().id.to_string(), data);
}
#[test]
fn save_del_db() {
let data = "TestData".to_string();
let db = Database::in_memory();
let m = TestModel {
id: Id::String(data.clone()),
data: data.clone(),
};
db.save(m);
let get_model: Model<TestModel> = db.get(data.as_str()).unwrap();
assert_eq!(get_model.read().id.to_string(), data);
db.delete(&get_model);
let get_model: Option<Model<TestModel>> = db.get(data.as_str());
assert!(get_model.is_none());
}