Merge branch 'master' into gwenn-stmt-cache

This commit is contained in:
John Gallagher 2016-05-17 08:54:47 -05:00
commit b76196ae1a
20 changed files with 840 additions and 403 deletions

View File

@ -10,4 +10,6 @@ script:
- cargo test --features trace - cargo test --features trace
- cargo test --features functions - cargo test --features functions
- cargo test --features cache - cargo test --features cache
- cargo test --features "backup blob cache functions load_extension trace" - cargo test --features chrono
- cargo test --features serde_json
- cargo test --features "backup blob cache chrono functions load_extension serde_json trace"

View File

@ -1,5 +1,5 @@
rusqlite contributors (sorted alphabetically) rusqlite contributors
============================================= =====================
* [John Gallagher](https://github.com/jgallagher) * [John Gallagher](https://github.com/jgallagher)
* [Marcus Klaas de Vries](https://github.com/marcusklaas) * [Marcus Klaas de Vries](https://github.com/marcusklaas)
@ -13,3 +13,4 @@ rusqlite contributors (sorted alphabetically)
* [Andrew Straw](https://github.com/astraw) * [Andrew Straw](https://github.com/astraw)
* [Ronald Kinard](https://github.com/Furyhunter) * [Ronald Kinard](https://github.com/Furyhunter)
* [maciejkula](https://github.com/maciejkula) * [maciejkula](https://github.com/maciejkula)
* [Xidorn Quan](https://github.com/upsuper)

View File

@ -13,7 +13,7 @@ license = "MIT"
name = "rusqlite" name = "rusqlite"
[features] [features]
load_extension = ["libsqlite3-sys/load_extension"] load_extension = []
backup = [] backup = []
blob = [] blob = []
cache = [] cache = []
@ -22,8 +22,11 @@ trace = []
[dependencies] [dependencies]
time = "~0.1.0" time = "~0.1.0"
bitflags = "~0.1" bitflags = "0.7"
libc = "~0.2" libc = "~0.2"
clippy = {version = "~0.0.58", optional = true}
chrono = { version = "~0.2", optional = true }
serde_json = { version = "0.6", optional = true }
[dev-dependencies] [dev-dependencies]
tempdir = "~0.3.4" tempdir = "~0.3.4"

View File

@ -2,6 +2,14 @@
* Adds a `cache` Cargo feature that provides `cache::StatementCache` for caching prepared * Adds a `cache` Cargo feature that provides `cache::StatementCache` for caching prepared
statements. statements.
* Adds `insert` convenience method to `Statement` which returns the row ID of an inserted row.
* Adds `exists` convenience method returning whether a query finds one or more rows.
* Adds support for serializing types from the `serde_json` crate. Requires the `serde_json` feature.
* Adds support for serializing types from the `chrono` crate. Requires the `chrono` feature.
* Removes `load_extension` feature from `libsqlite3-sys`. `load_extension` is still available
on rusqlite itself.
* Fixes crash on nightly Rust when using the `trace` feature.
* Adds optional `clippy` feature and addresses issues it found.
* Adds `column_count()` method to `Statement` and `Row`. * Adds `column_count()` method to `Statement` and `Row`.
* Adds `types::Value` for dynamic column types. * Adds `types::Value` for dynamic column types.
* Adds support for user-defined aggregate functions (behind the existing `functions` Cargo feature). * Adds support for user-defined aggregate functions (behind the existing `functions` Cargo feature).

View File

@ -1,5 +1,5 @@
environment: environment:
TARGET: 1.6.0-x86_64-pc-windows-gnu TARGET: 1.8.0-x86_64-pc-windows-gnu
MSYS2_BITS: 64 MSYS2_BITS: 64
install: install:
- ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-${env:TARGET}.exe" - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-${env:TARGET}.exe"
@ -16,7 +16,7 @@ build: false
test_script: test_script:
- cargo test --lib --verbose - cargo test --lib --verbose
- cargo test --lib --features "backup blob cache functions load_extension trace" - cargo test --lib --features "backup blob cache chrono functions load_extension serde_json trace"
cache: cache:
- C:\Users\appveyor\.cargo - C:\Users\appveyor\.cargo

View File

@ -8,9 +8,6 @@ license = "MIT"
links = "sqlite3" links = "sqlite3"
build = "build.rs" build = "build.rs"
[features]
load_extension = []
[build-dependencies] [build-dependencies]
pkg-config = "~0.3" pkg-config = "~0.3"

View File

@ -171,9 +171,7 @@ impl<'a, 'b> Backup<'a, 'b> {
/// ///
/// Will return `Err` if the underlying `sqlite3_backup_init` call returns /// Will return `Err` if the underlying `sqlite3_backup_init` call returns
/// `NULL`. /// `NULL`.
pub fn new(from: &'a Connection, pub fn new(from: &'a Connection, to: &'b mut Connection) -> Result<Backup<'a, 'b>> {
to: &'b mut Connection)
-> Result<Backup<'a, 'b>> {
Backup::new_with_names(from, DatabaseName::Main, to, DatabaseName::Main) Backup::new_with_names(from, DatabaseName::Main, to, DatabaseName::Main)
} }

View File

@ -159,9 +159,8 @@ impl<'conn> io::Read for Blob<'conn> {
if n <= 0 { if n <= 0 {
return Ok(0); return Ok(0);
} }
let rc = unsafe { let rc =
ffi::sqlite3_blob_read(self.blob, mem::transmute(buf.as_ptr()), n, self.pos) unsafe { ffi::sqlite3_blob_read(self.blob, mem::transmute(buf.as_ptr()), n, self.pos) };
};
self.conn self.conn
.decode_result(rc) .decode_result(rc)
.map(|_| { .map(|_| {
@ -352,7 +351,8 @@ mod test {
{ {
// ... but it should've written the first 10 bytes // ... but it should've written the first 10 bytes
let mut blob = db.blob_open(DatabaseName::Main, "test", "content", rowid, false).unwrap(); let mut blob = db.blob_open(DatabaseName::Main, "test", "content", rowid, false)
.unwrap();
let mut bytes = [0u8; 10]; let mut bytes = [0u8; 10];
assert_eq!(10, blob.read(&mut bytes[..]).unwrap()); assert_eq!(10, blob.read(&mut bytes[..]).unwrap());
assert_eq!(b"0123456701", &bytes); assert_eq!(b"0123456701", &bytes);
@ -369,7 +369,8 @@ mod test {
{ {
// ... but it should've written the first 10 bytes // ... but it should've written the first 10 bytes
let mut blob = db.blob_open(DatabaseName::Main, "test", "content", rowid, false).unwrap(); let mut blob = db.blob_open(DatabaseName::Main, "test", "content", rowid, false)
.unwrap();
let mut bytes = [0u8; 10]; let mut bytes = [0u8; 10];
assert_eq!(10, blob.read(&mut bytes[..]).unwrap()); assert_eq!(10, blob.read(&mut bytes[..]).unwrap());
assert_eq!(b"aaaaaaaaaa", &bytes); assert_eq!(b"aaaaaaaaaa", &bytes);

View File

@ -88,7 +88,6 @@ impl<'conn> StatementCache<'conn> {
// is full // is full
cache.pop_back(); // LRU dropped cache.pop_back(); // LRU dropped
} }
stmt.reset_if_needed();
stmt.clear_bindings(); stmt.clear_bindings();
cache.push_front(stmt) cache.push_front(stmt)
} }

88
src/convenient.rs Normal file
View File

@ -0,0 +1,88 @@
use {Error, Result, Statement};
use types::ToSql;
impl<'conn> Statement<'conn> {
/// Execute an INSERT and return the ROWID.
///
/// # Failure
/// Will return `Err` if no row is inserted or many rows are inserted.
pub fn insert(&mut self, params: &[&ToSql]) -> Result<i64> {
// Some non-insertion queries could still return 1 change (an UPDATE, for example), so
// to guard against that we can check that the connection's last_insert_rowid() changes
// after we execute the statement.
let prev_rowid = self.conn.last_insert_rowid();
let changes = try!(self.execute(params));
let new_rowid = self.conn.last_insert_rowid();
match changes {
1 if prev_rowid != new_rowid => Ok(new_rowid),
1 if prev_rowid == new_rowid => Err(Error::StatementFailedToInsertRow),
_ => Err(Error::StatementChangedRows(changes)),
}
}
/// Return `true` if a query in the SQL statement it executes returns one or more rows
/// and `false` if the SQL returns an empty set.
pub fn exists(&mut self, params: &[&ToSql]) -> Result<bool> {
let mut rows = try!(self.query(params));
let exists = {
match rows.next() {
Some(_) => true,
None => false,
}
};
Ok(exists)
}
}
#[cfg(test)]
mod test {
use {Connection, Error};
#[test]
fn test_insert() {
let db = Connection::open_in_memory().unwrap();
db.execute_batch("CREATE TABLE foo(x INTEGER UNIQUE)").unwrap();
let mut stmt = db.prepare("INSERT OR IGNORE INTO foo (x) VALUES (?)").unwrap();
assert_eq!(stmt.insert(&[&1i32]).unwrap(), 1);
assert_eq!(stmt.insert(&[&2i32]).unwrap(), 2);
match stmt.insert(&[&1i32]).unwrap_err() {
Error::StatementChangedRows(0) => (),
err => panic!("Unexpected error {}", err),
}
let mut multi = db.prepare("INSERT INTO foo (x) SELECT 3 UNION ALL SELECT 4").unwrap();
match multi.insert(&[]).unwrap_err() {
Error::StatementChangedRows(2) => (),
err => panic!("Unexpected error {}", err),
}
}
#[test]
fn test_insert_failures() {
let db = Connection::open_in_memory().unwrap();
db.execute_batch("CREATE TABLE foo(x INTEGER UNIQUE)").unwrap();
let mut insert = db.prepare("INSERT INTO foo (x) VALUES (?)").unwrap();
let mut update = db.prepare("UPDATE foo SET x = ?").unwrap();
assert_eq!(insert.insert(&[&1i32]).unwrap(), 1);
match update.insert(&[&2i32]) {
Err(Error::StatementFailedToInsertRow) => (),
r => panic!("Unexpected result {:?}", r),
}
}
#[test]
fn test_exists() {
let db = Connection::open_in_memory().unwrap();
let sql = "BEGIN;
CREATE TABLE foo(x INTEGER);
INSERT INTO foo VALUES(1);
INSERT INTO foo VALUES(2);
END;";
db.execute_batch(sql).unwrap();
let mut stmt = db.prepare("SELECT 1 FROM foo WHERE x = ?").unwrap();
assert!(stmt.exists(&[&1i32]).unwrap());
assert!(stmt.exists(&[&2i32]).unwrap());
assert!(!stmt.exists(&[&0i32]).unwrap());
}
}

View File

@ -56,6 +56,13 @@ pub enum Error {
/// that column cannot be converted to the requested Rust type. /// that column cannot be converted to the requested Rust type.
InvalidColumnType, InvalidColumnType,
/// Error when a query that was expected to insert one row did not insert any or insert many.
StatementChangedRows(c_int),
/// Error when a query that was expected to insert a row did not change the connection's
/// last_insert_rowid().
StatementFailedToInsertRow,
/// Error returned by `functions::Context::get` when the function argument cannot be converted /// Error returned by `functions::Context::get` when the function argument cannot be converted
/// to the requested type. /// to the requested type.
#[cfg(feature = "functions")] #[cfg(feature = "functions")]
@ -82,75 +89,93 @@ impl From<::std::ffi::NulError> for Error {
impl fmt::Display for Error { impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match *self {
&Error::SqliteFailure(ref err, None) => err.fmt(f), Error::SqliteFailure(ref err, None) => err.fmt(f),
&Error::SqliteFailure(_, Some(ref s)) => write!(f, "{}", s), Error::SqliteFailure(_, Some(ref s)) => write!(f, "{}", s),
&Error::SqliteSingleThreadedMode => write!(f, "SQLite was compiled or configured for single-threaded use only"), Error::SqliteSingleThreadedMode => {
&Error::FromSqlConversionFailure(ref err) => err.fmt(f), write!(f,
&Error::Utf8Error(ref err) => err.fmt(f), "SQLite was compiled or configured for single-threaded use only")
&Error::NulError(ref err) => err.fmt(f), }
&Error::InvalidParameterName(ref name) => write!(f, "Invalid parameter name: {}", name), Error::FromSqlConversionFailure(ref err) => err.fmt(f),
&Error::InvalidPath(ref p) => write!(f, "Invalid path: {}", p.to_string_lossy()), Error::Utf8Error(ref err) => err.fmt(f),
&Error::ExecuteReturnedResults => write!(f, "Execute returned results - did you mean to call query?"), Error::NulError(ref err) => err.fmt(f),
&Error::QueryReturnedNoRows => write!(f, "Query returned no rows"), Error::InvalidParameterName(ref name) => write!(f, "Invalid parameter name: {}", name),
&Error::GetFromStaleRow => write!(f, "Attempted to get a value from a stale row"), Error::InvalidPath(ref p) => write!(f, "Invalid path: {}", p.to_string_lossy()),
&Error::InvalidColumnIndex(i) => write!(f, "Invalid column index: {}", i), Error::ExecuteReturnedResults => {
&Error::InvalidColumnName(ref name) => write!(f, "Invalid column name: {}", name), write!(f, "Execute returned results - did you mean to call query?")
&Error::InvalidColumnType => write!(f, "Invalid column type"), }
Error::QueryReturnedNoRows => write!(f, "Query returned no rows"),
Error::GetFromStaleRow => write!(f, "Attempted to get a value from a stale row"),
Error::InvalidColumnIndex(i) => write!(f, "Invalid column index: {}", i),
Error::InvalidColumnName(ref name) => write!(f, "Invalid column name: {}", name),
Error::InvalidColumnType => write!(f, "Invalid column type"),
Error::StatementChangedRows(i) => write!(f, "Query changed {} rows", i),
Error::StatementFailedToInsertRow => write!(f, "Statement failed to insert new row"),
#[cfg(feature = "functions")] #[cfg(feature = "functions")]
&Error::InvalidFunctionParameterType => write!(f, "Invalid function parameter type"), Error::InvalidFunctionParameterType => write!(f, "Invalid function parameter type"),
#[cfg(feature = "functions")] #[cfg(feature = "functions")]
&Error::UserFunctionError(ref err) => err.fmt(f), Error::UserFunctionError(ref err) => err.fmt(f),
} }
} }
} }
impl error::Error for Error { impl error::Error for Error {
fn description(&self) -> &str { fn description(&self) -> &str {
match self { match *self {
&Error::SqliteFailure(ref err, None) => err.description(), Error::SqliteFailure(ref err, None) => err.description(),
&Error::SqliteFailure(_, Some(ref s)) => s, Error::SqliteFailure(_, Some(ref s)) => s,
&Error::SqliteSingleThreadedMode => "SQLite was compiled or configured for single-threaded use only", Error::SqliteSingleThreadedMode => {
&Error::FromSqlConversionFailure(ref err) => err.description(), "SQLite was compiled or configured for single-threaded use only"
&Error::Utf8Error(ref err) => err.description(), }
&Error::InvalidParameterName(_) => "invalid parameter name", Error::FromSqlConversionFailure(ref err) => err.description(),
&Error::NulError(ref err) => err.description(), Error::Utf8Error(ref err) => err.description(),
&Error::InvalidPath(_) => "invalid path", Error::InvalidParameterName(_) => "invalid parameter name",
&Error::ExecuteReturnedResults => "execute returned results - did you mean to call query?", Error::NulError(ref err) => err.description(),
&Error::QueryReturnedNoRows => "query returned no rows", Error::InvalidPath(_) => "invalid path",
&Error::GetFromStaleRow => "attempted to get a value from a stale row", Error::ExecuteReturnedResults => {
&Error::InvalidColumnIndex(_) => "invalid column index", "execute returned results - did you mean to call query?"
&Error::InvalidColumnName(_) => "invalid column name", }
&Error::InvalidColumnType => "invalid column type", Error::QueryReturnedNoRows => "query returned no rows",
Error::GetFromStaleRow => "attempted to get a value from a stale row",
Error::InvalidColumnIndex(_) => "invalid column index",
Error::InvalidColumnName(_) => "invalid column name",
Error::InvalidColumnType => "invalid column type",
Error::StatementChangedRows(_) => "query inserted zero or more than one row",
Error::StatementFailedToInsertRow => "statement failed to insert new row",
#[cfg(feature = "functions")] #[cfg(feature = "functions")]
&Error::InvalidFunctionParameterType => "invalid function parameter type", Error::InvalidFunctionParameterType => "invalid function parameter type",
#[cfg(feature = "functions")] #[cfg(feature = "functions")]
&Error::UserFunctionError(ref err) => err.description(), Error::UserFunctionError(ref err) => err.description(),
} }
} }
#[cfg_attr(feature="clippy", allow(match_same_arms))]
fn cause(&self) -> Option<&error::Error> { fn cause(&self) -> Option<&error::Error> {
match self { match *self {
&Error::SqliteFailure(ref err, _) => Some(err), Error::SqliteFailure(ref err, _) => Some(err),
&Error::SqliteSingleThreadedMode => None, Error::FromSqlConversionFailure(ref err) => Some(&**err),
&Error::FromSqlConversionFailure(ref err) => Some(&**err), Error::Utf8Error(ref err) => Some(err),
&Error::Utf8Error(ref err) => Some(err), Error::NulError(ref err) => Some(err),
&Error::NulError(ref err) => Some(err),
&Error::InvalidParameterName(_) => None, Error::SqliteSingleThreadedMode |
&Error::InvalidPath(_) => None, Error::InvalidParameterName(_) |
&Error::ExecuteReturnedResults => None, Error::ExecuteReturnedResults |
&Error::QueryReturnedNoRows => None, Error::QueryReturnedNoRows |
&Error::GetFromStaleRow => None, Error::GetFromStaleRow |
&Error::InvalidColumnIndex(_) => None, Error::InvalidColumnIndex(_) |
&Error::InvalidColumnName(_) => None, Error::InvalidColumnName(_) |
&Error::InvalidColumnType => None, Error::InvalidColumnType |
Error::InvalidPath(_) => None,
Error::StatementChangedRows(_) => None,
Error::StatementFailedToInsertRow => None,
#[cfg(feature = "functions")] #[cfg(feature = "functions")]
&Error::InvalidFunctionParameterType => None, Error::InvalidFunctionParameterType => None,
#[cfg(feature = "functions")] #[cfg(feature = "functions")]
&Error::UserFunctionError(ref err) => Some(&**err), Error::UserFunctionError(ref err) => Some(&**err),
} }
} }
} }

View File

@ -88,9 +88,10 @@ raw_to_impl!(c_double, sqlite3_result_double);
impl<'a> ToResult for bool { impl<'a> ToResult for bool {
unsafe fn set_result(&self, ctx: *mut sqlite3_context) { unsafe fn set_result(&self, ctx: *mut sqlite3_context) {
match *self { if *self {
true => ffi::sqlite3_result_int(ctx, 1), ffi::sqlite3_result_int(ctx, 1)
_ => ffi::sqlite3_result_int(ctx, 0), } else {
ffi::sqlite3_result_int(ctx, 0)
} }
} }
} }
@ -214,7 +215,7 @@ impl FromValue for String {
unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<String> { unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<String> {
let c_text = ffi::sqlite3_value_text(v); let c_text = ffi::sqlite3_value_text(v);
if c_text.is_null() { if c_text.is_null() {
Ok("".to_string()) Ok("".to_owned())
} else { } else {
let c_slice = CStr::from_ptr(c_text as *const c_char).to_bytes(); let c_slice = CStr::from_ptr(c_text as *const c_char).to_bytes();
let utf8_str = try!(str::from_utf8(c_slice)); let utf8_str = try!(str::from_utf8(c_slice));
@ -250,7 +251,7 @@ impl<T: FromValue> FromValue for Option<T> {
if sqlite3_value_type(v) == ffi::SQLITE_NULL { if sqlite3_value_type(v) == ffi::SQLITE_NULL {
Ok(None) Ok(None)
} else { } else {
FromValue::parameter_value(v).map(|t| Some(t)) FromValue::parameter_value(v).map(Some)
} }
} }
@ -274,6 +275,10 @@ impl<'a> Context<'a> {
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
self.args.len() self.args.len()
} }
/// Returns `true` when there is no argument.
pub fn is_empty(&self) -> bool {
self.args.is_empty()
}
/// Returns the `idx`th argument as a `T`. /// Returns the `idx`th argument as a `T`.
/// ///
@ -302,7 +307,7 @@ impl<'a> Context<'a> {
ffi::sqlite3_set_auxdata(self.ctx, ffi::sqlite3_set_auxdata(self.ctx,
arg, arg,
mem::transmute(boxed), mem::transmute(boxed),
Some(mem::transmute(free_boxed_value::<T>))) Some(free_boxed_value::<T>))
}; };
} }
@ -328,7 +333,9 @@ impl<'a> Context<'a> {
/// ///
/// `A` is the type of the aggregation context and `T` is the type of the final result. /// `A` is the type of the aggregation context and `T` is the type of the final result.
/// Implementations should be stateless. /// Implementations should be stateless.
pub trait Aggregate<A, T> where T: ToResult { pub trait Aggregate<A, T>
where T: ToResult
{
/// Initializes the aggregation context. Will be called prior to the first call /// Initializes the aggregation context. Will be called prior to the first call
/// to `step()` to set up the context for an invocation of the function. (Note: /// to `step()` to set up the context for an invocation of the function. (Note:
/// `init()` will not be called if the there are no rows.) /// `init()` will not be called if the there are no rows.)
@ -475,7 +482,7 @@ impl InnerConnection {
Some(call_boxed_closure::<F, T>), Some(call_boxed_closure::<F, T>),
None, None,
None, None,
Some(mem::transmute(free_boxed_value::<F>))) Some(free_boxed_value::<F>))
}; };
self.decode_result(r) self.decode_result(r)
} }
@ -592,7 +599,7 @@ impl InnerConnection {
None, None,
Some(call_boxed_step::<A, D, T>), Some(call_boxed_step::<A, D, T>),
Some(call_boxed_final::<A, D, T>), Some(call_boxed_final::<A, D, T>),
Some(mem::transmute(free_boxed_value::<D>))) Some(free_boxed_value::<D>))
}; };
self.decode_result(r) self.decode_result(r)
} }
@ -621,6 +628,7 @@ mod test {
use std::collections::HashMap; use std::collections::HashMap;
use libc::c_double; use libc::c_double;
use self::regex::Regex; use self::regex::Regex;
use std::f64::EPSILON;
use {Connection, Error, Result}; use {Connection, Error, Result};
use functions::{Aggregate, Context}; use functions::{Aggregate, Context};
@ -637,7 +645,7 @@ mod test {
db.create_scalar_function("half", 1, true, half).unwrap(); db.create_scalar_function("half", 1, true, half).unwrap();
let result: Result<f64> = db.query_row("SELECT half(6)", &[], |r| r.get(0)); let result: Result<f64> = db.query_row("SELECT half(6)", &[], |r| r.get(0));
assert_eq!(3f64, result.unwrap()); assert!((3f64 - result.unwrap()).abs() < EPSILON);
} }
#[test] #[test]
@ -645,7 +653,7 @@ mod test {
let db = Connection::open_in_memory().unwrap(); let db = Connection::open_in_memory().unwrap();
db.create_scalar_function("half", 1, true, half).unwrap(); db.create_scalar_function("half", 1, true, half).unwrap();
let result: Result<f64> = db.query_row("SELECT half(6)", &[], |r| r.get(0)); let result: Result<f64> = db.query_row("SELECT half(6)", &[], |r| r.get(0));
assert_eq!(3f64, result.unwrap()); assert!((3f64 - result.unwrap()).abs() < EPSILON);
db.remove_function("half", 1).unwrap(); db.remove_function("half", 1).unwrap();
let result: Result<f64> = db.query_row("SELECT half(6)", &[], |r| r.get(0)); let result: Result<f64> = db.query_row("SELECT half(6)", &[], |r| r.get(0));

View File

@ -50,6 +50,9 @@
//! } //! }
//! } //! }
//! ``` //! ```
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
extern crate libc; extern crate libc;
extern crate libsqlite3_sys as ffi; extern crate libsqlite3_sys as ffi;
#[macro_use] #[macro_use]
@ -84,12 +87,13 @@ pub mod types;
mod transaction; mod transaction;
mod named_params; mod named_params;
mod error; mod error;
mod convenient;
#[cfg(feature = "load_extension")]mod load_extension_guard; #[cfg(feature = "load_extension")]mod load_extension_guard;
#[cfg(feature = "trace")]pub mod trace; #[cfg(feature = "trace")]pub mod trace;
#[cfg(feature = "backup")]pub mod backup; #[cfg(feature = "backup")]pub mod backup;
#[cfg(feature = "cache")] pub mod cache; #[cfg(feature = "cache")]pub mod cache;
#[cfg(feature = "functions")] pub mod functions; #[cfg(feature = "functions")]pub mod functions;
#[cfg(feature = "blob")] pub mod blob; #[cfg(feature = "blob")]pub mod blob;
/// Old name for `Result`. `SqliteResult` is deprecated. /// Old name for `Result`. `SqliteResult` is deprecated.
pub type SqliteResult<T> = Result<T>; pub type SqliteResult<T> = Result<T>;
@ -99,8 +103,7 @@ pub type Result<T> = result::Result<T, Error>;
unsafe fn errmsg_to_string(errmsg: *const c_char) -> String { unsafe fn errmsg_to_string(errmsg: *const c_char) -> String {
let c_slice = CStr::from_ptr(errmsg).to_bytes(); let c_slice = CStr::from_ptr(errmsg).to_bytes();
let utf8_str = str::from_utf8(c_slice); String::from_utf8_lossy(c_slice).into_owned()
utf8_str.unwrap_or("Invalid string encoding").to_string()
} }
fn str_to_cstring(s: &str) -> Result<CString> { fn str_to_cstring(s: &str) -> Result<CString> {
@ -128,9 +131,9 @@ pub enum DatabaseName<'a> {
// impl to avoid dead code warnings. // impl to avoid dead code warnings.
#[cfg(any(feature = "backup", feature = "blob"))] #[cfg(any(feature = "backup", feature = "blob"))]
impl<'a> DatabaseName<'a> { impl<'a> DatabaseName<'a> {
fn to_cstring(self) -> Result<CString> { fn to_cstring(&self) -> Result<CString> {
use self::DatabaseName::{Main, Temp, Attached}; use self::DatabaseName::{Main, Temp, Attached};
match self { match *self {
Main => str_to_cstring("main"), Main => str_to_cstring("main"),
Temp => str_to_cstring("temp"), Temp => str_to_cstring("temp"),
Attached(s) => str_to_cstring(s), Attached(s) => str_to_cstring(s),
@ -183,9 +186,7 @@ impl Connection {
/// ///
/// Will return `Err` if `path` cannot be converted to a C-compatible string or if the /// Will return `Err` if `path` cannot be converted to a C-compatible string or if the
/// underlying SQLite open call fails. /// underlying SQLite open call fails.
pub fn open_with_flags<P: AsRef<Path>>(path: P, pub fn open_with_flags<P: AsRef<Path>>(path: P, flags: OpenFlags) -> Result<Connection> {
flags: OpenFlags)
-> Result<Connection> {
let c_path = try!(path_to_cstring(path.as_ref())); let c_path = try!(path_to_cstring(path.as_ref()));
InnerConnection::open_with_flags(&c_path, flags).map(|db| { InnerConnection::open_with_flags(&c_path, flags).map(|db| {
Connection { Connection {
@ -237,7 +238,7 @@ impl Connection {
/// # Failure /// # Failure
/// ///
/// Will return `Err` if the underlying SQLite call fails. /// Will return `Err` if the underlying SQLite call fails.
pub fn transaction<'a>(&'a self) -> Result<Transaction<'a>> { pub fn transaction(&self) -> Result<Transaction> {
Transaction::new(self, TransactionBehavior::Deferred) Transaction::new(self, TransactionBehavior::Deferred)
} }
@ -248,9 +249,7 @@ impl Connection {
/// # Failure /// # Failure
/// ///
/// Will return `Err` if the underlying SQLite call fails. /// Will return `Err` if the underlying SQLite call fails.
pub fn transaction_with_behavior<'a>(&'a self, pub fn transaction_with_behavior(&self, behavior: TransactionBehavior) -> Result<Transaction> {
behavior: TransactionBehavior)
-> Result<Transaction<'a>> {
Transaction::new(self, behavior) Transaction::new(self, behavior)
} }
@ -360,7 +359,11 @@ impl Connection {
/// ///
/// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the /// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
/// underlying SQLite call fails. /// underlying SQLite call fails.
pub fn query_row_and_then<T, E, F>(&self, sql: &str, params: &[&ToSql], f: F) -> result::Result<T, E> pub fn query_row_and_then<T, E, F>(&self,
sql: &str,
params: &[&ToSql],
f: F)
-> result::Result<T, E>
where F: FnOnce(Row) -> result::Result<T, E>, where F: FnOnce(Row) -> result::Result<T, E>,
E: convert::From<Error> E: convert::From<Error>
{ {
@ -535,7 +538,7 @@ bitflags! {
#[doc = "Flags for opening SQLite database connections."] #[doc = "Flags for opening SQLite database connections."]
#[doc = "See [sqlite3_open_v2](http://www.sqlite.org/c3ref/open.html) for details."] #[doc = "See [sqlite3_open_v2](http://www.sqlite.org/c3ref/open.html) for details."]
#[repr(C)] #[repr(C)]
flags OpenFlags: c_int { pub flags OpenFlags: ::libc::c_int {
const SQLITE_OPEN_READ_ONLY = 0x00000001, const SQLITE_OPEN_READ_ONLY = 0x00000001,
const SQLITE_OPEN_READ_WRITE = 0x00000002, const SQLITE_OPEN_READ_WRITE = 0x00000002,
const SQLITE_OPEN_CREATE = 0x00000004, const SQLITE_OPEN_CREATE = 0x00000004,
@ -555,9 +558,7 @@ impl Default for OpenFlags {
} }
impl InnerConnection { impl InnerConnection {
fn open_with_flags(c_path: &CString, fn open_with_flags(c_path: &CString, flags: OpenFlags) -> Result<InnerConnection> {
flags: OpenFlags)
-> Result<InnerConnection> {
unsafe { unsafe {
// Before opening the database, we need to check that SQLite hasn't been // Before opening the database, we need to check that SQLite hasn't been
// compiled or configured to be in single-threaded mode. If it has, we're // compiled or configured to be in single-threaded mode. If it has, we're
@ -573,11 +574,7 @@ impl InnerConnection {
// https://github.com/mackyle/sqlite/blob/master/src/mutex_noop.c). // https://github.com/mackyle/sqlite/blob/master/src/mutex_noop.c).
const SQLITE_SINGLETHREADED_MUTEX_MAGIC: usize = 8; const SQLITE_SINGLETHREADED_MUTEX_MAGIC: usize = 8;
let mutex_ptr = ffi::sqlite3_mutex_alloc(0); let mutex_ptr = ffi::sqlite3_mutex_alloc(0);
let is_singlethreaded = if mutex_ptr as usize == SQLITE_SINGLETHREADED_MUTEX_MAGIC { let is_singlethreaded = mutex_ptr as usize == SQLITE_SINGLETHREADED_MUTEX_MAGIC;
true
} else {
false
};
ffi::sqlite3_mutex_free(mutex_ptr); ffi::sqlite3_mutex_free(mutex_ptr);
if is_singlethreaded { if is_singlethreaded {
return Err(Error::SqliteSingleThreadedMode); return Err(Error::SqliteSingleThreadedMode);
@ -676,10 +673,7 @@ impl InnerConnection {
unsafe { ffi::sqlite3_last_insert_rowid(self.db()) } unsafe { ffi::sqlite3_last_insert_rowid(self.db()) }
} }
fn prepare<'a>(&mut self, fn prepare<'a>(&mut self, conn: &'a Connection, sql: &str) -> Result<Statement<'a>> {
conn: &'a Connection,
sql: &str)
-> Result<Statement<'a>> {
if sql.len() >= ::std::i32::MAX as usize { if sql.len() >= ::std::i32::MAX as usize {
return Err(error_from_sqlite_code(ffi::SQLITE_TOOBIG, None)); return Err(error_from_sqlite_code(ffi::SQLITE_TOOBIG, None));
} }
@ -715,7 +709,6 @@ pub type SqliteStatement<'conn> = Statement<'conn>;
pub struct Statement<'conn> { pub struct Statement<'conn> {
conn: &'conn Connection, conn: &'conn Connection,
stmt: *mut ffi::sqlite3_stmt, stmt: *mut ffi::sqlite3_stmt,
needs_reset: bool,
column_count: c_int, column_count: c_int,
} }
@ -724,7 +717,6 @@ impl<'conn> Statement<'conn> {
Statement { Statement {
conn: conn, conn: conn,
stmt: stmt, stmt: stmt,
needs_reset: false,
column_count: unsafe { ffi::sqlite3_column_count(stmt) }, column_count: unsafe { ffi::sqlite3_column_count(stmt) },
} }
} }
@ -798,12 +790,12 @@ impl<'conn> Statement<'conn> {
ffi::sqlite3_reset(self.stmt); ffi::sqlite3_reset(self.stmt);
match r { match r {
ffi::SQLITE_DONE => { ffi::SQLITE_DONE => {
if self.column_count != 0 { if self.column_count == 0 {
Err(Error::ExecuteReturnedResults)
} else {
Ok(self.conn.changes()) Ok(self.conn.changes())
} else {
Err(Error::ExecuteReturnedResults)
}
} }
},
ffi::SQLITE_ROW => Err(Error::ExecuteReturnedResults), ffi::SQLITE_ROW => Err(Error::ExecuteReturnedResults),
_ => Err(self.conn.decode_result(r).unwrap_err()), _ => Err(self.conn.decode_result(r).unwrap_err()),
} }
@ -833,13 +825,10 @@ impl<'conn> Statement<'conn> {
/// ///
/// Will return `Err` if binding parameters fails. /// Will return `Err` if binding parameters fails.
pub fn query<'a>(&'a mut self, params: &[&ToSql]) -> Result<Rows<'a>> { pub fn query<'a>(&'a mut self, params: &[&ToSql]) -> Result<Rows<'a>> {
self.reset_if_needed();
unsafe { unsafe {
try!(self.bind_parameters(params)); try!(self.bind_parameters(params));
} }
self.needs_reset = true;
Ok(Rows::new(self)) Ok(Rows::new(self))
} }
@ -852,10 +841,7 @@ impl<'conn> Statement<'conn> {
/// # Failure /// # Failure
/// ///
/// Will return `Err` if binding parameters fails. /// Will return `Err` if binding parameters fails.
pub fn query_map<'a, T, F>(&'a mut self, pub fn query_map<'a, T, F>(&'a mut self, params: &[&ToSql], f: F) -> Result<MappedRows<'a, F>>
params: &[&ToSql],
f: F)
-> Result<MappedRows<'a, F>>
where F: FnMut(&Row) -> T where F: FnMut(&Row) -> T
{ {
let row_iter = try!(self.query(params)); let row_iter = try!(self.query(params));
@ -916,15 +902,6 @@ impl<'conn> Statement<'conn> {
Ok(()) Ok(())
} }
fn reset_if_needed(&mut self) {
if self.needs_reset {
unsafe {
ffi::sqlite3_reset(self.stmt);
};
self.needs_reset = false;
}
}
#[cfg(feature = "cache")] #[cfg(feature = "cache")]
fn clear_bindings(&mut self) { fn clear_bindings(&mut self) {
unsafe { unsafe {
@ -974,7 +951,8 @@ pub struct MappedRows<'stmt, F> {
map: F, map: F,
} }
impl<'stmt, T, F> Iterator for MappedRows<'stmt, F> where F: FnMut(&Row) -> T impl<'stmt, T, F> Iterator for MappedRows<'stmt, F>
where F: FnMut(&Row) -> T
{ {
type Item = Result<T>; type Item = Result<T>;
@ -991,7 +969,7 @@ pub struct AndThenRows<'stmt, F> {
} }
impl<'stmt, T, E, F> Iterator for AndThenRows<'stmt, F> impl<'stmt, T, E, F> Iterator for AndThenRows<'stmt, F>
where E: convert::From<Error>, where E: convert::From<Error>,
F: FnMut(&Row) -> result::Result<T, E> F: FnMut(&Row) -> result::Result<T, E>
{ {
type Item = result::Result<T, E>; type Item = result::Result<T, E>;
@ -1040,17 +1018,15 @@ pub type SqliteRows<'stmt> = Rows<'stmt>;
/// `min`/`max` (which could return a stale row unless the last row happened to be the min or max, /// `min`/`max` (which could return a stale row unless the last row happened to be the min or max,
/// respectively). /// respectively).
pub struct Rows<'stmt> { pub struct Rows<'stmt> {
stmt: &'stmt Statement<'stmt>, stmt: Option<&'stmt Statement<'stmt>>,
current_row: Rc<Cell<c_int>>, current_row: Rc<Cell<c_int>>,
failed: bool,
} }
impl<'stmt> Rows<'stmt> { impl<'stmt> Rows<'stmt> {
fn new(stmt: &'stmt Statement<'stmt>) -> Rows<'stmt> { fn new(stmt: &'stmt Statement<'stmt>) -> Rows<'stmt> {
Rows { Rows {
stmt: stmt, stmt: Some(stmt),
current_row: Rc::new(Cell::new(0)), current_row: Rc::new(Cell::new(0)),
failed: false,
} }
} }
@ -1060,31 +1036,47 @@ impl<'stmt> Rows<'stmt> {
None => Err(Error::QueryReturnedNoRows), None => Err(Error::QueryReturnedNoRows),
} }
} }
fn reset(&mut self) {
if let Some(stmt) = self.stmt.take() {
unsafe {
ffi::sqlite3_reset(stmt.stmt);
}
}
}
} }
impl<'stmt> Iterator for Rows<'stmt> { impl<'stmt> Iterator for Rows<'stmt> {
type Item = Result<Row<'stmt>>; type Item = Result<Row<'stmt>>;
fn next(&mut self) -> Option<Result<Row<'stmt>>> { fn next(&mut self) -> Option<Result<Row<'stmt>>> {
if self.failed { self.stmt.and_then(|stmt| {
return None; match unsafe { ffi::sqlite3_step(stmt.stmt) } {
}
match unsafe { ffi::sqlite3_step(self.stmt.stmt) } {
ffi::SQLITE_ROW => { ffi::SQLITE_ROW => {
let current_row = self.current_row.get() + 1; let current_row = self.current_row.get() + 1;
self.current_row.set(current_row); self.current_row.set(current_row);
Some(Ok(Row { Some(Ok(Row {
stmt: self.stmt, stmt: stmt,
current_row: self.current_row.clone(), current_row: self.current_row.clone(),
row_idx: current_row, row_idx: current_row,
})) }))
} }
ffi::SQLITE_DONE => None, ffi::SQLITE_DONE => {
self.reset();
None
}
code => { code => {
self.failed = true; self.reset();
Some(Err(self.stmt.conn.decode_result(code).unwrap_err())) Some(Err(stmt.conn.decode_result(code).unwrap_err()))
} }
} }
})
}
}
impl<'stmt> Drop for Rows<'stmt> {
fn drop(&mut self) {
self.reset();
} }
} }
@ -1195,9 +1187,9 @@ impl<'a> RowIndex for &'a str {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
extern crate libsqlite3_sys as ffi;
extern crate tempdir; extern crate tempdir;
pub use super::*; pub use super::*;
use ffi;
use self::tempdir::TempDir; use self::tempdir::TempDir;
pub use std::error::Error as StdError; pub use std::error::Error as StdError;
pub use std::fmt; pub use std::fmt;
@ -1246,10 +1238,9 @@ mod test {
#[test] #[test]
fn test_open_with_flags() { fn test_open_with_flags() {
for bad_flags in [OpenFlags::empty(), for bad_flags in &[OpenFlags::empty(),
SQLITE_OPEN_READ_ONLY | SQLITE_OPEN_READ_WRITE, SQLITE_OPEN_READ_ONLY | SQLITE_OPEN_READ_WRITE,
SQLITE_OPEN_READ_ONLY | SQLITE_OPEN_CREATE] SQLITE_OPEN_READ_ONLY | SQLITE_OPEN_CREATE] {
.iter() {
assert!(Connection::open_in_memory_with_flags(*bad_flags).is_err()); assert!(Connection::open_in_memory_with_flags(*bad_flags).is_err());
} }
} }
@ -1427,7 +1418,7 @@ mod test {
assert_eq!(2i32, second.get(0)); assert_eq!(2i32, second.get(0));
match first.get_checked::<i32,i32>(0).unwrap_err() { match first.get_checked::<i32, i32>(0).unwrap_err() {
Error::GetFromStaleRow => (), Error::GetFromStaleRow => (),
err => panic!("Unexpected error {}", err), err => panic!("Unexpected error {}", err),
} }
@ -1475,7 +1466,7 @@ mod test {
if version >= 3007016 { if version >= 3007016 {
assert_eq!(err.extended_code, ffi::SQLITE_CONSTRAINT_NOTNULL) assert_eq!(err.extended_code, ffi::SQLITE_CONSTRAINT_NOTNULL)
} }
}, }
err => panic!("Unexpected error {}", err), err => panic!("Unexpected error {}", err),
} }
} }

View File

@ -37,11 +37,7 @@ impl Connection {
/// ///
/// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the /// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
/// underlying SQLite call fails. /// underlying SQLite call fails.
pub fn query_row_named<T, F>(&self, pub fn query_row_named<T, F>(&self, sql: &str, params: &[(&str, &ToSql)], f: F) -> Result<T>
sql: &str,
params: &[(&str, &ToSql)],
f: F)
-> Result<T>
where F: FnOnce(Row) -> T where F: FnOnce(Row) -> T
{ {
let mut stmt = try!(self.prepare(sql)); let mut stmt = try!(self.prepare(sql));
@ -91,9 +87,7 @@ impl<'conn> Statement<'conn> {
/// which case `query` should be used instead), or the underling SQLite call fails. /// which case `query` should be used instead), or the underling SQLite call fails.
pub fn execute_named(&mut self, params: &[(&str, &ToSql)]) -> Result<c_int> { pub fn execute_named(&mut self, params: &[(&str, &ToSql)]) -> Result<c_int> {
try!(self.bind_parameters_named(params)); try!(self.bind_parameters_named(params));
unsafe { unsafe { self.execute_() }
self.execute_()
}
} }
/// Execute the prepared statement with named parameter(s), returning an iterator over the /// Execute the prepared statement with named parameter(s), returning an iterator over the
@ -118,13 +112,8 @@ impl<'conn> Statement<'conn> {
/// # Failure /// # Failure
/// ///
/// Will return `Err` if binding parameters fails. /// Will return `Err` if binding parameters fails.
pub fn query_named<'a>(&'a mut self, pub fn query_named<'a>(&'a mut self, params: &[(&str, &ToSql)]) -> Result<Rows<'a>> {
params: &[(&str, &ToSql)])
-> Result<Rows<'a>> {
self.reset_if_needed();
try!(self.bind_parameters_named(params)); try!(self.bind_parameters_named(params));
self.needs_reset = true;
Ok(Rows::new(self)) Ok(Rows::new(self))
} }
@ -198,8 +187,9 @@ mod test {
let mut stmt = db.prepare("INSERT INTO test (x, y) VALUES (:x, :y)").unwrap(); let mut stmt = db.prepare("INSERT INTO test (x, y) VALUES (:x, :y)").unwrap();
stmt.execute_named(&[(":x", &"one")]).unwrap(); stmt.execute_named(&[(":x", &"one")]).unwrap();
let result: Option<String> = db.query_row("SELECT y FROM test WHERE x = 'one'", &[], let result: Option<String> =
|row| row.get(0)).unwrap(); db.query_row("SELECT y FROM test WHERE x = 'one'", &[], |row| row.get(0))
.unwrap();
assert!(result.is_none()); assert!(result.is_none());
} }
@ -213,8 +203,9 @@ mod test {
stmt.execute_named(&[(":x", &"one")]).unwrap(); stmt.execute_named(&[(":x", &"one")]).unwrap();
stmt.execute_named(&[(":y", &"two")]).unwrap(); stmt.execute_named(&[(":y", &"two")]).unwrap();
let result: String = db.query_row("SELECT x FROM test WHERE y = 'two'", &[], let result: String =
|row| row.get(0)).unwrap(); db.query_row("SELECT x FROM test WHERE y = 'two'", &[], |row| row.get(0))
.unwrap();
assert_eq!(result, "one"); assert_eq!(result, "one");
} }
} }

View File

@ -4,7 +4,6 @@ use libc::{c_char, c_int, c_void};
use std::ffi::{CStr, CString}; use std::ffi::{CStr, CString};
use std::mem; use std::mem;
use std::ptr; use std::ptr;
use std::str;
use std::time::Duration; use std::time::Duration;
use super::ffi; use super::ffi;
@ -27,15 +26,16 @@ pub unsafe fn config_log(callback: Option<fn(c_int, &str)>) -> Result<()> {
let c_slice = unsafe { CStr::from_ptr(msg).to_bytes() }; let c_slice = unsafe { CStr::from_ptr(msg).to_bytes() };
let callback: fn(c_int, &str) = unsafe { mem::transmute(p_arg) }; let callback: fn(c_int, &str) = unsafe { mem::transmute(p_arg) };
if let Ok(s) = str::from_utf8(c_slice) { let s = String::from_utf8_lossy(c_slice);
callback(err, s); callback(err, &s);
}
} }
let rc = match callback { let rc = match callback {
Some(f) => { Some(f) => {
let p_arg: *mut c_void = mem::transmute(f); let p_arg: *mut c_void = mem::transmute(f);
ffi::sqlite3_config(ffi::SQLITE_CONFIG_LOG, Some(log_callback), p_arg) ffi::sqlite3_config(ffi::SQLITE_CONFIG_LOG,
log_callback as extern "C" fn(_, _, _),
p_arg)
} }
None => { None => {
let nullptr: *mut c_void = ptr::null_mut(); let nullptr: *mut c_void = ptr::null_mut();
@ -68,9 +68,8 @@ impl Connection {
unsafe extern "C" fn trace_callback(p_arg: *mut c_void, z_sql: *const c_char) { unsafe extern "C" fn trace_callback(p_arg: *mut c_void, z_sql: *const c_char) {
let trace_fn: fn(&str) = mem::transmute(p_arg); let trace_fn: fn(&str) = mem::transmute(p_arg);
let c_slice = CStr::from_ptr(z_sql).to_bytes(); let c_slice = CStr::from_ptr(z_sql).to_bytes();
if let Ok(s) = str::from_utf8(c_slice) { let s = String::from_utf8_lossy(c_slice);
trace_fn(s); trace_fn(&s);
}
} }
let c = self.db.borrow_mut(); let c = self.db.borrow_mut();
@ -94,13 +93,12 @@ impl Connection {
nanoseconds: u64) { nanoseconds: u64) {
let profile_fn: fn(&str, Duration) = mem::transmute(p_arg); let profile_fn: fn(&str, Duration) = mem::transmute(p_arg);
let c_slice = CStr::from_ptr(z_sql).to_bytes(); let c_slice = CStr::from_ptr(z_sql).to_bytes();
if let Ok(s) = str::from_utf8(c_slice) { let s = String::from_utf8_lossy(c_slice);
const NANOS_PER_SEC: u64 = 1_000_000_000; const NANOS_PER_SEC: u64 = 1_000_000_000;
let duration = Duration::new(nanoseconds / NANOS_PER_SEC, let duration = Duration::new(nanoseconds / NANOS_PER_SEC,
(nanoseconds % NANOS_PER_SEC) as u32); (nanoseconds % NANOS_PER_SEC) as u32);
profile_fn(s, duration); profile_fn(&s, duration);
}
} }
let c = self.db.borrow_mut(); let c = self.db.borrow_mut();

View File

@ -47,9 +47,7 @@ pub struct Transaction<'conn> {
impl<'conn> Transaction<'conn> { impl<'conn> Transaction<'conn> {
/// Begin a new transaction. Cannot be nested; see `savepoint` for nested transactions. /// Begin a new transaction. Cannot be nested; see `savepoint` for nested transactions.
pub fn new(conn: &Connection, pub fn new(conn: &Connection, behavior: TransactionBehavior) -> Result<Transaction> {
behavior: TransactionBehavior)
-> Result<Transaction> {
let query = match behavior { let query = match behavior {
TransactionBehavior::Deferred => "BEGIN DEFERRED", TransactionBehavior::Deferred => "BEGIN DEFERRED",
TransactionBehavior::Immediate => "BEGIN IMMEDIATE", TransactionBehavior::Immediate => "BEGIN IMMEDIATE",
@ -91,7 +89,7 @@ impl<'conn> Transaction<'conn> {
/// tx.commit() /// tx.commit()
/// } /// }
/// ``` /// ```
pub fn savepoint<'a>(&'a self) -> Result<Transaction<'a>> { pub fn savepoint(&self) -> Result<Transaction> {
self.conn.execute_batch("SAVEPOINT sp").map(|_| { self.conn.execute_batch("SAVEPOINT sp").map(|_| {
Transaction { Transaction {
conn: self.conn, conn: self.conn,
@ -176,6 +174,7 @@ impl<'conn> Drop for Transaction<'conn> {
} }
#[cfg(test)] #[cfg(test)]
#[cfg_attr(feature="clippy", allow(similar_names))]
mod test { mod test {
use Connection; use Connection;

239
src/types/chrono.rs Normal file
View File

@ -0,0 +1,239 @@
//! Convert most of the [Time Strings](http://sqlite.org/lang_datefunc.html) to chrono types.
extern crate chrono;
use self::chrono::{NaiveDate, NaiveTime, NaiveDateTime, DateTime, TimeZone, UTC, Local};
use libc::c_int;
use {Error, Result};
use types::{FromSql, ToSql};
use ffi::sqlite3_stmt;
/// ISO 8601 calendar date without timezone => "YYYY-MM-DD"
impl ToSql for NaiveDate {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
let date_str = self.format("%Y-%m-%d").to_string();
date_str.bind_parameter(stmt, col)
}
}
/// "YYYY-MM-DD" => ISO 8601 calendar date without timezone.
impl FromSql for NaiveDate {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<NaiveDate> {
let s = try!(String::column_result(stmt, col));
match NaiveDate::parse_from_str(&s, "%Y-%m-%d") {
Ok(dt) => Ok(dt),
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)
}
}
/// ISO 8601 time without timezone => "HH:MM:SS.SSS"
impl ToSql for NaiveTime {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
let date_str = self.format("%H:%M:%S%.f").to_string();
date_str.bind_parameter(stmt, col)
}
}
/// "HH:MM"/"HH:MM:SS"/"HH:MM:SS.SSS" => ISO 8601 time without timezone.
impl FromSql for NaiveTime {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<NaiveTime> {
let s = try!(String::column_result(stmt, col));
let fmt = match s.len() {
5 => "%H:%M",
8 => "%H:%M:%S",
_ => "%H:%M:%S%.f",
};
match NaiveTime::parse_from_str(&s, fmt) {
Ok(dt) => Ok(dt),
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)
}
}
/// ISO 8601 combined date and time without timezone => "YYYY-MM-DD HH:MM:SS.SSS"
impl ToSql for NaiveDateTime {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
let date_str = self.format("%Y-%m-%dT%H:%M:%S%.f").to_string();
date_str.bind_parameter(stmt, col)
}
}
/// "YYYY-MM-DD HH:MM:SS"/"YYYY-MM-DD HH:MM:SS.SSS" => ISO 8601 combined date and time
/// without timezone. ("YYYY-MM-DDTHH:MM:SS"/"YYYY-MM-DDTHH:MM:SS.SSS" also supported)
impl FromSql for NaiveDateTime {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<NaiveDateTime> {
let s = try!(String::column_result(stmt, col));
let fmt = if s.len() >= 11 && s.as_bytes()[10] == b'T' {
"%Y-%m-%dT%H:%M:%S%.f"
} else {
"%Y-%m-%d %H:%M:%S%.f"
};
match NaiveDateTime::parse_from_str(&s, fmt) {
Ok(dt) => Ok(dt),
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)
}
}
/// Date and time with time zone => UTC RFC3339 timestamp ("YYYY-MM-DDTHH:MM:SS.SSS+00:00").
impl<Tz: TimeZone> ToSql for DateTime<Tz> {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
let utc_dt = self.with_timezone(&UTC);
utc_dt.to_rfc3339().bind_parameter(stmt, col)
}
}
/// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime<UTC>.
impl FromSql for DateTime<UTC> {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<DateTime<UTC>> {
let s = {
let mut s = try!(String::column_result(stmt, col));
if s.len() >= 11 {
let sbytes = s.as_mut_vec();
if sbytes[10] == b' ' {
sbytes[10] = b'T';
}
}
s
};
match DateTime::parse_from_rfc3339(&s) {
Ok(dt) => Ok(dt.with_timezone(&UTC)),
Err(_) => NaiveDateTime::column_result(stmt, col).map(|dt| UTC.from_utc_datetime(&dt)),
}
}
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool {
String::column_has_valid_sqlite_type(stmt, col)
}
}
/// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime<Local>.
impl FromSql for DateTime<Local> {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<DateTime<Local>> {
let utc_dt = try!(DateTime::<UTC>::column_result(stmt, col));
Ok(utc_dt.with_timezone(&Local))
}
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> bool {
DateTime::<UTC>::column_has_valid_sqlite_type(stmt, col)
}
}
#[cfg(test)]
mod test {
use Connection;
use super::chrono::{DateTime, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, UTC,
Duration};
fn checked_memory_handle() -> Connection {
let db = Connection::open_in_memory().unwrap();
db.execute_batch("CREATE TABLE foo (t TEXT, i INTEGER, f FLOAT, b BLOB)").unwrap();
db
}
#[test]
fn test_naive_date() {
let db = checked_memory_handle();
let date = NaiveDate::from_ymd(2016, 2, 23);
db.execute("INSERT INTO foo (t) VALUES (?)", &[&date]).unwrap();
let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!("2016-02-23", s);
let t: NaiveDate = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!(date, t);
}
#[test]
fn test_naive_time() {
let db = checked_memory_handle();
let time = NaiveTime::from_hms(23, 56, 4);
db.execute("INSERT INTO foo (t) VALUES (?)", &[&time]).unwrap();
let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!("23:56:04", s);
let v: NaiveTime = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!(time, v);
}
#[test]
fn test_naive_date_time() {
let db = checked_memory_handle();
let date = NaiveDate::from_ymd(2016, 2, 23);
let time = NaiveTime::from_hms(23, 56, 4);
let dt = NaiveDateTime::new(date, time);
db.execute("INSERT INTO foo (t) VALUES (?)", &[&dt]).unwrap();
let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!("2016-02-23T23:56:04", s);
let v: NaiveDateTime = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!(dt, v);
db.execute("UPDATE foo set b = datetime(t)", &[]).unwrap(); // "YYYY-MM-DD HH:MM:SS"
let hms: NaiveDateTime = db.query_row("SELECT b FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!(dt, hms);
}
#[test]
fn test_date_time_utc() {
let db = checked_memory_handle();
let date = NaiveDate::from_ymd(2016, 2, 23);
let time = NaiveTime::from_hms_milli(23, 56, 4, 789);
let dt = NaiveDateTime::new(date, time);
let utc = UTC.from_utc_datetime(&dt);
db.execute("INSERT INTO foo (t) VALUES (?)", &[&utc]).unwrap();
let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!("2016-02-23T23:56:04.789+00:00", s);
let v1: DateTime<UTC> = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!(utc, v1);
let v2: DateTime<UTC> = db.query_row("SELECT '2016-02-23 23:56:04.789'", &[], |r| r.get(0))
.unwrap();
assert_eq!(utc, v2);
let v3: DateTime<UTC> = db.query_row("SELECT '2016-02-23 23:56:04'", &[], |r| r.get(0))
.unwrap();
assert_eq!(utc - Duration::milliseconds(789), v3);
let v4: DateTime<UTC> =
db.query_row("SELECT '2016-02-23 23:56:04.789+00:00'", &[], |r| r.get(0)).unwrap();
assert_eq!(utc, v4);
}
#[test]
fn test_date_time_local() {
let db = checked_memory_handle();
let date = NaiveDate::from_ymd(2016, 2, 23);
let time = NaiveTime::from_hms_milli(23, 56, 4, 789);
let dt = NaiveDateTime::new(date, time);
let local = Local.from_local_datetime(&dt).single().unwrap();
db.execute("INSERT INTO foo (t) VALUES (?)", &[&local]).unwrap();
// Stored string should be in UTC
let s: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert!(s.ends_with("+00:00"));
let v: DateTime<Local> = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!(local, v);
}
}

View File

@ -52,8 +52,6 @@
//! } //! }
//! ``` //! ```
extern crate time;
use libc::{c_int, c_double, c_char}; use libc::{c_int, c_double, c_char};
use std::ffi::CStr; use std::ffi::CStr;
use std::mem; use std::mem;
@ -66,7 +64,11 @@ pub use ffi::sqlite3_column_type;
pub use ffi::{SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB, SQLITE_NULL}; 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"; mod time;
#[cfg(feature = "chrono")]
mod chrono;
#[cfg(feature = "serde_json")]
mod serde_json;
/// A trait for types that can be converted into SQLite values. /// A trait for types that can be converted into SQLite values.
pub trait ToSql { pub trait ToSql {
@ -102,9 +104,10 @@ raw_to_impl!(c_double, sqlite3_bind_double);
impl ToSql for bool { impl ToSql for bool {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
match *self { if *self {
true => ffi::sqlite3_bind_int(stmt, col, 1), ffi::sqlite3_bind_int(stmt, col, 1)
_ => ffi::sqlite3_bind_int(stmt, col, 0), } else {
ffi::sqlite3_bind_int(stmt, col, 0)
} }
} }
} }
@ -153,13 +156,6 @@ impl ToSql for Vec<u8> {
} }
} }
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> { impl<T: ToSql> ToSql for Option<T> {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
match *self { match *self {
@ -229,7 +225,7 @@ impl FromSql for String {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<String> { unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<String> {
let c_text = ffi::sqlite3_column_text(stmt, col); let c_text = ffi::sqlite3_column_text(stmt, col);
if c_text.is_null() { if c_text.is_null() {
Ok("".to_string()) Ok("".to_owned())
} else { } else {
let c_slice = CStr::from_ptr(c_text as *const c_char).to_bytes(); let c_slice = CStr::from_ptr(c_text as *const c_char).to_bytes();
let utf8_str = try!(str::from_utf8(c_slice)); let utf8_str = try!(str::from_utf8(c_slice));
@ -262,28 +258,12 @@ impl FromSql for Vec<u8> {
} }
} }
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> { impl<T: FromSql> FromSql for Option<T> {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<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 { if sqlite3_column_type(stmt, col) == ffi::SQLITE_NULL {
Ok(None) Ok(None)
} else { } else {
FromSql::column_result(stmt, col).map(|t| Some(t)) FromSql::column_result(stmt, col).map(Some)
} }
} }
@ -312,26 +292,25 @@ pub enum Value {
impl FromSql for Value { impl FromSql for Value {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<Value> { unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<Value> {
match sqlite3_column_type(stmt, col) { match sqlite3_column_type(stmt, col) {
ffi::SQLITE_TEXT => FromSql::column_result(stmt, col).map(|t| Value::Text(t)), ffi::SQLITE_TEXT => FromSql::column_result(stmt, col).map(Value::Text),
ffi::SQLITE_INTEGER => Ok(Value::Integer(ffi::sqlite3_column_int64(stmt, col))), ffi::SQLITE_INTEGER => Ok(Value::Integer(ffi::sqlite3_column_int64(stmt, col))),
ffi::SQLITE_FLOAT => Ok(Value::Real(ffi::sqlite3_column_double(stmt, col))), ffi::SQLITE_FLOAT => Ok(Value::Real(ffi::sqlite3_column_double(stmt, col))),
ffi::SQLITE_NULL => Ok(Value::Null), ffi::SQLITE_NULL => Ok(Value::Null),
ffi::SQLITE_BLOB => FromSql::column_result(stmt, col).map(|t| Value::Blob(t)), ffi::SQLITE_BLOB => FromSql::column_result(stmt, col).map(Value::Blob),
_ => Err(Error::InvalidColumnType), _ => Err(Error::InvalidColumnType),
} }
} }
unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool {
true
}
} }
#[cfg(test)] #[cfg(test)]
#[cfg_attr(feature="clippy", allow(similar_names))]
mod test { mod test {
extern crate time;
use Connection; use Connection;
use super::time;
use Error; use Error;
use libc::{c_int, c_double}; use libc::{c_int, c_double};
use std::f64::EPSILON;
fn checked_memory_handle() -> Connection { fn checked_memory_handle() -> Connection {
let db = Connection::open_in_memory().unwrap(); let db = Connection::open_in_memory().unwrap();
@ -355,26 +334,12 @@ mod test {
let db = checked_memory_handle(); let db = checked_memory_handle();
let s = "hello, world!"; let s = "hello, world!";
db.execute("INSERT INTO foo(t) VALUES (?)", &[&s.to_string()]).unwrap(); db.execute("INSERT INTO foo(t) VALUES (?)", &[&s.to_owned()]).unwrap();
let from: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap(); let from: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!(from, s); 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] #[test]
fn test_option() { fn test_option() {
let db = checked_memory_handle(); let db = checked_memory_handle();
@ -402,6 +367,7 @@ mod test {
} }
#[test] #[test]
#[cfg_attr(feature="clippy", allow(cyclomatic_complexity))]
fn test_mismatched_types() { fn test_mismatched_types() {
fn is_invalid_column_type(err: Error) -> bool { fn is_invalid_column_type(err: Error) -> bool {
match err { match err {
@ -422,54 +388,52 @@ mod test {
let row = rows.next().unwrap().unwrap(); let row = rows.next().unwrap().unwrap();
// check the correct types come back as expected // check the correct types come back as expected
assert_eq!(vec![1, 2], row.get_checked::<i32,Vec<u8>>(0).unwrap()); assert_eq!(vec![1, 2], row.get_checked::<i32, Vec<u8>>(0).unwrap());
assert_eq!("text", row.get_checked::<i32,String>(1).unwrap()); assert_eq!("text", row.get_checked::<i32, String>(1).unwrap());
assert_eq!(1, row.get_checked::<i32,c_int>(2).unwrap()); assert_eq!(1, row.get_checked::<i32, c_int>(2).unwrap());
assert_eq!(1.5, row.get_checked::<i32,c_double>(3).unwrap()); assert!((1.5 - row.get_checked::<i32, c_double>(3).unwrap()).abs() < EPSILON);
assert!(row.get_checked::<i32,Option<c_int>>(4).unwrap().is_none()); assert!(row.get_checked::<i32, Option<c_int>>(4).unwrap().is_none());
assert!(row.get_checked::<i32,Option<c_double>>(4).unwrap().is_none()); assert!(row.get_checked::<i32, Option<c_double>>(4).unwrap().is_none());
assert!(row.get_checked::<i32,Option<String>>(4).unwrap().is_none()); assert!(row.get_checked::<i32, Option<String>>(4).unwrap().is_none());
// check some invalid types // check some invalid types
// 0 is actually a blob (Vec<u8>) // 0 is actually a blob (Vec<u8>)
assert!(is_invalid_column_type(row.get_checked::<i32,c_int>(0).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, c_int>(0).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,c_int>(0).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, c_int>(0).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,i64>(0).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, i64>(0).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,c_double>(0).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, c_double>(0).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,String>(0).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, String>(0).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,time::Timespec>(0).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, time::Timespec>(0).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,Option<c_int>>(0).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, Option<c_int>>(0).err().unwrap()));
// 1 is actually a text (String) // 1 is actually a text (String)
assert!(is_invalid_column_type(row.get_checked::<i32,c_int>(1).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, c_int>(1).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,i64>(1).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, i64>(1).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,c_double>(1).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, c_double>(1).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,Vec<u8>>(1).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, Vec<u8>>(1).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,Option<c_int>>(1).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, Option<c_int>>(1).err().unwrap()));
// 2 is actually an integer // 2 is actually an integer
assert!(is_invalid_column_type(row.get_checked::<i32,c_double>(2).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, c_double>(2).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,String>(2).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, String>(2).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,Vec<u8>>(2).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, Vec<u8>>(2).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,time::Timespec>(2).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, Option<c_double>>(2).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,Option<c_double>>(2).err().unwrap()));
// 3 is actually a float (c_double) // 3 is actually a float (c_double)
assert!(is_invalid_column_type(row.get_checked::<i32,c_int>(3).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, c_int>(3).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,i64>(3).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, i64>(3).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,String>(3).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, String>(3).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,Vec<u8>>(3).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, Vec<u8>>(3).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,time::Timespec>(3).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, Option<c_int>>(3).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,Option<c_int>>(3).err().unwrap()));
// 4 is actually NULL // 4 is actually NULL
assert!(is_invalid_column_type(row.get_checked::<i32,c_int>(4).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, c_int>(4).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,i64>(4).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, i64>(4).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,c_double>(4).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, c_double>(4).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,String>(4).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, String>(4).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,Vec<u8>>(4).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, Vec<u8>>(4).err().unwrap()));
assert!(is_invalid_column_type(row.get_checked::<i32,time::Timespec>(4).err().unwrap())); assert!(is_invalid_column_type(row.get_checked::<i32, time::Timespec>(4).err().unwrap()));
} }
#[test] #[test]
@ -486,11 +450,14 @@ mod test {
let row = rows.next().unwrap().unwrap(); let row = rows.next().unwrap().unwrap();
assert_eq!(Value::Blob(vec![1, 2]), assert_eq!(Value::Blob(vec![1, 2]),
row.get_checked::<i32,Value>(0).unwrap()); row.get_checked::<i32, Value>(0).unwrap());
assert_eq!(Value::Text(String::from("text")), assert_eq!(Value::Text(String::from("text")),
row.get_checked::<i32,Value>(1).unwrap()); row.get_checked::<i32, Value>(1).unwrap());
assert_eq!(Value::Integer(1), row.get_checked::<i32,Value>(2).unwrap()); assert_eq!(Value::Integer(1), row.get_checked::<i32, Value>(2).unwrap());
assert_eq!(Value::Real(1.5), row.get_checked::<i32,Value>(3).unwrap()); match row.get_checked::<i32, Value>(3).unwrap() {
assert_eq!(Value::Null, row.get_checked::<i32,Value>(4).unwrap()); Value::Real(val) => assert!((1.5 - val).abs() < EPSILON),
x => panic!("Invalid Value {:?}", x),
}
assert_eq!(Value::Null, row.get_checked::<i32, Value>(4).unwrap());
} }
} }

66
src/types/serde_json.rs Normal file
View File

@ -0,0 +1,66 @@
//! `ToSql` and `FromSql` implementation for JSON `Value`.
extern crate serde_json;
use libc::c_int;
use self::serde_json::Value;
use {Error, Result};
use types::{FromSql, ToSql};
use ffi;
use ffi::sqlite3_stmt;
use ffi::sqlite3_column_type;
/// Serialize JSON `Value` to text.
impl ToSql for Value {
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
let s = serde_json::to_string(self).unwrap();
s.bind_parameter(stmt, col)
}
}
/// Deserialize text/blob to JSON `Value`.
impl FromSql for Value {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<Value> {
let value_result = match sqlite3_column_type(stmt, col) {
ffi::SQLITE_TEXT => {
let s = try!(String::column_result(stmt, col));
serde_json::from_str(&s)
}
ffi::SQLITE_BLOB => {
let blob = try!(Vec::<u8>::column_result(stmt, col));
serde_json::from_slice(&blob)
}
_ => return Err(Error::InvalidColumnType),
};
value_result.map_err(|err| Error::FromSqlConversionFailure(Box::new(err)))
}
}
#[cfg(test)]
mod test {
use Connection;
use super::serde_json;
fn checked_memory_handle() -> Connection {
let db = Connection::open_in_memory().unwrap();
db.execute_batch("CREATE TABLE foo (t TEXT, b BLOB)").unwrap();
db
}
#[test]
fn test_json_value() {
let db = checked_memory_handle();
let json = r#"{"foo": 13, "bar": "baz"}"#;
let data: serde_json::Value = serde_json::from_str(json).unwrap();
db.execute("INSERT INTO foo (t, b) VALUES (?, ?)",
&[&data, &json.as_bytes()])
.unwrap();
let t: serde_json::Value = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!(data, t);
let b: serde_json::Value = db.query_row("SELECT b FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!(data, b);
}
}

56
src/types/time.rs Normal file
View File

@ -0,0 +1,56 @@
extern crate time;
use libc::c_int;
use {Error, Result};
use types::{FromSql, ToSql};
use ffi::sqlite3_stmt;
const SQLITE_DATETIME_FMT: &'static str = "%Y-%m-%d %H:%M:%S";
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 FromSql for time::Timespec {
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<time::Timespec> {
let s = try!(String::column_result(stmt, col));
match time::strptime(&s, 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)
}
}
#[cfg(test)]
mod test {
use Connection;
use super::time;
fn checked_memory_handle() -> Connection {
let db = Connection::open_in_memory().unwrap();
db.execute_batch("CREATE TABLE foo (t TEXT, i INTEGER, f FLOAT)").unwrap();
db
}
#[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);
}
}