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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! `rust-sqlite3` is a rustic binding to the [sqlite3 API][].
//!
//! [sqlite3 API]: http://www.sqlite.org/c3ref/intro.html
//!
//! Three layers of API are provided:
//!
//!  - `mod ffi` provides exhaustive, though unsafe, [bindgen] bindings for `libsqlite.h`.
//!  - `mod core` provides a minimal safe interface to the basic sqlite3 API.
//!  - `mod types` provides `ToSql`/`FromSql` traits, and the library provides
//!     convenient `query()` and `update()` APIs.
//!
//! [bindgen]: https://github.com/crabtw/rust-bindgen
//!
//! The following example demonstrates opening a database, executing
//! DDL, and using the high-level `query()` and `update()` API. Note the
//! use of `Result` and `try!()` for error handling.
//!
//! ```rust
//! extern crate time;
//! extern crate sqlite3;
//! 
//! use time::Timespec;
//! 
//! use sqlite3::{
//!     DatabaseConnection,
//!     Query,
//!     ResultRow,
//!     ResultRowAccess,
//!     SqliteResult,
//!     StatementUpdate,
//! };
//! 
//! #[derive(Debug)]
//! struct Person {
//!     id: i32,
//!     name: String,
//!     time_created: Timespec,
//!     // TODO: data: Option<Vec<u8>>
//! }
//! 
//! pub fn main() {
//!     match io() {
//!         Ok(ppl) => println!("Found people: {:?}", ppl),
//!         Err(oops) => panic!(oops)
//!     }
//! }
//! 
//! fn io() -> SqliteResult<Vec<Person>> {
//!     let mut conn = try!(DatabaseConnection::in_memory());
//! 
//!     try!(conn.exec("CREATE TABLE person (
//!                  id              SERIAL PRIMARY KEY,
//!                  name            VARCHAR NOT NULL,
//!                  time_created    TIMESTAMP NOT NULL
//!                )"));
//! 
//!     let me = Person {
//!         id: 0,
//!         name: format!("Dan"),
//!         time_created: time::get_time(),
//!     };
//!     {
//!         let mut tx = try!(conn.prepare("INSERT INTO person (name, time_created)
//!                            VALUES ($1, $2)"));
//!         let changes = try!(tx.update(&[&me.name, &me.time_created]));
//!         assert_eq!(changes, 1);
//!     }
//! 
//!     let mut stmt = try!(conn.prepare("SELECT id, name, time_created FROM person"));
//! 
//!     let to_person = |row: &mut ResultRow| Ok(
//!         Person {
//!             id: row.get("id"),
//!             name: row.get("name"),
//!             time_created: row.get(2)
//!         });
//!     let ppl = try!(stmt.query(&[], to_person));
//!     ppl.collect()
//! }
//! ```

#![crate_name = "sqlite3"]
#![crate_type = "lib"]
#![warn(missing_docs)]

extern crate libc;
extern crate time;

#[macro_use]
extern crate bitflags;

#[macro_use]
extern crate enum_primitive;

use std::error::{Error};
use std::fmt::Display;
use std::fmt;

pub use core::Access;
pub use core::{DatabaseConnection, PreparedStatement, ResultSet, ResultRow};
pub use core::{ColIx, ParamIx};
pub use types::{FromSql, ToSql};

use self::SqliteErrorCode::SQLITE_MISUSE;

pub mod core;
pub mod types;

/// bindgen-bindings to libsqlite3
#[allow(non_camel_case_types, non_snake_case)]
#[allow(dead_code)]
#[allow(missing_docs)]
#[allow(missing_copy_implementations)]  // until I figure out rust-bindgen #89
pub mod ffi;

pub mod access;

/// Mix in `update()` convenience function.
pub trait StatementUpdate {
    /// Execute a statement after binding any parameters.
    fn update(&mut self,
              values: &[&ToSql]) -> SqliteResult<u64>;
}


impl StatementUpdate for core::PreparedStatement {
    /// Execute a statement after binding any parameters.
    ///
    /// When the statement is done, The [number of rows
    /// modified][changes] is reported.
    ///
    /// Fail with `Err(SQLITE_MISUSE)` in case the statement results
    /// in any any rows (e.g. a `SELECT` rather than `INSERT` or
    /// `UPDATE`).
    ///
    /// [changes]: http://www.sqlite.org/c3ref/changes.html
    fn update(&mut self,
              values: &[&ToSql]) -> SqliteResult<u64> {
        let check = {
            try!(bind_values(self, values));
            let mut results = self.execute();
            match try!(results.step()) {
                None => Ok(()),
                Some(_row) => Err(SqliteError {
                    kind: SQLITE_MISUSE,
                    desc: "unexpected SQLITE_ROW from update",
                    detail: None
                })
            }
        };
        check.map(|_ok| self.changes())
    }
}


