icydb_core/db/query/
load.rs

1use crate::{
2    db::{
3        primitives::{FilterExpr, FilterSlot, LimitExpr, LimitSlot, SortExpr, SortSlot},
4        query::{QueryError, QueryValidate, prelude::*},
5    },
6    traits::{EntityKind, FieldValue},
7};
8use candid::CandidType;
9use serde::{Deserialize, Serialize};
10
11///
12/// LoadQuery
13///
14
15#[derive(CandidType, Clone, Debug, Default, Deserialize, Serialize)]
16pub struct LoadQuery {
17    pub filter: Option<FilterExpr>,
18    pub limit: Option<LimitExpr>,
19    pub sort: Option<SortExpr>,
20}
21
22impl LoadQuery {
23    #[must_use]
24    /// Construct an empty load query.
25    pub fn new() -> Self {
26        Self::default()
27    }
28
29    #[must_use]
30    pub const fn is_empty(&self) -> bool {
31        self.filter.is_none() && self.limit.is_none() && self.sort.is_none()
32    }
33
34    ///
35    /// SHAPES
36    ///
37
38    #[must_use]
39    /// Filter by a single primary key value.
40    pub fn one<E: EntityKind>(self, value: impl FieldValue) -> Self {
41        self.filter(|f| f.eq(E::PRIMARY_KEY, value))
42    }
43
44    #[must_use]
45    /// Filter by primary key presence (unit key).
46    pub fn only<E: EntityKind>(self) -> Self {
47        self.filter(|f| f.eq(E::PRIMARY_KEY, ()))
48    }
49
50    #[must_use]
51    /// Filter by a set of primary key values.
52    pub fn many<E: EntityKind>(self, values: impl IntoIterator<Item = impl FieldValue>) -> Self {
53        self.filter(move |f| f.in_iter(E::PRIMARY_KEY, values))
54    }
55
56    // all just overrides, same as calling new
57    #[must_use]
58    /// Read all rows (alias for `LoadQuery::default()`).
59    pub fn all() -> Self {
60        Self::default()
61    }
62}
63
64impl FilterSlot for LoadQuery {
65    fn filter_slot(&mut self) -> &mut Option<FilterExpr> {
66        &mut self.filter
67    }
68}
69
70impl LimitSlot for LoadQuery {
71    fn limit_slot(&mut self) -> &mut Option<LimitExpr> {
72        &mut self.limit
73    }
74}
75
76impl SortSlot for LoadQuery {
77    fn sort_slot(&mut self) -> &mut Option<SortExpr> {
78        &mut self.sort
79    }
80}
81
82impl<E: EntityKind> QueryValidate<E> for LoadQuery {
83    fn validate(&self) -> Result<(), QueryError> {
84        if let Some(filter) = &self.filter {
85            QueryValidate::<E>::validate(filter)?;
86        }
87        if let Some(limit) = &self.limit {
88            QueryValidate::<E>::validate(limit)?;
89        }
90        if let Some(sort) = &self.sort {
91            QueryValidate::<E>::validate(sort)?;
92        }
93
94        Ok(())
95    }
96}