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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
const ORDER_BY: &str = "order by";
const LIMIT: &str = "limit";
const OFFSET: &str = "offset";
const ASC: &str = " asc";
const DESC: &str = " desc";
pub trait Options {
fn order_options(&self) -> Option<OrderOptions>;
fn page_options(&self) -> Option<PageOptions>;
}
pub fn parse_options<T: Options>(options: &T, table_name: impl Into<String>, result_fields: Vec<&str>) -> String {
let mut stmt = String::default();
let table_name = table_name.into();
if let Some(OrderOptions {
order_by,
order_direction,
}) = options.order_options().clone()
{
if !result_fields.contains(&order_by.as_str()) {
panic!("'order by' value must be one of {:#?}", result_fields)
}
stmt.push_str(format!(" {} {}.{}", ORDER_BY, table_name, order_by).as_str());
if let Some(OrderDir::Desc) = order_direction {
stmt.push_str(DESC)
} else {
stmt.push_str(ASC)
}
}
if let Some(PageOptions { limit, offset }) = options.page_options().clone() {
stmt.push_str(format!(" {} {}", LIMIT, limit).as_str());
if let Some(off) = offset {
stmt.push_str(format!(" {} {}", OFFSET, off).as_str());
}
}
stmt
}
#[derive(Debug, Clone)]
pub enum OrderDir {
Asc,
Desc,
}
#[derive(Debug, Clone)]
pub struct OrderOptions {
pub order_by: String,
pub order_direction: Option<OrderDir>,
}
#[derive(Debug, Clone)]
pub struct PageOptions {
pub limit: u32,
pub offset: Option<u32>,
}
#[derive(Debug, Clone)]
pub struct SelectOptions {
pub order_options: Option<OrderOptions>,
pub page_options: Option<PageOptions>,
}
impl Options for SelectOptions {
fn order_options(&self) -> Option<OrderOptions> {
self.order_options.clone()
}
fn page_options(&self) -> Option<PageOptions> {
self.page_options.clone()
}
}