/// Mix in `query_each()` convenience function.
pub trait QueryEach<F>
    where F: FnMut(&mut ResultRow) -> SqliteResult<()>
{
    /// Process rows from a query after binding parameters.
    fn query_each(&mut self,
                  values: &[&ToSql],
                  each_row: &mut F
                  ) -> SqliteResult<()>;
}

impl<F> QueryEach<F> for core::PreparedStatement
    where F: FnMut(&mut ResultRow) -> SqliteResult<()>
{
    /// Process rows from a query after binding parameters.
    ///
    /// For call `each_row(row)` for each resulting step,
    /// exiting on `Err`.
    fn query_each(&mut self,
                  values: &[&ToSql],
                  each_row: &mut F
                  ) -> SqliteResult<()>
    {
        try!(bind_values(self, values));
        let mut results = self.execute();
        loop {
            match try!(results.step()) {
                None => break,
                Some(ref mut row) => try!(each_row(row)),
            }
        }
        Ok(())
    }
}


/// Mix in `query_fold()` convenience function.
pub trait QueryFold<F, A>
    where F: Fn(&mut ResultRow, A) -> SqliteResult<A>
{
    /// Fold rows from a query after binding parameters.
    fn query_fold(&mut self,
                  values: &[&ToSql],
                  init: A,
                  each_row: F
                  ) -> SqliteResult<A>;
}


impl<F, A> QueryFold<F, A> for core::PreparedStatement
    where F: Fn(&mut ResultRow, A) -> SqliteResult<A>
{
    /// Fold rows from a query after binding parameters.
    fn query_fold(&mut self,
                  values: &[&ToSql],
                  init: A,
                  f: F
                  ) -> SqliteResult<A>
    {
        try!(bind_values(self, values));
        let mut results = self.execute();
        let mut accum = init;
        loop {
            match try!(results.step()) {
                None => break,
                Some(ref mut row) => accum = try!(f(row, accum)),
            }
        }
        Ok(accum)
    }
}


/// Mix in `query()` convenience function.
pub trait Query<F, T>
    where F: FnMut(&mut ResultRow) -> SqliteResult<T>
{
    /// Iterate over query results after binding parameters.
    ///
    /// Each of the `values` is bound to the statement (using `to_sql`)
    /// and the statement is executed.
    ///
    /// Returns an iterator over rows transformed by `txform`,
    /// which computes a value for each row (or an error).
    fn query<'stmt>(&'stmt mut self,
                    values: &[&ToSql],
                    txform: F
                ) -> SqliteResult<QueryResults<'stmt, T, F>>;
}

impl<F, T> Query<F, T> for core::PreparedStatement
    where F: FnMut(&mut ResultRow) -> SqliteResult<T>
{
    fn query<'stmt>(&'stmt mut self,
                    values: &[&ToSql],
                    txform: F
                    ) -> SqliteResult<QueryResults<'stmt, T, F>>
    {
        try!(bind_values(self, values));
        let results = self.execute();
        Ok(QueryResults { results: results, txform: txform })
    }
}

/// An iterator over transformed query results
pub struct QueryResults<'stmt, T, F>
    where F: FnMut(&mut ResultRow) -> SqliteResult<T>
{
    results: core::ResultSet<'stmt>,
    txform: F
}

impl<'stmt, T, F> Iterator for QueryResults<'stmt, T, F>
    where F: FnMut(&mut ResultRow) -> SqliteResult<T>
{
    type Item = SqliteResult<T>;

    fn next(&mut self) -> Option<SqliteResult<T>> {
        match self.results.step() {
            Ok(None) => None,
            Ok(Some(ref mut row)) => Some((self.txform)(row)),
            Err(e) => Some(Err(e))
        }
    }
}


fn bind_values(s: &mut PreparedStatement, values: &[&ToSql]) -> SqliteResult<()> {
    for (ix, v) in values.iter().enumerate() {
        let p = ix as ParamIx + 1;
        try!(v.to_sql(s, p));
    }
    Ok(())
}


