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
133
134
135
136
137
138
139
140
use dao::Value;
use database::SqlOption;
use std::fmt;
pub struct SqlFrag{
pub sql:String,
pub params:Vec<Value>,
pub sql_options: Vec<SqlOption>,
}
impl fmt::Display for SqlFrag{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "{}", self.sql));
let mut do_comma = false;
try!(write!(f, "["));
for param in &self.params{
if do_comma {
try!(write!(f, ", "));
} else {
do_comma = true;
}
try!(write!(f, "{}", param));
}
write!(f, "]")
}
}
impl SqlFrag{
#[inline]
pub fn new(sql_options: Vec<SqlOption>)->Self{
SqlFrag{sql:String::new(), params:vec![], sql_options: sql_options}
}
#[inline]
pub fn append(&mut self, str:&str)->&mut Self{
self.sql.push_str(str);
self
}
#[inline]
pub fn appendln(&mut self, str:&str)->&mut Self{
self.append(str);
self.ln()
}
#[inline]
pub fn tab(&mut self)->&mut Self{
self.append(" ")
}
#[inline]
pub fn tabs(&mut self, n:u32)->&mut Self{
for _ in 0..n{
self.tab();
}
self
}
#[inline]
pub fn ln(&mut self)->&mut Self{
self.append("\n")
}
#[inline]
pub fn ln_tab(&mut self)->&mut Self{
self.ln();
self.tab()
}
#[inline]
pub fn ln_tabs(&mut self, n:u32)->&mut Self{
self.ln();
self.tabs(n)
}
#[inline]
pub fn comma(&mut self)->&mut Self{
self.append(",")
}
#[inline]
pub fn sp(&mut self)->&mut Self{
self.append(" ")
}
#[inline]
pub fn spaces(&mut self, n: i32)->&mut Self{
for _ in 0..n{
self.sp();
}
self
}
#[inline]
fn river(&mut self, str: &str)->&mut Self{
let river_size:i32 = 9;
let trim = str.trim();
let diff:i32 = river_size - trim.len() as i32;
if diff > 0 {
self.spaces(diff);
}
self.append(trim);
self.sp()
}
#[inline]
pub fn left_river(&mut self, str: &str)->&mut Self{
self.ln();
self.river(str)
}
#[inline]
pub fn right_river(&mut self, str: &str)->&mut Self{
self.ln();
self.river("");
self.append(str)
}
#[inline]
pub fn commasp(&mut self)->&mut Self{
self.comma().sp()
}
#[inline]
pub fn comment(&mut self, comment: &str)->&mut Self{
self.append("-- ");
self.append(comment)
}
pub fn parameter(&mut self, param:Value){
self.params.push(param);
if self.sql_options.contains(&SqlOption::UsesNumberedParam){
let numbered_param = format!("${} ", self.params.len());
self.append(&numbered_param);
}
else if self.sql_options.contains(&SqlOption::UsesQuestionMark){
self.append("?");
}
}
}