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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
use std::cell::Cell;
use std::fmt;
use std::ascii::AsciiExt;
use {bad_response, Result, Connection};
use rows::Rows;
use stmt::Statement;
use types::ToSql;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IsolationLevel {
ReadUncommitted,
ReadCommitted,
RepeatableRead,
Serializable,
}
impl IsolationLevel {
pub(crate) fn new(raw: &str) -> Result<IsolationLevel> {
if raw.eq_ignore_ascii_case("READ UNCOMMITTED") {
Ok(IsolationLevel::ReadUncommitted)
} else if raw.eq_ignore_ascii_case("READ COMMITTED") {
Ok(IsolationLevel::ReadCommitted)
} else if raw.eq_ignore_ascii_case("REPEATABLE READ") {
Ok(IsolationLevel::RepeatableRead)
} else if raw.eq_ignore_ascii_case("SERIALIZABLE") {
Ok(IsolationLevel::Serializable)
} else {
Err(bad_response().into())
}
}
fn to_sql(&self) -> &'static str {
match *self {
IsolationLevel::ReadUncommitted => "READ UNCOMMITTED",
IsolationLevel::ReadCommitted => "READ COMMITTED",
IsolationLevel::RepeatableRead => "REPEATABLE READ",
IsolationLevel::Serializable => "SERIALIZABLE",
}
}
}
#[derive(Debug)]
pub struct Config {
isolation_level: Option<IsolationLevel>,
read_only: Option<bool>,
deferrable: Option<bool>,
}
impl Default for Config {
fn default() -> Config {
Config {
isolation_level: None,
read_only: None,
deferrable: None,
}
}
}
impl Config {
pub(crate) fn build_command(&self, s: &mut String) {
let mut first = true;
if let Some(isolation_level) = self.isolation_level {
s.push_str(" ISOLATION LEVEL ");
s.push_str(isolation_level.to_sql());
first = false;
}
if let Some(read_only) = self.read_only {
if !first {
s.push(',');
}
if read_only {
s.push_str(" READ ONLY");
} else {
s.push_str(" READ WRITE");
}
first = false;
}
if let Some(deferrable) = self.deferrable {
if !first {
s.push(',');
}
if deferrable {
s.push_str(" DEFERRABLE");
} else {
s.push_str(" NOT DEFERRABLE");
}
}
}
pub fn new() -> Config {
Config::default()
}
pub fn isolation_level(&mut self, isolation_level: IsolationLevel) -> &mut Config {
self.isolation_level = Some(isolation_level);
self
}
pub fn read_only(&mut self, read_only: bool) -> &mut Config {
self.read_only = Some(read_only);
self
}
pub fn deferrable(&mut self, deferrable: bool) -> &mut Config {
self.deferrable = Some(deferrable);
self
}
}
pub struct Transaction<'conn> {
conn: &'conn Connection,
depth: u32,
savepoint_name: Option<String>,
commit: Cell<bool>,
finished: bool,
}
impl<'a> fmt::Debug for Transaction<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Transaction")
.field("commit", &self.commit.get())
.field("depth", &self.depth)
.finish()
}
}
impl<'conn> Drop for Transaction<'conn> {
fn drop(&mut self) {
if !self.finished {
let _ = self.finish_inner();
}
}
}
impl<'conn> Transaction<'conn> {
pub(crate) fn new(conn: &'conn Connection, depth: u32) -> Transaction<'conn> {
Transaction {
conn: conn,
depth: depth,
savepoint_name: None,
commit: Cell::new(false),
finished: false,
}
}
pub(crate) fn conn(&self) -> &'conn Connection {
self.conn
}
pub(crate) fn depth(&self) -> u32 {
self.depth
}
fn finish_inner(&mut self) -> Result<()> {
let mut conn = self.conn.0.borrow_mut();
debug_assert!(self.depth == conn.trans_depth);
conn.trans_depth -= 1;
match (self.commit.get(), &self.savepoint_name) {
(false, &Some(ref sp)) => conn.quick_query(&format!("ROLLBACK TO {}", sp))?,
(false, &None) => conn.quick_query("ROLLBACK")?,
(true, &Some(ref sp)) => conn.quick_query(&format!("RELEASE {}", sp))?,
(true, &None) => conn.quick_query("COMMIT")?,
};
Ok(())
}
pub fn prepare(&self, query: &str) -> Result<Statement<'conn>> {
self.conn.prepare(query)
}
pub fn prepare_cached(&self, query: &str) -> Result<Statement<'conn>> {
self.conn.prepare_cached(query)
}
pub fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64> {
self.conn.execute(query, params)
}
pub fn query<'a>(&'a self, query: &str, params: &[&ToSql]) -> Result<Rows> {
self.conn.query(query, params)
}
pub fn batch_execute(&self, query: &str) -> Result<()> {
self.conn.batch_execute(query)
}
pub fn transaction<'a>(&'a self) -> Result<Transaction<'a>> {
self.savepoint("sp")
}
pub fn savepoint<'a>(&'a self, name: &str) -> Result<Transaction<'a>> {
let mut conn = self.conn.0.borrow_mut();
check_desync!(conn);
assert!(
conn.trans_depth == self.depth,
"`savepoint` may only be called on the active transaction"
);
conn.quick_query(&format!("SAVEPOINT {}", name))?;
conn.trans_depth += 1;
Ok(Transaction {
conn: self.conn,
depth: self.depth + 1,
savepoint_name: Some(name.to_owned()),
commit: Cell::new(false),
finished: false,
})
}
pub fn connection(&self) -> &'conn Connection {
self.conn
}
pub fn is_active(&self) -> bool {
self.conn.0.borrow().trans_depth == self.depth
}
pub fn set_config(&self, config: &Config) -> Result<()> {
let mut command = "SET TRANSACTION".to_owned();
config.build_command(&mut command);
self.batch_execute(&command)
}
pub fn will_commit(&self) -> bool {
self.commit.get()
}
pub fn set_commit(&self) {
self.commit.set(true);
}
pub fn set_rollback(&self) {
self.commit.set(false);
}
pub fn commit(self) -> Result<()> {
self.set_commit();
self.finish()
}
pub fn finish(mut self) -> Result<()> {
self.finished = true;
self.finish_inner()
}
}