/// Access result columns of a row by name or numeric index.
pub trait ResultRowAccess {
    /// Get `T` type result value from `idx`th column of a row.
    ///
    /// # Panic
    ///
    /// Panics if there is no such column or value.
    fn get<I: RowIndex + Display + Clone, T: FromSql>(&mut self, idx: I) -> T;

    /// Try to get `T` type result value from `idx`th column of a row.
    fn get_opt<I: RowIndex + Display + Clone, T: FromSql>(&mut self, idx: I) -> SqliteResult<T>;
}

impl<'res, 'row> ResultRowAccess for core::ResultRow<'res, 'row> {
    fn get<I: RowIndex + Display + Clone, T: FromSql>(&mut self, idx: I) -> T {
        match self.get_opt(idx.clone()) {
            Ok(ok) => ok,
            Err(err) => panic!("retrieving column {}: {}", idx, err)
        }
    }

    fn get_opt<I: RowIndex + Display + Clone, T: FromSql>(&mut self, idx: I) -> SqliteResult<T> {
        match idx.idx(self) {
            Some(idx) => FromSql::from_sql(self, idx),
            None => Err(SqliteError {
                kind: SQLITE_MISUSE,
                desc: "no such row name/number",
                detail: Some(format!("{}", idx))
            })
        }
    }

}

/// A trait implemented by types that can index into columns of a row.
///
/// *inspired by sfackler's [RowIndex][]*
/// [RowIndex]: http://www.rust-ci.org/sfackler/rust-postgres/doc/postgres/trait.RowIndex.html
pub trait RowIndex {
    /// Try to convert `self` to an index into a row.
    fn idx(&self, row: &mut ResultRow) -> Option<ColIx>;
}

impl RowIndex for ColIx {
    /// Index into a row directly by uint.
    fn idx(&self, _row: &mut ResultRow) -> Option<ColIx> { Some(*self) }
}

impl RowIndex for &'static str {
    /// Index into a row by column name.
    ///
    /// *TODO: figure out how to use lifetime of row rather than
    /// `static`.*
    fn idx(&self, row: &mut ResultRow) -> Option<ColIx> {
        let mut ixs = 0 .. row.column_count();
        ixs.find(|ix| row.with_column_name(*ix, false, |name| name == *self))
    }
}


/// The type used for returning and propagating sqlite3 errors.
#[must_use]
pub type SqliteResult<T> = Result<T, SqliteError>;

/// Result codes for errors.
///
/// cf. [sqlite3 result codes][codes].
///
/// Note `SQLITE_OK` is not included; we use `Ok(...)` instead.
///
/// Likewise, in place of `SQLITE_ROW` and `SQLITE_DONE`, we return
/// `Some(...)` or `None` from `ResultSet::next()`.
///
/// [codes]: http://www.sqlite.org/c3ref/c_abort.html
enum_from_primitive! {
    #[derive(Debug, PartialEq, Eq, Copy, Clone)]
    #[allow(non_camel_case_types)]
    #[allow(missing_docs)]
    pub enum SqliteErrorCode {
        SQLITE_ERROR     =  1,
        SQLITE_INTERNAL  =  2,
        SQLITE_PERM      =  3,
        SQLITE_ABORT     =  4,
        SQLITE_BUSY      =  5,
        SQLITE_LOCKED    =  6,
        SQLITE_NOMEM     =  7,
        SQLITE_READONLY  =  8,
        SQLITE_INTERRUPT =  9,
        SQLITE_IOERR     = 10,
        SQLITE_CORRUPT   = 11,
        SQLITE_NOTFOUND  = 12,
        SQLITE_FULL      = 13,
        SQLITE_CANTOPEN  = 14,
        SQLITE_PROTOCOL  = 15,
        SQLITE_EMPTY     = 16,
        SQLITE_SCHEMA    = 17,
        SQLITE_TOOBIG    = 18,
        SQLITE_CONSTRAINT= 19,
        SQLITE_MISMATCH  = 20,
        SQLITE_MISUSE    = 21,
        SQLITE_NOLFS     = 22,
        SQLITE_AUTH      = 23,
        SQLITE_FORMAT    = 24,
        SQLITE_RANGE     = 25,
        SQLITE_NOTADB    = 26
    }
}

/// Error results
#[derive(Debug, PartialEq, Eq)]
pub struct SqliteError {
    /// kind of error, by code
    pub kind: SqliteErrorCode,
    /// static error description
    pub desc: &'static str,
    /// dynamic detail (optional)
    pub detail: Option<String>
}

