easy_sqlx_core/sql/dialects/
page.rs

1#[derive(Clone, Debug)]
2pub enum OrderType {
3    Asc,
4    Desc,
5    None,
6}
7
8impl OrderType {
9    pub fn sql(&self) -> String {
10        match self {
11            OrderType::Asc => "asc".to_string(),
12            OrderType::Desc => "desc".to_string(),
13            OrderType::None => "".to_string(),
14        }
15    }
16}
17
18#[derive(Clone, Debug)]
19pub struct Order {
20    pub field: String,
21    pub order_type: OrderType,
22}
23
24impl Order {
25    /// 字段升序
26    pub fn asc(field: String) -> Self {
27        Self {
28            field,
29            order_type: OrderType::Asc,
30        }
31    }
32    /// 字段降序
33    pub fn desc(field: String) -> Self {
34        Self {
35            field,
36            order_type: OrderType::Desc,
37        }
38    }
39    /// 字段默认顺序
40    pub fn new(field: String) -> Self {
41        Self {
42            field,
43            order_type: OrderType::None,
44        }
45    }
46}
47
48pub struct PageRequest {
49    /// 每页记录数
50    page_size: usize,
51    /// 页码,从 1 开始
52    page_no: usize,
53}
54
55impl PageRequest {
56    pub fn new(page_size: usize, page_no: usize) -> Self {
57        Self { page_no, page_size }
58    }
59
60    pub fn get_page_no(&self) -> usize {
61        if self.page_no <= 0 {
62            1
63        } else {
64            self.page_no
65        }
66    }
67
68    pub fn get_page_size(&self) -> usize {
69        if self.page_size <= 0 {
70            20
71        } else {
72            self.page_size
73        }
74    }
75}
76
77#[derive(Default)]
78pub struct PageResult<O>
79where
80    O: std::marker::Send,
81    O: Unpin,
82{
83    /// 每页记录数
84    pub page_size: usize,
85    /// 页码,从 1 开始
86    pub page_no: usize,
87    /// 总记录数
88    pub total: usize,
89    /// 总页数
90    pub page_count: usize,
91    /// 记录
92    pub records: Vec<O>,
93}
94
95impl<O> PageResult<O>
96where
97    O: std::marker::Send,
98    O: Unpin,
99{
100    /// 设置总记录数,同时计算总页数
101    pub fn set_total(&mut self, total: usize) {
102        self.total = total;
103        if total == 0 {
104            self.page_count = 0;
105        } else {
106            let page_count = total / self.page_size;
107            if total % self.page_size != 0 {
108                self.page_count = page_count + 1;
109            } else {
110                self.page_count = page_count
111            }
112        }
113    }
114}