agdb/query/
select_keys_query.rs

1use crate::DbElement;
2use crate::DbError;
3use crate::DbImpl;
4use crate::DbValue;
5use crate::Query;
6use crate::QueryIds;
7use crate::QueryResult;
8use crate::SearchQuery;
9use crate::StorageData;
10use crate::query_builder::search::SearchQueryBuilder;
11
12/// Query to select only property keys of given ids. All
13/// of the ids must exist in the database.
14///
15/// The result will be number of elements returned and the list
16/// of elements with all properties except all values will be empty.
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::ApiDef))]
21#[derive(Clone, Debug, PartialEq)]
22pub struct SelectKeysQuery(pub QueryIds);
23
24impl Query for SelectKeysQuery {
25    fn process<Store: StorageData>(&self, db: &DbImpl<Store>) -> Result<QueryResult, DbError> {
26        let mut result = QueryResult::default();
27
28        let db_ids = match &self.0 {
29            QueryIds::Ids(ids) => {
30                let mut db_ids = Vec::with_capacity(ids.len());
31
32                for query_id in ids {
33                    db_ids.push(db.db_id(query_id)?);
34                }
35
36                db_ids
37            }
38            QueryIds::Search(search_query) => search_query.search(db)?,
39        };
40
41        result.elements.reserve(db_ids.len());
42        result.result = db_ids.len() as i64;
43
44        for id in db_ids {
45            result.elements.push(DbElement {
46                id,
47                from: db.from_id(id),
48                to: db.to_id(id),
49                values: db
50                    .keys(id)?
51                    .into_iter()
52                    .map(|k| (k, DbValue::default()).into())
53                    .collect(),
54            });
55        }
56
57        Ok(result)
58    }
59}
60
61impl Query for &SelectKeysQuery {
62    fn process<Store: StorageData>(&self, db: &DbImpl<Store>) -> Result<QueryResult, DbError> {
63        (*self).process(db)
64    }
65}
66
67impl SearchQueryBuilder for SelectKeysQuery {
68    fn search_mut(&mut self) -> &mut SearchQuery {
69        if let QueryIds::Search(search) = &mut self.0 {
70            search
71        } else {
72            panic!("Expected search query");
73        }
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80
81    #[test]
82    #[should_panic]
83    fn missing_search() {
84        SelectKeysQuery(QueryIds::Ids(vec![])).search_mut();
85    }
86}