cat_gateway/db/event/common/
query_limits.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//! `QueryLimits` query argument object.

use std::fmt::Display;

use crate::service::common::types::generic::query::pagination::{Limit, Page};

/// A query limits struct.
pub(crate) struct QueryLimits(QueryLimitsInner);

/// `QueryLimits` inner enum representation.
enum QueryLimitsInner {
    /// Return all entries without any `LIMIT` and `OFFSET` parameters
    All,
    /// Specifies `LIMIT` parameter
    Limit(u64),
    /// Specifies `LIMIT` and `OFFSET` parameters
    LimitAndOffset(u64, u64),
}

impl Display for QueryLimits {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.0 {
            QueryLimitsInner::All => write!(f, ""),
            QueryLimitsInner::Limit(limit) => write!(f, "LIMIT {limit}"),
            QueryLimitsInner::LimitAndOffset(limit, offset) => {
                write!(f, "LIMIT {limit} OFFSET {offset}")
            },
        }
    }
}

impl QueryLimits {
    /// Create a `QueryLimits` object without the any limits.
    #[allow(dead_code)]
    pub(crate) const ALL: QueryLimits = Self(QueryLimitsInner::All);
    /// Create a `QueryLimits` object with the limit equals to `1`.
    #[allow(dead_code)]
    pub(crate) const ONE: QueryLimits = Self(QueryLimitsInner::Limit(1));

    /// Create a `QueryLimits` object from the service `Limit` and `Page` values.
    pub(crate) fn new(limit: Option<Limit>, page: Option<Page>) -> Self {
        match (limit, page) {
            (Some(limit), Some(page)) => {
                Self(QueryLimitsInner::LimitAndOffset(limit.into(), page.into()))
            },
            (Some(limit), None) => {
                Self(QueryLimitsInner::LimitAndOffset(
                    limit.into(),
                    Page::default().into(),
                ))
            },
            (None, Some(page)) => {
                Self(QueryLimitsInner::LimitAndOffset(
                    Limit::default().into(),
                    page.into(),
                ))
            },
            (None, None) => {
                Self(QueryLimitsInner::LimitAndOffset(
                    Limit::default().into(),
                    Page::default().into(),
                ))
            },
        }
    }
}