agdb/query/
remove_values_query.rs

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