Merge remote-tracking branch 'jgallagher/master' into vtab

This commit is contained in:
gwenn 2016-02-03 18:10:58 +01:00
commit effbf1e395
7 changed files with 197 additions and 200 deletions

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

@ -352,7 +352,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 +370,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

@ -85,13 +85,18 @@ impl fmt::Display for Error {
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 => {
write!(f,
"SQLite was compiled or configured for single-threaded use only")
}
&Error::FromSqlConversionFailure(ref err) => err.fmt(f), &Error::FromSqlConversionFailure(ref err) => err.fmt(f),
&Error::Utf8Error(ref err) => err.fmt(f), &Error::Utf8Error(ref err) => err.fmt(f),
&Error::NulError(ref err) => err.fmt(f), &Error::NulError(ref err) => err.fmt(f),
&Error::InvalidParameterName(ref name) => write!(f, "Invalid parameter name: {}", name), &Error::InvalidParameterName(ref name) => write!(f, "Invalid parameter name: {}", name),
&Error::InvalidPath(ref p) => write!(f, "Invalid path: {}", p.to_string_lossy()), &Error::InvalidPath(ref p) => write!(f, "Invalid path: {}", p.to_string_lossy()),
&Error::ExecuteReturnedResults => write!(f, "Execute returned results - did you mean to call query?"), &Error::ExecuteReturnedResults => {
write!(f, "Execute returned results - did you mean to call query?")
}
&Error::QueryReturnedNoRows => write!(f, "Query returned no rows"), &Error::QueryReturnedNoRows => write!(f, "Query returned no rows"),
&Error::GetFromStaleRow => write!(f, "Attempted to get a value from a stale row"), &Error::GetFromStaleRow => write!(f, "Attempted to get a value from a stale row"),
&Error::InvalidColumnIndex(i) => write!(f, "Invalid column index: {}", i), &Error::InvalidColumnIndex(i) => write!(f, "Invalid column index: {}", i),
@ -111,13 +116,17 @@ impl error::Error for Error {
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 => {
"SQLite was compiled or configured for single-threaded use only"
}
&Error::FromSqlConversionFailure(ref err) => err.description(), &Error::FromSqlConversionFailure(ref err) => err.description(),
&Error::Utf8Error(ref err) => err.description(), &Error::Utf8Error(ref err) => err.description(),
&Error::InvalidParameterName(_) => "invalid parameter name", &Error::InvalidParameterName(_) => "invalid parameter name",
&Error::NulError(ref err) => err.description(), &Error::NulError(ref err) => err.description(),
&Error::InvalidPath(_) => "invalid path", &Error::InvalidPath(_) => "invalid path",
&Error::ExecuteReturnedResults => "execute returned results - did you mean to call query?", &Error::ExecuteReturnedResults => {
"execute returned results - did you mean to call query?"
}
&Error::QueryReturnedNoRows => "query returned no rows", &Error::QueryReturnedNoRows => "query returned no rows",
&Error::GetFromStaleRow => "attempted to get a value from a stale row", &Error::GetFromStaleRow => "attempted to get a value from a stale row",
&Error::InvalidColumnIndex(_) => "invalid column index", &Error::InvalidColumnIndex(_) => "invalid column index",

View File

@ -87,8 +87,8 @@ mod error;
#[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 = "functions")] pub mod functions; #[cfg(feature = "functions")]pub mod functions;
#[cfg(feature = "blob")] pub mod blob; #[cfg(feature = "blob")]pub mod blob;
#[cfg(all(feature = "vtab", feature = "functions"))]pub mod vtab; #[cfg(all(feature = "vtab", feature = "functions"))]pub mod vtab;
/// Old name for `Result`. `SqliteResult` is deprecated. /// Old name for `Result`. `SqliteResult` is deprecated.
@ -183,17 +183,15 @@ 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) let c_path = try!(path_to_cstring(path.as_ref()));
-> Result<Connection> { InnerConnection::open_with_flags(&c_path, flags).map(|db| {
let c_path = try!(path_to_cstring(path.as_ref())); Connection {
InnerConnection::open_with_flags(&c_path, flags).map(|db| { db: RefCell::new(db),
Connection { path: Some(path.as_ref().to_path_buf()),
db: RefCell::new(db), }
path: Some(path.as_ref().to_path_buf()), })
} }
})
}
/// Open a new connection to an in-memory SQLite database. /// Open a new connection to an in-memory SQLite database.
/// ///
@ -250,9 +248,9 @@ impl Connection {
/// 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<'a>(&'a self,
behavior: TransactionBehavior) behavior: TransactionBehavior)
-> Result<Transaction<'a>> { -> Result<Transaction<'a>> {
Transaction::new(self, behavior) Transaction::new(self, behavior)
} }
/// Convenience method to run multiple SQL statements (that cannot take any parameters). /// Convenience method to run multiple SQL statements (that cannot take any parameters).
/// ///
@ -360,7 +358,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>
{ {
@ -391,9 +393,9 @@ impl Connection {
/// does exactly the same thing. /// does exactly the same thing.
pub fn query_row_safe<T, F>(&self, sql: &str, params: &[&ToSql], f: F) -> Result<T> pub fn query_row_safe<T, F>(&self, sql: &str, params: &[&ToSql], f: F) -> Result<T>
where F: FnOnce(Row) -> T where F: FnOnce(Row) -> T
{ {
self.query_row(sql, params, f) self.query_row(sql, params, f)
} }
/// Prepare a SQL statement for execution. /// Prepare a SQL statement for execution.
/// ///
@ -491,9 +493,9 @@ impl Connection {
pub fn load_extension<P: AsRef<Path>>(&self, pub fn load_extension<P: AsRef<Path>>(&self,
dylib_path: P, dylib_path: P,
entry_point: Option<&str>) entry_point: Option<&str>)
-> Result<()> { -> Result<()> {
self.db.borrow_mut().load_extension(dylib_path.as_ref(), entry_point) self.db.borrow_mut().load_extension(dylib_path.as_ref(), entry_point)
} }
/// Get access to the underlying SQLite database connection handle. /// Get access to the underlying SQLite database connection handle.
/// ///
@ -519,8 +521,8 @@ impl Connection {
impl fmt::Debug for Connection { impl fmt::Debug for Connection {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Connection") f.debug_struct("Connection")
.field("path", &self.path) .field("path", &self.path)
.finish() .finish()
} }
} }
@ -555,60 +557,58 @@ 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) unsafe {
-> Result<InnerConnection> { // Before opening the database, we need to check that SQLite hasn't been
unsafe { // compiled or configured to be in single-threaded mode. If it has, we're
// Before opening the database, we need to check that SQLite hasn't been // exposing a very unsafe API to Rust, so refuse to open connections at all.
// compiled or configured to be in single-threaded mode. If it has, we're // Unfortunately, the check for this is quite gross. sqlite3_threadsafe() only
// exposing a very unsafe API to Rust, so refuse to open connections at all. // returns how SQLite was _compiled_; there is no public API to check whether
// Unfortunately, the check for this is quite gross. sqlite3_threadsafe() only // someone called sqlite3_config() to set single-threaded mode. We can cheat
// returns how SQLite was _compiled_; there is no public API to check whether // by trying to allocate a mutex, though; in single-threaded mode due to
// someone called sqlite3_config() to set single-threaded mode. We can cheat // compilation settings, the magic value 8 is returned (see the definition of
// by trying to allocate a mutex, though; in single-threaded mode due to // sqlite3_mutex_alloc at https://github.com/mackyle/sqlite/blob/master/src/mutex.h);
// compilation settings, the magic value 8 is returned (see the definition of // in single-threaded mode due to sqlite3_config(), the magic value 8 is also
// sqlite3_mutex_alloc at https://github.com/mackyle/sqlite/blob/master/src/mutex.h); // returned (see the definition of noopMutexAlloc at
// in single-threaded mode due to sqlite3_config(), the magic value 8 is also // https://github.com/mackyle/sqlite/blob/master/src/mutex_noop.c).
// returned (see the definition of noopMutexAlloc at const SQLITE_SINGLETHREADED_MUTEX_MAGIC: usize = 8;
// https://github.com/mackyle/sqlite/blob/master/src/mutex_noop.c). let mutex_ptr = ffi::sqlite3_mutex_alloc(0);
const SQLITE_SINGLETHREADED_MUTEX_MAGIC: usize = 8; let is_singlethreaded = if mutex_ptr as usize == SQLITE_SINGLETHREADED_MUTEX_MAGIC {
let mutex_ptr = ffi::sqlite3_mutex_alloc(0); true
let is_singlethreaded = if mutex_ptr as usize == SQLITE_SINGLETHREADED_MUTEX_MAGIC { } else {
true false
};
ffi::sqlite3_mutex_free(mutex_ptr);
if is_singlethreaded {
return Err(Error::SqliteSingleThreadedMode);
}
let mut db: *mut ffi::sqlite3 = mem::uninitialized();
let r = ffi::sqlite3_open_v2(c_path.as_ptr(), &mut db, flags.bits(), ptr::null());
if r != ffi::SQLITE_OK {
let e = if db.is_null() {
error_from_sqlite_code(r, None)
} else { } else {
false
};
ffi::sqlite3_mutex_free(mutex_ptr);
if is_singlethreaded {
return Err(Error::SqliteSingleThreadedMode);
}
let mut db: *mut ffi::sqlite3 = mem::uninitialized();
let r = ffi::sqlite3_open_v2(c_path.as_ptr(), &mut db, flags.bits(), ptr::null());
if r != ffi::SQLITE_OK {
let e = if db.is_null() {
error_from_sqlite_code(r, None)
} else {
let e = error_from_handle(db, r);
ffi::sqlite3_close(db);
e
};
return Err(e);
}
let r = ffi::sqlite3_busy_timeout(db, 5000);
if r != ffi::SQLITE_OK {
let e = error_from_handle(db, r); let e = error_from_handle(db, r);
ffi::sqlite3_close(db); ffi::sqlite3_close(db);
return Err(e); e
} };
// attempt to turn on extended results code; don't fail if we can't. return Err(e);
ffi::sqlite3_extended_result_codes(db, 1);
Ok(InnerConnection { db: db })
} }
let r = ffi::sqlite3_busy_timeout(db, 5000);
if r != ffi::SQLITE_OK {
let e = error_from_handle(db, r);
ffi::sqlite3_close(db);
return Err(e);
}
// attempt to turn on extended results code; don't fail if we can't.
ffi::sqlite3_extended_result_codes(db, 1);
Ok(InnerConnection { db: db })
} }
}
fn db(&self) -> *mut ffi::Struct_sqlite3 { fn db(&self) -> *mut ffi::Struct_sqlite3 {
self.db self.db
@ -634,10 +634,10 @@ impl InnerConnection {
let c_sql = try!(str_to_cstring(sql)); let c_sql = try!(str_to_cstring(sql));
unsafe { unsafe {
let r = ffi::sqlite3_exec(self.db(), let r = ffi::sqlite3_exec(self.db(),
c_sql.as_ptr(), c_sql.as_ptr(),
None, None,
ptr::null_mut(), ptr::null_mut(),
ptr::null_mut()); ptr::null_mut());
self.decode_result(r) self.decode_result(r)
} }
} }
@ -676,25 +676,22 @@ 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, if sql.len() >= ::std::i32::MAX as usize {
sql: &str) return Err(error_from_sqlite_code(ffi::SQLITE_TOOBIG, None));
-> Result<Statement<'a>> {
if sql.len() >= ::std::i32::MAX as usize {
return Err(error_from_sqlite_code(ffi::SQLITE_TOOBIG, None));
}
let mut c_stmt: *mut ffi::sqlite3_stmt = unsafe { mem::uninitialized() };
let c_sql = try!(str_to_cstring(sql));
let r = unsafe {
let len_with_nul = (sql.len() + 1) as c_int;
ffi::sqlite3_prepare_v2(self.db(),
c_sql.as_ptr(),
len_with_nul,
&mut c_stmt,
ptr::null_mut())
};
self.decode_result(r).map(|_| Statement::new(conn, c_stmt))
} }
let mut c_stmt: *mut ffi::sqlite3_stmt = unsafe { mem::uninitialized() };
let c_sql = try!(str_to_cstring(sql));
let r = unsafe {
let len_with_nul = (sql.len() + 1) as c_int;
ffi::sqlite3_prepare_v2(self.db(),
c_sql.as_ptr(),
len_with_nul,
&mut c_stmt,
ptr::null_mut())
};
self.decode_result(r).map(|_| Statement::new(conn, c_stmt))
}
fn changes(&mut self) -> c_int { fn changes(&mut self) -> c_int {
unsafe { ffi::sqlite3_changes(self.db()) } unsafe { ffi::sqlite3_changes(self.db()) }
@ -803,7 +800,7 @@ impl<'conn> Statement<'conn> {
} else { } else {
Ok(self.conn.changes()) Ok(self.conn.changes())
} }
}, }
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()),
} }
@ -852,19 +849,16 @@ 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));
Ok(MappedRows { Ok(MappedRows {
rows: row_iter, rows: row_iter,
map: f, map: f,
}) })
} }
/// Executes the prepared statement and maps a function over the resulting /// Executes the prepared statement and maps a function over the resulting
/// rows, where the function returns a `Result` with `Error` type implementing /// rows, where the function returns a `Result` with `Error` type implementing
@ -879,17 +873,17 @@ impl<'conn> Statement<'conn> {
pub fn query_and_then<'a, T, E, F>(&'a mut self, pub fn query_and_then<'a, T, E, F>(&'a mut self,
params: &[&ToSql], params: &[&ToSql],
f: F) f: F)
-> Result<AndThenRows<'a, F>> -> Result<AndThenRows<'a, 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>
{ {
let row_iter = try!(self.query(params)); let row_iter = try!(self.query(params));
Ok(AndThenRows { Ok(AndThenRows {
rows: row_iter, rows: row_iter,
map: f, map: f,
}) })
} }
/// Consumes the statement. /// Consumes the statement.
/// ///
@ -905,9 +899,9 @@ impl<'conn> Statement<'conn> {
unsafe fn bind_parameters(&mut self, params: &[&ToSql]) -> Result<()> { unsafe fn bind_parameters(&mut self, params: &[&ToSql]) -> Result<()> {
assert!(params.len() as c_int == ffi::sqlite3_bind_parameter_count(self.stmt), assert!(params.len() as c_int == ffi::sqlite3_bind_parameter_count(self.stmt),
"incorrect number of parameters to query(): expected {}, got {}", "incorrect number of parameters to query(): expected {}, got {}",
ffi::sqlite3_bind_parameter_count(self.stmt), ffi::sqlite3_bind_parameter_count(self.stmt),
params.len()); params.len());
for (i, p) in params.iter().enumerate() { for (i, p) in params.iter().enumerate() {
try!(self.conn.decode_result(p.bind_parameter(self.stmt, (i + 1) as c_int))); try!(self.conn.decode_result(p.bind_parameter(self.stmt, (i + 1) as c_int)));
@ -939,10 +933,10 @@ impl<'conn> fmt::Debug for Statement<'conn> {
str::from_utf8(c_slice) str::from_utf8(c_slice)
}; };
f.debug_struct("Statement") f.debug_struct("Statement")
.field("conn", self.conn) .field("conn", self.conn)
.field("stmt", &self.stmt) .field("stmt", &self.stmt)
.field("sql", &sql) .field("sql", &sql)
.finish() .finish()
} }
} }
@ -976,15 +970,15 @@ 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>;
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
self.rows.next().map(|row_result| { self.rows.next().map(|row_result| {
row_result.map_err(E::from) row_result.map_err(E::from)
.and_then(|row| (self.map)(&row)) .and_then(|row| (self.map)(&row))
}) })
} }
} }
@ -1232,11 +1226,11 @@ 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() { .iter() {
assert!(Connection::open_in_memory_with_flags(*bad_flags).is_err()); assert!(Connection::open_in_memory_with_flags(*bad_flags).is_err());
} }
} }
#[test] #[test]
@ -1412,7 +1406,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),
} }
@ -1460,7 +1454,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,9 +112,7 @@ 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(); self.reset_if_needed();
try!(self.bind_parameters_named(params)); try!(self.bind_parameters_named(params));
@ -198,8 +190,10 @@ 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> = db.query_row("SELECT y FROM test WHERE x = 'one'",
|row| row.get(0)).unwrap(); &[],
|row| row.get(0))
.unwrap();
assert!(result.is_none()); assert!(result.is_none());
} }
@ -213,8 +207,10 @@ 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 = db.query_row("SELECT x FROM test WHERE y = 'two'",
|row| row.get(0)).unwrap(); &[],
|row| row.get(0))
.unwrap();
assert_eq!(result, "one"); assert_eq!(result, "one");
} }
} }

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",

View File

@ -422,54 +422,54 @@ 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_eq!(1.5, row.get_checked::<i32, c_double>(3).unwrap());
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, 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, 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 +486,11 @@ 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()); assert_eq!(Value::Real(1.5), row.get_checked::<i32, Value>(3).unwrap());
assert_eq!(Value::Null, row.get_checked::<i32,Value>(4).unwrap()); assert_eq!(Value::Null, row.get_checked::<i32, Value>(4).unwrap());
} }
} }