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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
extern crate time;
use libc::{c_int, c_double, c_char};
use std::ffi::CStr;
use std::mem;
use std::str;
use super::ffi;
use super::{Result, Error, str_to_cstring};
pub use ffi::sqlite3_stmt;
pub use ffi::sqlite3_column_type;
pub use ffi::{SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB, SQLITE_NULL};
const SQLITE_DATETIME_FMT: &'static str = "%Y-%m-%d %H:%M:%S";
pub trait ToSql {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int;
}
pub trait FromSql: Sized {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<Self>;
unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool {
true
}
}
macro_rules! raw_to_impl(
($t:ty, $f:ident) => (
impl ToSql for $t {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
ffi::$f(stmt, col, *self)
}
}
)
);
raw_to_impl!(c_int, sqlite3_bind_int);
raw_to_impl!(i64, sqlite3_bind_int64);
raw_to_impl!(c_double, sqlite3_bind_double);
impl ToSql for bool {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
match *self {
true => ffi::sqlite3_bind_int(stmt, col, 1),
_ => ffi::sqlite3_bind_int(stmt, col, 0),
}
}
}
impl<'a> ToSql for &'a str {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
let length = self.len();
if length > ::std::i32::MAX as usize {
return ffi::SQLITE_TOOBIG;
}
match str_to_cstring(self) {
Ok(c_str) => {
ffi::sqlite3_bind_text(stmt,
col,
c_str.as_ptr(),
length as c_int,
ffi::SQLITE_TRANSIENT())
}
Err(_) => ffi::SQLITE_MISUSE,
}
}
}
impl ToSql for String {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
(&self[..]).bind_parameter(stmt, col)
}
}
impl<'a> ToSql for &'a [u8] {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
if self.len() > ::std::i32::MAX as usize {
return ffi::SQLITE_TOOBIG;
}
ffi::sqlite3_bind_blob(stmt,
col,
mem::transmute(self.as_ptr()),
self.len() as c_int,
ffi::SQLITE_TRANSIENT())
}
}
impl ToSql for Vec<u8> {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
(&self[..]).bind_parameter(stmt, col)
}
}
impl ToSql for time::Timespec {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
let time_str = time::at_utc(*self).strftime(SQLITE_DATETIME_FMT).unwrap().to_string();
time_str.bind_parameter(stmt, col)
}
}
impl<T: ToSql> ToSql for Option<T> {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
match *self {
None => ffi::sqlite3_bind_null(stmt, col),
Some(ref t) => t.bind_parameter(stmt, col),
}
}
}
#[derive(Copy,Clone)]
pub struct Null;
impl ToSql for Null {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
ffi::sqlite3_bind_null(stmt, col)
}
}
macro_rules! raw_from_impl(
($t:ty, $f:ident, $c:expr) => (
impl FromSql for $t {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<$t> {
Ok(ffi::$f(stmt, col))
}
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool {
sqlite3_column_type(stmt, col) == $c
}
}
)
);
raw_from_impl!(c_int, sqlite3_column_int, ffi::SQLITE_INTEGER);
raw_from_impl!(i64, sqlite3_column_int64, ffi::SQLITE_INTEGER);
raw_from_impl!(c_double, sqlite3_column_double, ffi::SQLITE_FLOAT);
impl FromSql for bool {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<bool> {
match ffi::sqlite3_column_int(stmt, col) {
0 => Ok(false),
_ => Ok(true),
}
}
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool {
sqlite3_column_type(stmt, col) == ffi::SQLITE_INTEGER
}
}
impl FromSql for String {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<String> {
let c_text = ffi::sqlite3_column_text(stmt, col);
if c_text.is_null() {
Ok("".to_string())
} else {
let c_slice = CStr::from_ptr(c_text as *const c_char).to_bytes();
let utf8_str = try!(str::from_utf8(c_slice));
Ok(utf8_str.into())
}
}
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool {
sqlite3_column_type(stmt, col) == ffi::SQLITE_TEXT
}
}
impl FromSql for Vec<u8> {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<Vec<u8>> {
use std::slice::from_raw_parts;
let c_blob = ffi::sqlite3_column_blob(stmt, col);
let len = ffi::sqlite3_column_bytes(stmt, col);
assert!(len >= 0,
"unexpected negative return from sqlite3_column_bytes");
let len = len as usize;
Ok(from_raw_parts(mem::transmute(c_blob), len).to_vec())
}
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool {
sqlite3_column_type(stmt, col) == ffi::SQLITE_BLOB
}
}
impl FromSql for time::Timespec {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<time::Timespec> {
let col_str = FromSql::column_result(stmt, col);
col_str.and_then(|txt: String| {
match time::strptime(&txt, SQLITE_DATETIME_FMT) {
Ok(tm) => Ok(tm.to_timespec()),
Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))),
}
})
}
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool {
String::column_has_valid_sqlite_type(stmt, col)
}
}
impl<T: FromSql> FromSql for Option<T> {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<Option<T>> {
if sqlite3_column_type(stmt, col) == ffi::SQLITE_NULL {
Ok(None)
} else {
FromSql::column_result(stmt, col).map(|t| Some(t))
}
}
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool {
sqlite3_column_type(stmt, col) == ffi::SQLITE_NULL ||
T::column_has_valid_sqlite_type(stmt, col)
}
}
#[cfg(test)]
mod test {
use Connection;
use super::time;
use Error;
use libc::{c_int, c_double};
fn checked_memory_handle() -> Connection {
let db = Connection::open_in_memory().unwrap();
db.execute_batch("CREATE TABLE foo (b BLOB, t TEXT, i INTEGER, f FLOAT, n)").unwrap();
db
}
#[test]
fn test_blob() {
let db = checked_memory_handle();
let v1234 = vec![1u8, 2, 3, 4];
db.execute("INSERT INTO foo(b) VALUES (?)", &[&v1234]).unwrap();
let v: Vec<u8> = db.query_row("SELECT b FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!(v, v1234);
}
#[test]
fn test_str() {
let db = checked_memory_handle();
let s = "hello, world!";
db.execute("INSERT INTO foo(t) VALUES (?)", &[&s.to_string()]).unwrap();
let from: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!(from, s);
}
#[test]
fn test_timespec() {
let db = checked_memory_handle();
let ts = time::Timespec {
sec: 10_000,
nsec: 0,
};
db.execute("INSERT INTO foo(t) VALUES (?)", &[&ts]).unwrap();
let from: time::Timespec = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!(from, ts);
}
#[test]
fn test_option() {
let db = checked_memory_handle();
let s = Some("hello, world!");
let b = Some(vec![1u8, 2, 3, 4]);
db.execute("INSERT INTO foo(t) VALUES (?)", &[&s]).unwrap();
db.execute("INSERT INTO foo(b) VALUES (?)", &[&b]).unwrap();
let mut stmt = db.prepare("SELECT t, b FROM foo ORDER BY ROWID ASC").unwrap();
let mut rows = stmt.query(&[]).unwrap();
let row1 = rows.next().unwrap().unwrap();
let s1: Option<String> = row1.get(0);
let b1: Option<Vec<u8>> = row1.get(1);
assert_eq!(s.unwrap(), s1.unwrap());
assert!(b1.is_none());
let row2 = rows.next().unwrap().unwrap();
let s2: Option<String> = row2.get(0);
let b2: Option<Vec<u8>> = row2.get(1);
assert!(s2.is_none());
assert_eq!(b, b2);
}
#[test]
fn test_mismatched_types() {
fn is_invalid_column_type(err: Error) -> bool {
match err {
Error::InvalidColumnType => true,
_ => false,
}
}
let db = checked_memory_handle();
db.execute("INSERT INTO foo(b, t, i, f) VALUES (X'0102', 'text', 1, 1.5)",
&[])
.unwrap();
let mut stmt = db.prepare("SELECT b, t, i, f, n FROM foo").unwrap();
let mut rows = stmt.query(&[]).unwrap();
let row = rows.next().unwrap().unwrap();
assert_eq!(vec![1, 2], row.get_checked::<Vec<u8>>(0).unwrap());
assert_eq!("text", row.get_checked::<String>(1).unwrap());
assert_eq!(1, row.get_checked::<c_int>(2).unwrap());
assert_eq!(1.5, row.get_checked::<c_double>(3).unwrap());
assert!(row.get_checked::<Option<c_int>>(4).unwrap().is_none());
assert!(row.get_checked::<Option<c_double>>(4).unwrap().is_none());
assert!(row.get_checked::<Option<String>>(4).unwrap().is_none());
assert!(is_invalid_column_type(row.get_checked::<c_int>(0).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<c_int>(0).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i64>(0).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<c_double>(0).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<String>(0).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<time::Timespec>(0).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<Option<c_int>>(0).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<c_int>(1).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i64>(1).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<c_double>(1).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<Vec<u8>>(1).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<Option<c_int>>(1).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<c_double>(2).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<String>(2).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<Vec<u8>>(2).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<time::Timespec>(2).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<Option<c_double>>(2).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<c_int>(3).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i64>(3).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<String>(3).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<Vec<u8>>(3).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<time::Timespec>(3).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<Option<c_int>>(3).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<c_int>(4).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i64>(4).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<c_double>(4).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<String>(4).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<Vec<u8>>(4).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<time::Timespec>(4).err().unwrap()));
}
}