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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
const DEFAULT: &'static str = "default";
const ORDER_BY: &'static str = "order by";
const LIMIT: &'static str = "limit";
const OFFSET: &'static str = "offset";
const ASC: &'static str = " asc";
const DESC: &'static str = " desc";
pub trait Options {
fn module(&self) -> Option<&str>;
fn table_name(&self) -> &str;
fn order_options(&self) -> Option<OrderOptions>;
fn page_options(&self) -> Option<PageOptions>;
}
pub fn parse_options<T: Options>(options: &T) -> String {
let table_name = options
.module()
.or_else(|| Some(DEFAULT))
.map(|module| format!("{}::{}", module, options.table_name()))
.unwrap();
let mut stmt = String::default();
if let Some(OrderOptions {
order_by,
order_direction,
}) = options.order_options().clone()
{
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(Clone)]
pub enum OrderDir {
Asc,
Desc,
}
#[derive(Clone)]
pub struct OrderOptions {
pub order_by: String,
pub order_direction: Option<OrderDir>,
}
#[derive(Clone)]
pub struct PageOptions {
pub limit: u32,
pub offset: Option<u32>,
}
pub struct SelectOptions<'a> {
pub table_name: &'a str,
pub module: Option<&'a str>,
pub order_options: Option<OrderOptions>,
pub page_options: Option<PageOptions>,
}
impl<'a> Options for SelectOptions<'a> {
fn module(&self) -> Option<&str> {
self.module
}
fn table_name(&self) -> &str {
self.table_name
}
fn order_options(&self) -> Option<OrderOptions> {
self.order_options.clone()
}
fn page_options(&self) -> Option<PageOptions> {
self.page_options.clone()
}
}