Skip to main content

ignite_core/
query.rs

1//! What the list view asks for: the page, the search text and the sort.
2
3/// The sort direction of a list.
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum Direction {
6    /// Smallest first.
7    Asc,
8    /// Largest first.
9    Desc,
10}
11
12/// What the list view asks a resource for. Only `search` and `sort` come from
13/// the user, through the query string.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct ListQuery {
16    /// The page to return, 1-based.
17    pub page: i64,
18    /// The number of rows on a page.
19    pub per_page: i64,
20    /// The search text, if the user entered any.
21    pub search: Option<String>,
22    /// The column key to sort by and the direction, if the user chose one.
23    /// The key is one of the resource's sortable columns.
24    pub sort: Option<(String, Direction)>,
25}
26
27impl ListQuery {
28    /// The number of rows to skip before the page starts. A page below 1 is
29    /// treated as 1.
30    pub fn offset(&self) -> i64 {
31        (self.page.max(1) - 1) * self.per_page
32    }
33}
34
35/// One page of rows and the total number of matching rows, for the pager.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct Page<T> {
38    /// The rows on this page.
39    pub rows: Vec<T>,
40    /// The number of rows across all pages.
41    pub total: i64,
42}
43
44/// Escapes `%`, `_` and `\` in search text, so a LIKE pattern matches them
45/// literally. Use it inside `%...%` and pass `ESCAPE '\\'` where the database
46/// needs the escape character named.
47pub fn escape_like(text: &str) -> String {
48    let mut escaped = String::with_capacity(text.len());
49    for c in text.chars() {
50        if matches!(c, '%' | '_' | '\\') {
51            escaped.push('\\');
52        }
53        escaped.push(c);
54    }
55    escaped
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    fn query(page: i64, per_page: i64) -> ListQuery {
63        ListQuery {
64            page,
65            per_page,
66            search: None,
67            sort: None,
68        }
69    }
70
71    #[test]
72    fn offset_counts_full_pages_before_the_current_one() {
73        assert_eq!(query(1, 20).offset(), 0);
74        assert_eq!(query(3, 20).offset(), 40);
75    }
76
77    #[test]
78    fn offset_treats_a_page_below_one_as_the_first() {
79        assert_eq!(query(0, 20).offset(), 0);
80        assert_eq!(query(-4, 20).offset(), 0);
81    }
82
83    #[test]
84    fn escape_like_escapes_wildcards_and_the_escape_character() {
85        assert_eq!(escape_like("50%_off\\"), "50\\%\\_off\\\\");
86        assert_eq!(escape_like("plain"), "plain");
87    }
88}