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    pub fn new() -> Self {
25        Self::default()
26    }
27
28    #[must_use]
29    pub const fn is_empty(&self) -> bool {
30        self.filter.is_none() && self.limit.is_none() && self.sort.is_none()
31    }
32
33    ///
34    /// SHAPES
35    ///
36
37    #[must_use]
38    pub fn one<E: EntityKind>(self, value: impl FieldValue) -> Self {
39        self.filter(|f| f.eq(E::PRIMARY_KEY, value))
40    }
41
42    #[must_use]
43    pub fn only<E: EntityKind>(self) -> Self {
44        self.filter(|f| f.eq(E::PRIMARY_KEY, ()))
45    }
46
47    #[must_use]
48    pub fn many<E: EntityKind>(self, values: impl IntoIterator<Item = impl FieldValue>) -> Self {
49        self.filter(move |f| f.in_iter(E::PRIMARY_KEY, values))
50    }
51
52    // all just overrides, same as calling new
53    #[must_use]
54    pub fn all() -> Self {
55        Self::default()
56    }
57}
58
59impl FilterSlot for LoadQuery {
60    fn filter_slot(&mut self) -> &mut Option<FilterExpr> {
61        &mut self.filter
62    }
63}
64
65impl LimitSlot for LoadQuery {
66    fn limit_slot(&mut self) -> &mut Option<LimitExpr> {
67        &mut self.limit
68    }
69}
70
71impl SortSlot for LoadQuery {
72    fn sort_slot(&mut self) -> &mut Option<SortExpr> {
73        &mut self.sort
74    }
75}
76
77impl<E: EntityKind> QueryValidate<E> for LoadQuery {
78    fn validate(&self) -> Result<(), QueryError> {
79        if let Some(filter) = &self.filter {
80            QueryValidate::<E>::validate(filter)?;
81        }
82        if let Some(limit) = &self.limit {
83            QueryValidate::<E>::validate(limit)?;
84        }
85        if let Some(sort) = &self.sort {
86            QueryValidate::<E>::validate(sort)?;
87        }
88
89        Ok(())
90    }
91}