1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum Direction {
6 Asc,
8 Desc,
10}
11
12#[derive(Debug, Clone, PartialEq, Eq)]
15pub struct ListQuery {
16 pub page: i64,
18 pub per_page: i64,
20 pub search: Option<String>,
22 pub sort: Option<(String, Direction)>,
25}
26
27impl ListQuery {
28 pub fn offset(&self) -> i64 {
31 (self.page.max(1) - 1) * self.per_page
32 }
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct Page<T> {
38 pub rows: Vec<T>,
40 pub total: i64,
42}
43
44pub 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}