impl Display for SqliteError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.detail {
            Some(ref x) => f.write_fmt(format_args!("{} ({})", x, self.kind as u32)),
            None => f.write_fmt(format_args!("{} ({})", self.desc, self.kind as u32))
        }
    }
}

impl SqliteError {
    /// Get a detailed description of the error
    pub fn detail(&self) -> Option<String> { self.detail.clone() }
}

impl Error for SqliteError {
    fn description(&self) -> &str { self.desc }
    fn cause(&self) -> Option<&Error> { None }
}


/// Fundamental Datatypes
enum_from_primitive! {
    #[derive(Debug, PartialEq, Eq, Copy, Clone)]
    #[allow(non_camel_case_types)]
    #[allow(missing_docs)]
    pub enum ColumnType {
        SQLITE_INTEGER = 1,
        SQLITE_FLOAT   = 2,
        SQLITE_TEXT    = 3,
        SQLITE_BLOB    = 4,
        SQLITE_NULL    = 5
    }
}

#[cfg(test)]
mod bind_tests {
    use super::{DatabaseConnection, ResultSet};
    use super::{ResultRowAccess};
    use super::{SqliteResult};

    #[test]
    fn bind_fun() {
        fn go() -> SqliteResult<()> {
            let mut database = try!(DatabaseConnection::in_memory());

            try!(database.exec(
                "BEGIN;
                CREATE TABLE test (id int, name text, address text);
                INSERT INTO test (id, name, address) VALUES (1, 'John Doe', '123 w Pine');
                COMMIT;"));

            {
                let mut tx = try!(database.prepare(
                    "INSERT INTO test (id, name, address) VALUES (?, ?, ?)"));
                assert_eq!(tx.bind_parameter_count(), 3);
                try!(tx.bind_int(1, 2));
                try!(tx.bind_text(2, "Jane Doe"));
                try!(tx.bind_text(3, "345 e Walnut"));
                let mut results = tx.execute();
                assert!(results.step().ok().unwrap().is_none());
            }
            assert_eq!(database.changes(), 1);

            let mut q = try!(database.prepare("select * from test order by id"));
            let mut rows = q.execute();
            match rows.step() {
                Ok(Some(ref mut row)) => {
                    assert_eq!(row.get::<u32, i32>(0), 1);
                    // TODO let name = q.get_text(1);
                    // assert_eq!(name.as_slice(), "John Doe");
                },
                _ => panic!()
            }

            match rows.step() {
                Ok(Some(ref mut row)) => {
                    assert_eq!(row.get::<u32, i32>(0), 2);
                    //TODO let addr = q.get_text(2);
                    // assert_eq!(addr.as_slice(), "345 e Walnut");
                },
                _ => panic!()
            }
            Ok(())
        }
        match go() {
            Ok(_) => (),
            Err(e) => panic!("oops! {:?}", e)
        }
    }

    fn with_query<T, F>(sql: &str, mut f: F) -> SqliteResult<T>
        where F: FnMut(&mut ResultSet) -> T
    {
        let db = try!(DatabaseConnection::in_memory());
        let mut s = try!(db.prepare(sql));
        let mut rows = s.execute();
        let x = f(&mut rows);
        return Ok(x);
    }

    #[test]
    fn named_rowindex() {
        fn go() -> SqliteResult<(u32, i32)> {
            let mut count = 0;
            let mut sum = 0i32;

            with_query("select 1 as col1
                       union all
                       select 2", |rows| {
                loop {
                    match rows.step() {
                        Ok(Some(ref mut row)) => {
                            count += 1;
                            sum += row.column_int(0);
                        },
                        _ => break
                    }
                }
                (count, sum)
            })
        }
        assert_eq!(go(), Ok((2, 3)))
    }

    #[test]
    fn err_with_detail() {
        let io = || {
            let mut conn = try!(DatabaseConnection::in_memory());
            conn.exec("CREATE gobbledygook")
        };

        let go = || match io() {
            Ok(_) => panic!(),
            Err(oops) => {
                format!("{:?}: {}: {}",
                        oops.kind, oops.desc,
                        oops.detail.unwrap())
            }
        };

        let expected = "SQLITE_ERROR: sqlite3_exec: near \"gobbledygook\": syntax error";
        assert_eq!(go(), expected.to_string())
    }
}