Skip to main content

agdb/query/
remove_query.rs

1use crate::DbError;
2use crate::DbImpl;
3use crate::QueryIds;
4use crate::QueryMut;
5use crate::QueryResult;
6use crate::SearchQuery;
7use crate::StorageData;
8use crate::query_builder::search::SearchQueryBuilder;
9
10/// Query to remove database elements (nodes & edges). It
11/// is not an error if any of the `ids` do not already exist.
12///
13/// All properties associated with a given element are also removed.
14///
15/// If removing nodes all of its incoming and outgoing edges are
16/// also removed along with their properties.
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
19#[cfg_attr(feature = "derive", derive(agdb::DbSerialize))]
20#[cfg_attr(feature = "api", derive(agdb::TypeDefImpl))]
21#[derive(Clone, Debug, PartialEq)]
22pub struct RemoveQuery(pub QueryIds);
23
24impl QueryMut for RemoveQuery {
25    fn process<Store: StorageData>(&self, db: &mut DbImpl<Store>) -> Result<QueryResult, DbError> {
26        let mut result = QueryResult::default();
27
28        match &self.0 {
29            QueryIds::Ids(ids) => {
30                for id in ids {
31                    if db.remove(id)? {
32                        result.result -= 1;
33                    }
34                }
35            }
36            QueryIds::Search(search_query) => {
37                for db_id in search_query.search(db)? {
38                    if db.remove_id(db_id)? {
39                        result.result -= 1;
40                    }
41                }
42            }
43        }
44
45        Ok(result)
46    }
47}
48
49impl QueryMut for &RemoveQuery {
50    fn process<Store: StorageData>(&self, db: &mut DbImpl<Store>) -> Result<QueryResult, DbError> {
51        (*self).process(db)
52    }
53}
54
55impl SearchQueryBuilder for RemoveQuery {
56    fn search_mut(&mut self) -> &mut SearchQuery {
57        if let QueryIds::Search(search) = &mut self.0 {
58            search
59        } else {
60            panic!("Expected search query");
61        }
62    }
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    #[test]
70    #[should_panic]
71    fn missing_search() {
72        RemoveQuery(QueryIds::Ids(vec![])).search_mut();
73    }
74}